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/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/plugin/resolver_provider.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@deprecated
library analyzer.plugin.resolver_provider;
export 'package:analyzer/src/plugin/resolver_provider.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/plugin/embedded_resolver_provider.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.
@deprecated
library analyzer.plugin.embedded_resolver_provider;
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/source/embedder.dart';
/**
* A function that will return a [UriResolver] that can be used to resolve
* URI's for embedded libraries within a given folder, or `null` if we should
* fall back to the standard URI resolver.
*/
@deprecated
typedef EmbedderUriResolver EmbeddedResolverProvider(Folder folder);
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/error_processor.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:analyzer/error/error.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:analyzer/src/task/options.dart';
import 'package:yaml/yaml.dart';
/// String identifiers mapped to associated severities.
const Map<String, ErrorSeverity> severityMap = const {
'error': ErrorSeverity.ERROR,
'info': ErrorSeverity.INFO,
'warning': ErrorSeverity.WARNING
};
/// Error processor configuration derived from analysis (or embedder) options.
class ErrorConfig {
/// The processors in this config.
final List<ErrorProcessor> processors = <ErrorProcessor>[];
/// Create an error config for the given error code map.
/// For example:
/// new ErrorConfig({'missing_return' : 'error'});
/// will create a processor config that turns `missing_return` hints into
/// errors.
ErrorConfig(YamlNode codeMap) {
_processMap(codeMap);
}
void _process(String code, Object action) {
code = toUpperCase(code);
action = toLowerCase(action);
if (AnalyzerOptions.ignoreSynonyms.contains(action)) {
processors.add(new ErrorProcessor.ignore(code));
} else {
ErrorSeverity severity = _toSeverity(action);
if (severity != null) {
processors.add(new ErrorProcessor(code, severity));
}
}
}
void _processMap(YamlNode codes) {
if (codes is YamlMap) {
codes.nodes.forEach((k, v) {
if (k is YamlScalar && v is YamlScalar) {
_process(k.value, v.value);
}
});
}
}
ErrorSeverity _toSeverity(String severity) => severityMap[severity];
}
/// Process errors by filtering or changing associated [ErrorSeverity].
class ErrorProcessor {
/// The code name of the associated error.
final String code;
/// The desired severity of the processed error.
///
/// If `null`, this processor will "filter" the associated error code.
final ErrorSeverity severity;
/// Create an error processor that assigns errors with this [code] the
/// given [severity].
///
/// If [severity] is `null`, matching errors will be filtered.
ErrorProcessor(this.code, [this.severity]);
/// Create an error processor that ignores the given error by [code].
factory ErrorProcessor.ignore(String code) => new ErrorProcessor(code);
/// The string that unique describes the processor.
String get description => '$code -> ${severity?.name}';
/// Check if this processor applies to the given [error].
///
/// Note: [code] is normalized to uppercase; `errorCode.name` for regular
/// analysis issues uses uppercase; `errorCode.name` for lints uses lowercase.
bool appliesTo(AnalysisError error) =>
code == error.errorCode.name ||
code == error.errorCode.name.toUpperCase();
/// Return an error processor associated in the [analysisOptions] for the
/// given [error], or `null` if none is found.
static ErrorProcessor getProcessor(
AnalysisOptions analysisOptions, AnalysisError error) {
if (analysisOptions == null) {
return null;
}
// Let the user configure how specific errors are processed.
List<ErrorProcessor> processors = analysisOptions.errorProcessors;
// Add the strong mode processor.
processors = processors.toList();
return processors.firstWhere((ErrorProcessor p) => p.appliesTo(error),
orElse: () => null);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/path_filter.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@deprecated
library analyzer.source.path_filter;
export 'package:analyzer/src/source/path_filter.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/source_range.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import "dart:math" as math;
/**
* A source range defines a range of characters within source code.
*/
class SourceRange {
/**
* An empty source range (a range with offset `0` and length `0`).
*/
static const SourceRange EMPTY = const SourceRange(0, 0);
/**
* The 0-based index of the first character of the source range.
*/
final int offset;
/**
* The number of characters in the source range.
*/
final int length;
/**
* Initialize a newly created source range using the given [offset] and
* [length].
*/
const SourceRange(this.offset, this.length);
/**
* Return the 0-based index of the character immediately after this source
* range.
*/
int get end => offset + length;
@override
int get hashCode => 31 * offset + length;
@override
bool operator ==(Object other) {
return other is SourceRange &&
other.offset == offset &&
other.length == length;
}
/**
* Return `true` if [x] is in the interval `[offset, offset + length)`.
*/
bool contains(int x) => offset <= x && x < offset + length;
/**
* Return `true` if [x] is in the interval `(offset, offset + length)`.
*/
bool containsExclusive(int x) => offset < x && x < offset + length;
/**
* Return `true` if the [otherRange] covers this source range.
*/
bool coveredBy(SourceRange otherRange) => otherRange.covers(this);
/**
* Return `true` if this source range covers the [otherRange].
*/
bool covers(SourceRange otherRange) =>
offset <= otherRange.offset && otherRange.end <= end;
/**
* Return `true` if this source range ends inside the [otherRange].
*/
bool endsIn(SourceRange otherRange) {
int thisEnd = end;
return otherRange.contains(thisEnd);
}
/**
* Return a source range covering [delta] characters before the start of this
* source range and [delta] characters after the end of this source range.
*/
SourceRange getExpanded(int delta) =>
new SourceRange(offset - delta, delta + length + delta);
/**
* Return a source range with the same offset as this source range but whose
* length is [delta] characters longer than this source range.
*/
SourceRange getMoveEnd(int delta) => new SourceRange(offset, length + delta);
/**
* Return a source range with the same length as this source range but whose
* offset is [delta] characters after the offset of this source range.
*/
SourceRange getTranslated(int delta) =>
new SourceRange(offset + delta, length);
/**
* Return the minimal source range that covers both this and the [otherRange].
*/
SourceRange getUnion(SourceRange otherRange) {
int newOffset = math.min(offset, otherRange.offset);
int newEnd =
math.max(offset + length, otherRange.offset + otherRange.length);
return new SourceRange(newOffset, newEnd - newOffset);
}
/**
* Return `true` if this source range intersects the [otherRange].
*/
bool intersects(SourceRange otherRange) {
if (otherRange == null) {
return false;
}
if (end <= otherRange.offset) {
return false;
}
if (offset >= otherRange.end) {
return false;
}
return true;
}
/**
* Return `true` if this source range starts in the [otherRange].
*/
bool startsIn(SourceRange otherRange) => otherRange.contains(offset);
@override
String toString() => '[offset=$offset, length=$length]';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/sdk_ext.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@deprecated
library analyzer.source.sdk_ext;
export 'package:analyzer/src/source/sdk_ext.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/embedder.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@deprecated
library analyzer.source.embedder;
import 'dart:collection' show HashMap;
import 'dart:core';
import 'dart:io' as io;
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/source/package_map_provider.dart'
show PackageMapProvider;
import 'package:analyzer/src/generated/java_io.dart' show JavaFile;
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/sdk_io.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart' show FileBasedSource;
import 'package:analyzer/src/summary/idl.dart' show PackageBundle;
import 'package:yaml/yaml.dart';
export 'package:analyzer/src/context/builder.dart' show EmbedderYamlLocator;
const String _DART_COLON_PREFIX = 'dart:';
const String _EMBEDDED_LIB_MAP_KEY = 'embedded_libs';
/// Check if this map defines embedded libraries.
@deprecated
bool definesEmbeddedLibs(Map map) => map[_EMBEDDED_LIB_MAP_KEY] != null;
/// An SDK backed by URI mappings derived from an `_embedder.yaml` file.
@deprecated
class EmbedderSdk extends AbstractDartSdk {
final Map<String, String> _urlMappings = new HashMap<String, String>();
EmbedderSdk([Map<Folder, YamlMap> embedderYamls]) {
embedderYamls?.forEach(_processEmbedderYaml);
}
// TODO(danrubel) Determine SDK version
@override
String get sdkVersion => '0';
/// The url mappings for this SDK.
Map<String, String> get urlMappings => _urlMappings;
@override
PackageBundle getLinkedBundle() => null;
@override
String getRelativePathFromFile(JavaFile file) => file.getAbsolutePath();
@deprecated
@override
PackageBundle getSummarySdkBundle(bool _) => null;
@override
FileBasedSource internalMapDartUri(String dartUri) {
String libraryName;
String relativePath;
int index = dartUri.indexOf('/');
if (index >= 0) {
libraryName = dartUri.substring(0, index);
relativePath = dartUri.substring(index + 1);
} else {
libraryName = dartUri;
relativePath = "";
}
SdkLibrary library = getSdkLibrary(libraryName);
if (library == null) {
return null;
}
String srcPath;
if (relativePath.isEmpty) {
srcPath = library.path;
} else {
String libraryPath = library.path;
int index = libraryPath.lastIndexOf(io.Platform.pathSeparator);
if (index == -1) {
index = libraryPath.lastIndexOf('/');
if (index == -1) {
return null;
}
}
String prefix = libraryPath.substring(0, index + 1);
srcPath = '$prefix$relativePath';
}
String filePath = srcPath.replaceAll('/', io.Platform.pathSeparator);
try {
JavaFile file = new JavaFile(filePath);
return new FileBasedSource(file, Uri.parse(dartUri));
} on FormatException {
return null;
}
}
/// Install the mapping from [name] to [libDir]/[file].
void _processEmbeddedLibs(String name, String file, Folder libDir) {
if (!name.startsWith(_DART_COLON_PREFIX)) {
// SDK libraries must begin with 'dart:'.
return;
}
String libPath = libDir.canonicalizePath(file);
_urlMappings[name] = libPath;
SdkLibraryImpl library = new SdkLibraryImpl(name);
library.path = libPath;
libraryMap.setLibrary(name, library);
}
/// Given the 'embedderYamls' from [EmbedderYamlLocator] check each one for the
/// top level key 'embedded_libs'. Under the 'embedded_libs' key are key value
/// pairs. Each key is a 'dart:' library uri and each value is a path
/// (relative to the directory containing `_embedder.yaml`) to a dart script
/// for the given library. For example:
///
/// embedded_libs:
/// 'dart:io': '../../sdk/io/io.dart'
///
/// If a key doesn't begin with `dart:` it is ignored.
void _processEmbedderYaml(Folder libDir, YamlMap map) {
YamlNode embedded_libs = map[_EMBEDDED_LIB_MAP_KEY];
if (embedded_libs is YamlMap) {
embedded_libs.forEach((k, v) => _processEmbeddedLibs(k, v, libDir));
}
}
}
/// Given the 'embedderYamls' from [EmbedderYamlLocator] check each one for the
/// top level key 'embedded_libs'. Under the 'embedded_libs' key are key value
/// pairs. Each key is a 'dart:' library uri and each value is a path
/// (relative to the directory containing `_embedder.yaml`) to a dart script
/// for the given library. For example:
///
/// embedded_libs:
/// 'dart:io': '../../sdk/io/io.dart'
///
/// If a key doesn't begin with `dart:` it is ignored.
///
/// This class is deprecated; use DartUriResolver directly. In particular, if
/// there used to be an instance creation of the form:
///
/// ```
/// new EmbedderUriResolver(embedderMap)
/// ```
///
/// This should be replaced by
///
/// ```
/// new DartUriResolver(new EmbedderSdk(embedderMap))
/// ```
@deprecated
class EmbedderUriResolver implements DartUriResolver {
EmbedderSdk _embedderSdk;
DartUriResolver _dartUriResolver;
/// Construct a [EmbedderUriResolver] from a package map
/// (see [PackageMapProvider]).
EmbedderUriResolver(Map<Folder, YamlMap> embedderMap)
: this._forSdk(new EmbedderSdk(embedderMap));
/// (Provisional API.)
EmbedderUriResolver._forSdk(this._embedderSdk) {
_dartUriResolver = new DartUriResolver(_embedderSdk);
}
@override
DartSdk get dartSdk => _embedderSdk;
/// Number of embedded libraries.
int get length => _embedderSdk?.urlMappings?.length ?? 0;
@override
void clearCache() {}
@override
Source resolveAbsolute(Uri uri, [Uri actualUri]) =>
_dartUriResolver.resolveAbsolute(uri, actualUri);
@override
Uri restoreAbsolute(Source source) {
String path = source.fullName;
if (path.length > 3 && path[1] == ':' && path[2] == '\\') {
path = '/${path[0]}:${path.substring(2).replaceAll('\\', '/')}';
}
Source sdkSource = dartSdk.fromFileUri(Uri.parse('file://$path'));
return sdkSource?.uri;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/custom_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.
@deprecated
library analyzer.source.custom_resolver;
export 'package:analyzer/src/source/custom_resolver.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/package_map_resolver.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.
@deprecated
library src.source.package_map_provider;
export 'package:analyzer/src/source/package_map_resolver.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/package_map_provider.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.
@deprecated
library analyzer.source.package_map_provider;
export 'package:analyzer/src/source/package_map_provider.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/analysis_options_provider.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@deprecated
library analyzer.src.analysis_options.analysis_options_provider;
export 'package:analyzer/src/analysis_options/analysis_options_provider.dart';
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/source/line_info.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/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
/**
* The location of a character represented as a line and column pair.
*/
// ignore: deprecated_member_use_from_same_package
class CharacterLocation extends LineInfo_Location {
// TODO(brianwilkerson) Replace the body of this class with the body of
// LineInfo_Location and remove LineInfo_Location.
/**
* Initialize a newly created location to represent the location of the
* character at the given [lineNumber] and [columnNumber].
*/
CharacterLocation(int lineNumber, int columnNumber)
: super(lineNumber, columnNumber);
}
/**
* Information about line and column information within a source file.
*/
class LineInfo {
/**
* A list containing the offsets of the first character of each line in the
* source code.
*/
final List<int> lineStarts;
/**
* The zero-based [lineStarts] index resulting from the last call to
* [getLocation].
*/
int _previousLine = 0;
/**
* Initialize a newly created set of line information to represent the data
* encoded in the given list of [lineStarts].
*/
LineInfo(this.lineStarts) {
if (lineStarts == null) {
throw new ArgumentError("lineStarts must be non-null");
} else if (lineStarts.isEmpty) {
throw new ArgumentError("lineStarts must be non-empty");
}
}
/**
* Initialize a newly created set of line information corresponding to the
* given file [content].
*/
factory LineInfo.fromContent(String content) =>
new LineInfo(StringUtilities.computeLineStarts(content));
/**
* The number of lines.
*/
int get lineCount => lineStarts.length;
/**
* Return the location information for the character at the given [offset].
*
* A future version of this API will return a [CharacterLocation] rather than
// ignore: deprecated_member_use_from_same_package
* a [LineInfo_Location].
*/
// ignore: deprecated_member_use_from_same_package
LineInfo_Location getLocation(int offset) {
var min = 0;
var max = lineStarts.length - 1;
// Subsequent calls to [getLocation] are often for offsets near each other.
// To take advantage of that, we cache the index of the line start we found
// when this was last called. If the current offset is on that line or
// later, we'll skip those early indices completely when searching.
if (offset >= lineStarts[_previousLine]) {
min = _previousLine;
// Before kicking off a full binary search, do a quick check here to see
// if the new offset is on that exact line.
if (min == lineStarts.length - 1 || offset < lineStarts[min + 1]) {
return new CharacterLocation(min + 1, offset - lineStarts[min] + 1);
}
}
// Binary search to fine the line containing this offset.
while (min < max) {
var midpoint = (max - min + 1) ~/ 2 + min;
if (lineStarts[midpoint] > offset) {
max = midpoint - 1;
} else {
min = midpoint;
}
}
_previousLine = min;
return new CharacterLocation(min + 1, offset - lineStarts[min] + 1);
}
/**
* Return the offset of the first character on the line with the given
* [lineNumber].
*/
int getOffsetOfLine(int lineNumber) {
if (lineNumber < 0 || lineNumber >= lineCount) {
throw new ArgumentError(
'Invalid line number: $lineNumber; must be between 0 and ${lineCount - 1}');
}
return lineStarts[lineNumber];
}
/**
* Return the offset of the first character on the line following the line
* containing the given [offset].
*/
int getOffsetOfLineAfter(int offset) {
return getOffsetOfLine(getLocation(offset).lineNumber);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/file_system/physical_file_system.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io' as io;
import 'dart:typed_data';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/source/source_resource.dart';
import 'package:path/path.dart';
import 'package:watcher/watcher.dart';
/**
* The name of the directory containing plugin specific subfolders used to store
* data across sessions.
*/
const String _SERVER_DIR = ".dartServer";
/**
* Returns the path to default state location.
*
* Generally this is ~/.dartServer. It can be overridden via the
* ANALYZER_STATE_LOCATION_OVERRIDE environment variable, in which case this
* method will return the contents of that environment variable.
*/
String _getStandardStateLocation() {
final Map<String, String> env = io.Platform.environment;
if (env.containsKey('ANALYZER_STATE_LOCATION_OVERRIDE')) {
return env['ANALYZER_STATE_LOCATION_OVERRIDE'];
}
final home = io.Platform.isWindows ? env['LOCALAPPDATA'] : env['HOME'];
return home != null && io.FileSystemEntity.isDirectorySync(home)
? join(home, _SERVER_DIR)
: null;
}
/**
* Return modification times for every file path in [paths].
*
* If a path is `null`, the modification time is also `null`.
*
* If any exception happens, the file is considered as a not existing and
* `-1` is its modification time.
*/
List<int> _pathsToTimes(List<String> paths) {
return paths.map((path) {
if (path != null) {
try {
io.File file = new io.File(path);
return file.lastModifiedSync().millisecondsSinceEpoch;
} catch (_) {
return -1;
}
} else {
return null;
}
}).toList();
}
/**
* A `dart:io` based implementation of [ResourceProvider].
*/
class PhysicalResourceProvider implements ResourceProvider {
static final String Function(String) NORMALIZE_EOL_ALWAYS =
(String string) => string.replaceAll(new RegExp('\r\n?'), '\n');
static final PhysicalResourceProvider INSTANCE =
new PhysicalResourceProvider(null);
/**
* The path to the base folder where state is stored.
*/
final String _stateLocation;
PhysicalResourceProvider(String Function(String) fileReadMode,
{String stateLocation})
: _stateLocation = stateLocation ?? _getStandardStateLocation() {
if (fileReadMode != null) {
FileBasedSource.fileReadMode = fileReadMode;
}
}
@override
Context get pathContext => context;
@override
File getFile(String path) {
_ensureAbsoluteAndNormalized(path);
return new _PhysicalFile(new io.File(path));
}
@override
Folder getFolder(String path) {
_ensureAbsoluteAndNormalized(path);
return new _PhysicalFolder(new io.Directory(path));
}
@override
Future<List<int>> getModificationTimes(List<Source> sources) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
List<String> paths = sources.map((source) => source.fullName).toList();
return _pathsToTimes(paths);
}
@override
Resource getResource(String path) {
_ensureAbsoluteAndNormalized(path);
if (io.FileSystemEntity.isDirectorySync(path)) {
return getFolder(path);
} else {
return getFile(path);
}
}
@override
Folder getStateLocation(String pluginId) {
if (_stateLocation != null) {
io.Directory directory = new io.Directory(join(_stateLocation, pluginId));
directory.createSync(recursive: true);
return new _PhysicalFolder(directory);
}
return null;
}
/**
* The file system abstraction supports only absolute and normalized paths.
* This method is used to validate any input paths to prevent errors later.
*/
void _ensureAbsoluteAndNormalized(String path) {
assert(() {
if (!pathContext.isAbsolute(path)) {
throw new ArgumentError("Path must be absolute : $path");
}
if (pathContext.normalize(path) != path) {
throw new ArgumentError("Path must be normalized : $path");
}
return true;
}());
}
}
/**
* A `dart:io` based implementation of [File].
*/
class _PhysicalFile extends _PhysicalResource implements File {
_PhysicalFile(io.File file) : super(file);
@override
Stream<WatchEvent> get changes => new FileWatcher(_entry.path).events;
@override
int get lengthSync {
try {
return _file.lengthSync();
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
int get modificationStamp {
try {
return _file.lastModifiedSync().millisecondsSinceEpoch;
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
/**
* Return the underlying file being represented by this wrapper.
*/
io.File get _file => _entry as io.File;
@override
File copyTo(Folder parentFolder) {
parentFolder.create();
File destination = parentFolder.getChildAssumingFile(shortName);
destination.writeAsBytesSync(readAsBytesSync());
return destination;
}
@override
Source createSource([Uri uri]) {
return new FileSource(this, uri ?? pathContext.toUri(path));
}
@override
bool isOrContains(String path) {
return path == this.path;
}
@override
Uint8List readAsBytesSync() {
_throwIfWindowsDeviceDriver();
try {
return _file.readAsBytesSync();
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
String readAsStringSync() {
_throwIfWindowsDeviceDriver();
try {
return FileBasedSource.fileReadMode(_file.readAsStringSync());
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
File renameSync(String newPath) {
try {
return new _PhysicalFile(_file.renameSync(newPath));
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
File resolveSymbolicLinksSync() {
try {
return new _PhysicalFile(new io.File(_file.resolveSymbolicLinksSync()));
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
Uri toUri() => new Uri.file(path);
@override
void writeAsBytesSync(List<int> bytes) {
try {
_file.writeAsBytesSync(bytes);
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
void writeAsStringSync(String content) {
try {
_file.writeAsStringSync(content);
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
}
/**
* A `dart:io` based implementation of [Folder].
*/
class _PhysicalFolder extends _PhysicalResource implements Folder {
_PhysicalFolder(io.Directory directory) : super(directory);
@override
Stream<WatchEvent> get changes =>
new DirectoryWatcher(_entry.path).events.handleError((error) {},
test: (error) => error is io.FileSystemException);
/**
* Return the underlying file being represented by this wrapper.
*/
io.Directory get _directory => _entry as io.Directory;
@override
String canonicalizePath(String relPath) {
return normalize(join(path, relPath));
}
@override
bool contains(String path) {
PhysicalResourceProvider.INSTANCE._ensureAbsoluteAndNormalized(path);
return pathContext.isWithin(this.path, path);
}
@override
Folder copyTo(Folder parentFolder) {
Folder destination = parentFolder.getChildAssumingFolder(shortName);
destination.create();
for (Resource child in getChildren()) {
child.copyTo(destination);
}
return destination;
}
@override
void create() {
_directory.createSync(recursive: true);
}
@override
Resource getChild(String relPath) {
String canonicalPath = canonicalizePath(relPath);
return PhysicalResourceProvider.INSTANCE.getResource(canonicalPath);
}
@override
_PhysicalFile getChildAssumingFile(String relPath) {
String canonicalPath = canonicalizePath(relPath);
io.File file = new io.File(canonicalPath);
return new _PhysicalFile(file);
}
@override
_PhysicalFolder getChildAssumingFolder(String relPath) {
String canonicalPath = canonicalizePath(relPath);
io.Directory directory = new io.Directory(canonicalPath);
return new _PhysicalFolder(directory);
}
@override
List<Resource> getChildren() {
try {
List<Resource> children = <Resource>[];
io.Directory directory = _entry as io.Directory;
List<io.FileSystemEntity> entries = directory.listSync(recursive: false);
int numEntries = entries.length;
for (int i = 0; i < numEntries; i++) {
io.FileSystemEntity entity = entries[i];
if (entity is io.Directory) {
children.add(new _PhysicalFolder(entity));
} else if (entity is io.File) {
children.add(new _PhysicalFile(entity));
}
}
return children;
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
bool isOrContains(String path) {
if (path == this.path) {
return true;
}
return contains(path);
}
@override
Folder resolveSymbolicLinksSync() {
try {
return new _PhysicalFolder(
new io.Directory(_directory.resolveSymbolicLinksSync()));
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
Uri toUri() => new Uri.directory(path);
}
/**
* A `dart:io` based implementation of [Resource].
*/
abstract class _PhysicalResource implements Resource {
final io.FileSystemEntity _entry;
_PhysicalResource(this._entry);
@override
bool get exists => _entry.existsSync();
@override
get hashCode => path.hashCode;
@override
Folder get parent {
String parentPath = pathContext.dirname(path);
if (parentPath == path) {
return null;
}
return new _PhysicalFolder(new io.Directory(parentPath));
}
@override
String get path => _entry.path;
/**
* Return the path context used by this resource provider.
*/
Context get pathContext => io.Platform.isWindows ? windows : posix;
@override
String get shortName => pathContext.basename(path);
@override
bool operator ==(other) {
if (runtimeType != other.runtimeType) {
return false;
}
return path == other.path;
}
@override
void delete() {
try {
_entry.deleteSync(recursive: true);
} on io.FileSystemException catch (exception) {
throw new FileSystemException(exception.path, exception.message);
}
}
@override
String toString() => path;
/**
* If the operating system is Windows and the resource references one of the
* device drivers, throw a [FileSystemException].
*
* https://support.microsoft.com/en-us/kb/74496
*/
void _throwIfWindowsDeviceDriver() {
if (io.Platform.isWindows) {
String shortName = this.shortName.toUpperCase();
if (shortName == r'CON' ||
shortName == r'PRN' ||
shortName == r'AUX' ||
shortName == r'CLOCK$' ||
shortName == r'NUL' ||
shortName == r'COM1' ||
shortName == r'LPT1' ||
shortName == r'LPT2' ||
shortName == r'LPT3' ||
shortName == r'COM2' ||
shortName == r'COM3' ||
shortName == r'COM4') {
throw new FileSystemException(
path, 'Windows device drivers cannot be read.');
}
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/file_system/memory_file_system.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:typed_data';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/source/source_resource.dart';
import 'package:path/path.dart' as pathos;
import 'package:watcher/watcher.dart';
/**
* An in-memory implementation of [ResourceProvider].
* Use `/` as a path separator.
*/
class MemoryResourceProvider implements ResourceProvider {
final Map<String, _MemoryResource> _pathToResource =
new HashMap<String, _MemoryResource>();
final Map<String, Uint8List> _pathToBytes = new HashMap<String, Uint8List>();
final Map<String, int> _pathToTimestamp = new HashMap<String, int>();
final Map<String, List<StreamController<WatchEvent>>> _pathToWatchers =
new HashMap<String, List<StreamController<WatchEvent>>>();
int nextStamp = 0;
final pathos.Context _pathContext;
MemoryResourceProvider(
{pathos.Context context, @deprecated bool isWindows: false})
: _pathContext = (context ??= pathos.style == pathos.Style.windows
// On Windows, ensure that the current drive matches
// the drive inserted by MemoryResourceProvider.convertPath
// so that packages are mapped to the correct drive
? new pathos.Context(current: 'C:\\')
: pathos.context);
@override
pathos.Context get pathContext => _pathContext;
/**
* Convert the given posix [path] to conform to this provider's path context.
*
* This is a utility method for testing; paths passed in to other methods in
* this class are never converted automatically.
*/
String convertPath(String path) {
if (pathContext.style == pathos.windows.style) {
if (path.startsWith(pathos.posix.separator)) {
path = r'C:' + path;
}
path = path.replaceAll(pathos.posix.separator, pathos.windows.separator);
}
return path;
}
/**
* Delete the file with the given path.
*/
void deleteFile(String path) {
_checkFileAtPath(path);
_pathToResource.remove(path);
_pathToBytes.remove(path);
_pathToTimestamp.remove(path);
_notifyWatchers(path, ChangeType.REMOVE);
}
/**
* Delete the folder with the given path
* and recursively delete nested files and folders.
*/
void deleteFolder(String path) {
_checkFolderAtPath(path);
_MemoryFolder folder = _pathToResource[path];
for (Resource child in folder.getChildren()) {
if (child is File) {
deleteFile(child.path);
} else if (child is Folder) {
deleteFolder(child.path);
} else {
throw 'failed to delete resource: $child';
}
}
_pathToResource.remove(path);
_pathToBytes.remove(path);
_pathToTimestamp.remove(path);
_notifyWatchers(path, ChangeType.REMOVE);
}
@override
File getFile(String path) {
_ensureAbsoluteAndNormalized(path);
return new _MemoryFile(this, path);
}
@override
Folder getFolder(String path) {
_ensureAbsoluteAndNormalized(path);
return new _MemoryFolder(this, path);
}
@override
Future<List<int>> getModificationTimes(List<Source> sources) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
return sources.map((source) {
String path = source.fullName;
return _pathToTimestamp[path] ?? -1;
}).toList();
}
@override
Resource getResource(String path) {
_ensureAbsoluteAndNormalized(path);
Resource resource = _pathToResource[path];
if (resource == null) {
resource = new _MemoryFile(this, path);
}
return resource;
}
@override
Folder getStateLocation(String pluginId) {
var path = convertPath('/user/home/$pluginId');
return newFolder(path);
}
void modifyFile(String path, String content) {
_checkFileAtPath(path);
_pathToBytes[path] = utf8.encode(content) as Uint8List;
_pathToTimestamp[path] = nextStamp++;
_notifyWatchers(path, ChangeType.MODIFY);
}
/**
* Create a resource representing a dummy link (that is, a File object which
* appears in its parent directory, but whose `exists` property is false)
*/
File newDummyLink(String path) {
_ensureAbsoluteAndNormalized(path);
newFolder(pathContext.dirname(path));
_MemoryDummyLink link = new _MemoryDummyLink(this, path);
_pathToResource[path] = link;
_pathToTimestamp[path] = nextStamp++;
_notifyWatchers(path, ChangeType.ADD);
return link;
}
File newFile(String path, String content, [int stamp]) {
_ensureAbsoluteAndNormalized(path);
_MemoryFile file = _newFile(path);
_pathToBytes[path] = utf8.encode(content) as Uint8List;
_pathToTimestamp[path] = stamp ?? nextStamp++;
_notifyWatchers(path, ChangeType.ADD);
return file;
}
File newFileWithBytes(String path, List<int> bytes, [int stamp]) {
_ensureAbsoluteAndNormalized(path);
_MemoryFile file = _newFile(path);
_pathToBytes[path] = Uint8List.fromList(bytes);
_pathToTimestamp[path] = stamp ?? nextStamp++;
_notifyWatchers(path, ChangeType.ADD);
return file;
}
Folder newFolder(String path) {
_ensureAbsoluteAndNormalized(path);
if (!pathContext.isAbsolute(path)) {
throw new ArgumentError("Path must be absolute : $path");
}
_MemoryResource resource = _pathToResource[path];
if (resource == null) {
String parentPath = pathContext.dirname(path);
if (parentPath != path) {
newFolder(parentPath);
}
_MemoryFolder folder = new _MemoryFolder(this, path);
_pathToResource[path] = folder;
_pathToTimestamp[path] = nextStamp++;
_notifyWatchers(path, ChangeType.ADD);
return folder;
} else if (resource is _MemoryFolder) {
_notifyWatchers(path, ChangeType.ADD);
return resource;
} else {
String message =
'Folder expected at ' "'$path'" 'but ${resource.runtimeType} found';
throw new ArgumentError(message);
}
}
File updateFile(String path, String content, [int stamp]) {
_ensureAbsoluteAndNormalized(path);
newFolder(pathContext.dirname(path));
_MemoryFile file = new _MemoryFile(this, path);
_pathToResource[path] = file;
_pathToBytes[path] = utf8.encode(content) as Uint8List;
_pathToTimestamp[path] = stamp ?? nextStamp++;
_notifyWatchers(path, ChangeType.MODIFY);
return file;
}
/**
* Write a representation of the file system on the given [sink].
*/
void writeOn(StringSink sink) {
List<String> paths = _pathToResource.keys.toList();
paths.sort();
paths.forEach(sink.writeln);
}
void _checkFileAtPath(String path) {
// TODO(brianwilkerson) Consider throwing a FileSystemException rather than
// an ArgumentError.
_MemoryResource resource = _pathToResource[path];
if (resource is! _MemoryFile) {
if (resource == null) {
throw new ArgumentError('File expected at "$path" but does not exist');
}
throw new ArgumentError(
'File expected at "$path" but ${resource.runtimeType} found');
}
}
void _checkFolderAtPath(String path) {
// TODO(brianwilkerson) Consider throwing a FileSystemException rather than
// an ArgumentError.
_MemoryResource resource = _pathToResource[path];
if (resource is! _MemoryFolder) {
throw new ArgumentError(
'Folder expected at "$path" but ${resource.runtimeType} found');
}
}
/**
* The file system abstraction supports only absolute and normalized paths.
* This method is used to validate any input paths to prevent errors later.
*/
void _ensureAbsoluteAndNormalized(String path) {
if (!pathContext.isAbsolute(path)) {
throw new ArgumentError("Path must be absolute : $path");
}
if (pathContext.normalize(path) != path) {
throw new ArgumentError("Path must be normalized : $path");
}
}
/**
* Create a new [_MemoryFile] without any content.
*/
_MemoryFile _newFile(String path) {
String folderPath = pathContext.dirname(path);
_MemoryResource folder = _pathToResource[folderPath];
if (folder == null) {
newFolder(folderPath);
} else if (folder is! Folder) {
throw new ArgumentError('Cannot create file ($path) as child of file');
}
_MemoryFile file = new _MemoryFile(this, path);
_pathToResource[path] = file;
return file;
}
void _notifyWatchers(String path, ChangeType changeType) {
_pathToWatchers.forEach((String watcherPath,
List<StreamController<WatchEvent>> streamControllers) {
if (watcherPath == path || pathContext.isWithin(watcherPath, path)) {
for (StreamController<WatchEvent> streamController
in streamControllers) {
streamController.add(new WatchEvent(changeType, path));
}
}
});
}
_MemoryFile _renameFileSync(_MemoryFile file, String newPath) {
String path = file.path;
if (newPath == path) {
return file;
}
_MemoryResource existingNewResource = _pathToResource[newPath];
if (existingNewResource is _MemoryFolder) {
throw new FileSystemException(
path, 'Could not be renamed: $newPath is a folder.');
}
_MemoryFile newFile = _newFile(newPath);
_pathToResource.remove(path);
_pathToBytes[newPath] = _pathToBytes.remove(path);
_pathToTimestamp[newPath] = _pathToTimestamp.remove(path);
if (existingNewResource != null) {
_notifyWatchers(newPath, ChangeType.REMOVE);
}
_notifyWatchers(path, ChangeType.REMOVE);
_notifyWatchers(newPath, ChangeType.ADD);
return newFile;
}
void _setFileContent(_MemoryFile file, List<int> bytes) {
String path = file.path;
_pathToResource[path] = file;
_pathToBytes[path] = Uint8List.fromList(bytes);
_pathToTimestamp[path] = nextStamp++;
_notifyWatchers(path, ChangeType.MODIFY);
}
}
/**
* An in-memory implementation of [File] which acts like a symbolic link to a
* non-existent file.
*/
class _MemoryDummyLink extends _MemoryResource implements File {
_MemoryDummyLink(MemoryResourceProvider provider, String path)
: super(provider, path);
@override
Stream<WatchEvent> get changes {
throw new FileSystemException(path, "File does not exist");
}
@override
bool get exists => false;
@override
int get lengthSync {
throw new FileSystemException(path, 'File could not be read');
}
@override
int get modificationStamp {
int stamp = _provider._pathToTimestamp[path];
if (stamp == null) {
throw new FileSystemException(path, "File does not exist");
}
return stamp;
}
@override
File copyTo(Folder parentFolder) {
throw new FileSystemException(path, 'File could not be copied');
}
@override
Source createSource([Uri uri]) {
throw new FileSystemException(path, 'File could not be read');
}
@override
void delete() {
throw new FileSystemException(path, 'File could not be deleted');
}
@override
bool isOrContains(String path) {
return path == this.path;
}
@override
Uint8List readAsBytesSync() {
throw new FileSystemException(path, 'File could not be read');
}
@override
String readAsStringSync() {
throw new FileSystemException(path, 'File could not be read');
}
@override
File renameSync(String newPath) {
throw new FileSystemException(path, 'File could not be renamed');
}
@override
File resolveSymbolicLinksSync() {
return throw new FileSystemException(path, "File does not exist");
}
@override
void writeAsBytesSync(List<int> bytes) {
throw new FileSystemException(path, 'File could not be written');
}
@override
void writeAsStringSync(String content) {
throw new FileSystemException(path, 'File could not be written');
}
}
/**
* An in-memory implementation of [File].
*/
class _MemoryFile extends _MemoryResource implements File {
_MemoryFile(MemoryResourceProvider provider, String path)
: super(provider, path);
@override
bool get exists => _provider._pathToResource[path] is _MemoryFile;
@override
int get lengthSync {
return readAsBytesSync().length;
}
@override
int get modificationStamp {
int stamp = _provider._pathToTimestamp[path];
if (stamp == null) {
throw new FileSystemException(path, 'File "$path" does not exist.');
}
return stamp;
}
@override
File copyTo(Folder parentFolder) {
parentFolder.create();
File destination = parentFolder.getChildAssumingFile(shortName);
destination.writeAsBytesSync(readAsBytesSync());
return destination;
}
@override
Source createSource([Uri uri]) {
uri ??= _provider.pathContext.toUri(path);
return new FileSource(this, uri);
}
@override
void delete() {
_provider.deleteFile(path);
}
@override
bool isOrContains(String path) {
return path == this.path;
}
@override
Uint8List readAsBytesSync() {
Uint8List content = _provider._pathToBytes[path];
if (content == null) {
throw new FileSystemException(path, 'File "$path" does not exist.');
}
return content;
}
@override
String readAsStringSync() {
Uint8List content = _provider._pathToBytes[path];
if (content == null) {
throw new FileSystemException(path, 'File "$path" does not exist.');
}
return utf8.decode(content);
}
@override
File renameSync(String newPath) {
return _provider._renameFileSync(this, newPath);
}
@override
File resolveSymbolicLinksSync() => this;
@override
void writeAsBytesSync(List<int> bytes) {
_provider._setFileContent(this, bytes);
}
@override
void writeAsStringSync(String content) {
_provider._setFileContent(this, utf8.encode(content));
}
}
/**
* An in-memory implementation of [Folder].
*/
class _MemoryFolder extends _MemoryResource implements Folder {
_MemoryFolder(MemoryResourceProvider provider, String path)
: super(provider, path);
@override
bool get exists => _provider._pathToResource[path] is _MemoryFolder;
@override
String canonicalizePath(String relPath) {
relPath = _provider.pathContext.normalize(relPath);
String childPath = _provider.pathContext.join(path, relPath);
childPath = _provider.pathContext.normalize(childPath);
return childPath;
}
@override
bool contains(String path) {
return _provider.pathContext.isWithin(this.path, path);
}
@override
Folder copyTo(Folder parentFolder) {
Folder destination = parentFolder.getChildAssumingFolder(shortName);
destination.create();
for (Resource child in getChildren()) {
child.copyTo(destination);
}
return destination;
}
@override
void create() {
_provider.newFolder(path);
}
@override
void delete() {
_provider.deleteFolder(path);
}
@override
Resource getChild(String relPath) {
String childPath = canonicalizePath(relPath);
_MemoryResource resource = _provider._pathToResource[childPath];
if (resource == null) {
resource = new _MemoryFile(_provider, childPath);
}
return resource;
}
@override
_MemoryFile getChildAssumingFile(String relPath) {
String childPath = canonicalizePath(relPath);
_MemoryResource resource = _provider._pathToResource[childPath];
if (resource is _MemoryFile) {
return resource;
}
return new _MemoryFile(_provider, childPath);
}
@override
_MemoryFolder getChildAssumingFolder(String relPath) {
String childPath = canonicalizePath(relPath);
_MemoryResource resource = _provider._pathToResource[childPath];
if (resource is _MemoryFolder) {
return resource;
}
return new _MemoryFolder(_provider, childPath);
}
@override
List<Resource> getChildren() {
if (!exists) {
throw new FileSystemException(path, 'Folder does not exist.');
}
List<Resource> children = <Resource>[];
_provider._pathToResource.forEach((resourcePath, resource) {
if (_provider.pathContext.dirname(resourcePath) == path) {
children.add(resource);
}
});
return children;
}
@override
bool isOrContains(String path) {
if (path == this.path) {
return true;
}
return contains(path);
}
@override
Folder resolveSymbolicLinksSync() => this;
@override
Uri toUri() => _provider.pathContext.toUri(path + '/');
}
/**
* An in-memory implementation of [Resource].
*/
abstract class _MemoryResource implements Resource {
final MemoryResourceProvider _provider;
@override
final String path;
_MemoryResource(this._provider, this.path);
Stream<WatchEvent> get changes {
StreamController<WatchEvent> streamController =
new StreamController<WatchEvent>();
if (!_provider._pathToWatchers.containsKey(path)) {
_provider._pathToWatchers[path] = <StreamController<WatchEvent>>[];
}
_provider._pathToWatchers[path].add(streamController);
streamController.done.then((_) {
_provider._pathToWatchers[path].remove(streamController);
if (_provider._pathToWatchers[path].isEmpty) {
_provider._pathToWatchers.remove(path);
}
});
return streamController.stream;
}
@override
get hashCode => path.hashCode;
@override
Folder get parent {
String parentPath = _provider.pathContext.dirname(path);
if (parentPath == path) {
return null;
}
return _provider.getFolder(parentPath);
}
@override
String get shortName => _provider.pathContext.basename(path);
@override
bool operator ==(other) {
if (runtimeType != other.runtimeType) {
return false;
}
return path == other.path;
}
@override
String toString() => path;
@override
Uri toUri() => _provider.pathContext.toUri(path);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/file_system/file_system.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:analyzer/src/generated/source.dart';
import 'package:path/path.dart';
import 'package:watcher/watcher.dart';
export 'package:analyzer/src/file_system/file_system.dart';
/**
* [File]s are leaf [Resource]s which contain data.
*/
abstract class File implements Resource {
/**
* Watch for changes to this file
*/
Stream<WatchEvent> get changes;
/**
* Synchronously get the length of the file.
* Throws a [FileSystemException] if the operation fails.
*/
int get lengthSync;
/**
* Return the last-modified stamp of the file.
* Throws a [FileSystemException] if the file does not exist.
*/
int get modificationStamp;
@override
File copyTo(Folder parentFolder);
/**
* Create a new [Source] instance that serves this file.
*/
Source createSource([Uri uri]);
/**
* Synchronously read the entire file contents as a list of bytes.
* Throws a [FileSystemException] if the operation fails.
*/
List<int> readAsBytesSync();
/**
* Synchronously read the entire file contents as a [String].
* Throws [FileSystemException] if the file does not exist.
*/
String readAsStringSync();
/**
* Synchronously rename this file.
* Return a [File] instance for the renamed file.
*
* The [newPath] must be absolute and normalized.
*
* If [newPath] identifies an existing file, that file is replaced.
* If [newPath] identifies an existing resource the operation might fail and
* an exception is thrown.
*/
File renameSync(String newPath);
/**
* Synchronously write the given [bytes] to the file. The new content will
* replace any existing content.
*
* Throws a [FileSystemException] if the operation fails.
*/
void writeAsBytesSync(List<int> bytes);
/**
* Synchronously write the given [content] to the file. The new content will
* replace any existing content.
*
* Throws a [FileSystemException] if the operation fails.
*/
void writeAsStringSync(String content);
}
/**
* Base class for all file system exceptions.
*/
class FileSystemException implements Exception {
final String path;
final String message;
FileSystemException(this.path, this.message);
@override
String toString() => 'FileSystemException(path=$path; message=$message)';
}
/**
* [Folder]s are [Resource]s which may contain files and/or other folders.
*/
abstract class Folder implements Resource {
/**
* Watch for changes to the files inside this folder (and in any nested
* folders, including folders reachable via links).
*/
Stream<WatchEvent> get changes;
/**
* If the path [path] is a relative path, convert it to an absolute path
* by interpreting it relative to this folder. If it is already an absolute
* path, then don't change it.
*
* However, regardless of whether [path] is relative or absolute, normalize
* it by removing path components of the form '.' or '..'.
*/
String canonicalizePath(String path);
/**
* Return `true` if the [path] references a resource in this folder.
*
* The [path] must be absolute and normalized.
*/
bool contains(String path);
@override
Folder copyTo(Folder parentFolder);
/**
* If this folder does not already exist, create it.
*/
void create();
/**
* Return an existing child [Resource] with the given [relPath].
* Return a not existing [File] if no such child exist.
*/
Resource getChild(String relPath);
/**
* Return a [File] representing a child [Resource] with the given
* [relPath]. This call does not check whether a file with the given name
* exists on the filesystem - client must call the [File]'s `exists` getter
* to determine whether the folder actually exists.
*/
File getChildAssumingFile(String relPath);
/**
* Return a [Folder] representing a child [Resource] with the given
* [relPath]. This call does not check whether a folder with the given name
* exists on the filesystem--client must call the [Folder]'s `exists` getter
* to determine whether the folder actually exists.
*/
Folder getChildAssumingFolder(String relPath);
/**
* Return a list of existing direct children [Resource]s (folders and files)
* in this folder, in no particular order.
*
* On I/O errors, this will throw [FileSystemException].
*/
List<Resource> getChildren();
}
/**
* The abstract class [Resource] is an abstraction of file or folder.
*/
abstract class Resource {
/**
* Return `true` if this resource exists.
*/
bool get exists;
/**
* Return the [Folder] that contains this resource, or `null` if this resource
* is a root folder.
*/
Folder get parent;
/**
* Return the full path to this resource.
*/
String get path;
/**
* Return a short version of the name that can be displayed to the user to
* denote this resource.
*/
String get shortName;
/**
* Copy this resource to a child of the [parentFolder] with the same kind and
* [shortName] as this resource. If this resource is a folder, then all of the
* contents of the folder will be recursively copied.
*
* The parent folder is created if it does not already exist.
*
* Existing files and folders will be overwritten.
*
* Return the resource corresponding to this resource in the parent folder.
*/
Resource copyTo(Folder parentFolder);
/**
* Synchronously deletes this resource and its children.
*
* Throws an exception if the resource cannot be deleted.
*/
void delete();
/**
* Return `true` if absolute [path] references this resource or a resource in
* this folder.
*
* The [path] must be absolute and normalized.
*/
bool isOrContains(String path);
/**
* Return a resource that refers to the same resource as this resource, but
* whose path does not contain any symbolic links.
*/
Resource resolveSymbolicLinksSync();
/**
* Return a Uri representing this resource.
*/
Uri toUri();
}
/**
* Instances of the class [ResourceProvider] convert [String] paths into
* [Resource]s.
*/
abstract class ResourceProvider {
/**
* Get the path context used by this resource provider.
*/
Context get pathContext;
/**
* Return a [File] that corresponds to the given [path].
*
* The [path] must be absolute and normalized.
*
* A file may or may not exist at this location.
*/
File getFile(String path);
/**
* Return a [Folder] that corresponds to the given [path].
*
* The [path] must be absolute and normalized.
*
* A folder may or may not exist at this location.
*/
Folder getFolder(String path);
/**
* Complete with a list of modification times for the given [sources].
*
* If the file of a source is not managed by this provider, return `null`.
* If the file a source does not exist, return `-1`.
*/
Future<List<int>> getModificationTimes(List<Source> sources);
/**
* Return the [Resource] that corresponds to the given [path].
*
* The [path] must be absolute and normalized.
*/
Resource getResource(String path);
/**
* Return the folder in which the plugin with the given [pluginId] can store
* state that will persist across sessions. The folder returned for a given id
* will not be returned for a different id, ensuring that plugins do not need
* to be concerned with file name collisions with other plugins, assuming that
* the plugin ids are unique. The plugin ids must be valid folder names.
*/
Folder getStateLocation(String pluginId);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/file_system/overlay_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 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'dart:typed_data';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/source/source_resource.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as pathos;
import 'package:watcher/watcher.dart';
/**
* A resource provider that allows clients to overlay the file system provided
* by a base resource provider. These overlays allow both the contents and
* modification stamps of files to be different than what the base resource
* provider would report.
*
* This provider does not report watch events when overlays are added, modified
* or removed.
*/
class OverlayResourceProvider implements ResourceProvider {
/**
* The underlying resource provider used to access files and folders that
* do not have an overlay.
*/
final ResourceProvider baseProvider;
/**
* A map from the paths of files for which there is an overlay to the contents
* of the files.
*/
final Map<String, String> _overlayContent = <String, String>{};
/**
* A map from the paths of files for which there is an overlay to the
* modification stamps of the files.
*/
final Map<String, int> _overlayModificationStamps = <String, int>{};
/**
* Initialize a newly created resource provider to represent an overlay on the
* given [baseProvider].
*/
OverlayResourceProvider(this.baseProvider);
@override
pathos.Context get pathContext => baseProvider.pathContext;
@override
File getFile(String path) =>
new _OverlayFile(this, baseProvider.getFile(path));
@override
Folder getFolder(String path) =>
new _OverlayFolder(this, baseProvider.getFolder(path));
@override
Future<List<int>> getModificationTimes(List<Source> sources) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
return sources.map((source) {
String path = source.fullName;
return _overlayModificationStamps[path] ??
baseProvider.getFile(path).modificationStamp;
}).toList();
}
@override
Resource getResource(String path) {
if (hasOverlay(path)) {
return new _OverlayResource._from(this, baseProvider.getFile(path));
} else if (_hasOverlayIn(path)) {
return new _OverlayResource._from(this, baseProvider.getFolder(path));
}
return new _OverlayResource._from(this, baseProvider.getResource(path));
}
@override
Folder getStateLocation(String pluginId) =>
new _OverlayFolder(this, baseProvider.getStateLocation(pluginId));
/**
* Return `true` if there is an overlay associated with the file at the given
* [path].
*/
bool hasOverlay(String path) => _overlayContent.containsKey(path);
/**
* Remove any overlay of the file at the given [path]. The state of the file
* in the base resource provider will not be affected.
*/
bool removeOverlay(String path) {
bool hadOverlay = _overlayContent.containsKey(path);
_overlayContent.remove(path);
_overlayModificationStamps.remove(path);
return hadOverlay;
}
/**
* Overlay the content of the file at the given [path]. The file will appear
* to have the given [content] and [modificationStamp] even if the file is
* modified in the base resource provider.
*/
void setOverlay(String path,
{@required String content, @required int modificationStamp}) {
if (content == null) {
throw new ArgumentError(
'OverlayResourceProvider.setOverlay: content cannot be null');
} else if (modificationStamp == null) {
throw new ArgumentError(
'OverlayResourceProvider.setOverlay: modificationStamp cannot be null');
}
_overlayContent[path] = content;
_overlayModificationStamps[path] = modificationStamp;
}
/**
* Copy any overlay for the file at the [oldPath] to be an overlay for the
* file with the [newPath].
*/
void _copyOverlay(String oldPath, String newPath) {
if (hasOverlay(oldPath)) {
_overlayContent[newPath] = _overlayContent[oldPath];
_overlayModificationStamps[newPath] = _overlayModificationStamps[oldPath];
}
}
/**
* Return the content of the overlay of the file at the given [path], or
* `null` if there is no overlay for the specified file.
*/
String _getOverlayContent(String path) {
return _overlayContent[path];
}
/**
* Return the modification stamp of the overlay of the file at the given
* [path], or `null` if there is no overlay for the specified file.
*/
int _getOverlayModificationStamp(String path) {
return _overlayModificationStamps[path];
}
/**
* Return `true` if there is an overlay associated with at least one file
* contained inside the folder with the given [folderPath].
*/
bool _hasOverlayIn(String folderPath) => _overlayContent.keys
.any((filePath) => pathContext.isWithin(folderPath, filePath));
/**
* Return the paths of all of the overlaid files that are children of the
* given [folder], either directly or indirectly.
*/
Iterable<String> _overlaysInFolder(String folderPath) => _overlayContent.keys
.where((filePath) => pathContext.isWithin(folderPath, filePath));
}
/**
* A file from an [OverlayResourceProvider].
*/
class _OverlayFile extends _OverlayResource implements File {
/**
* Initialize a newly created file to have the given [provider] and to
* correspond to the given [file] from the provider's base resource provider.
*/
_OverlayFile(OverlayResourceProvider provider, File file)
: super(provider, file);
@override
Stream<WatchEvent> get changes => _file.changes;
@override
bool get exists => _provider.hasOverlay(path) || _resource.exists;
@override
int get lengthSync {
String content = _provider._getOverlayContent(path);
if (content != null) {
return content.length;
}
return _file.lengthSync;
}
@override
int get modificationStamp {
int stamp = _provider._getOverlayModificationStamp(path);
if (stamp != null) {
return stamp;
}
return _file.modificationStamp;
}
/**
* Return the file from the base resource provider that corresponds to this
* folder.
*/
File get _file => _resource as File;
@override
File copyTo(Folder parentFolder) {
String newPath = _provider.pathContext.join(parentFolder.path, shortName);
_provider._copyOverlay(path, newPath);
if (_file.exists) {
if (parentFolder is _OverlayFolder) {
return new _OverlayFile(_provider, _file.copyTo(parentFolder._folder));
}
return new _OverlayFile(_provider, _file.copyTo(parentFolder));
} else {
return new _OverlayFile(
_provider, _provider.baseProvider.getFile(newPath));
}
}
@override
Source createSource([Uri uri]) =>
new FileSource(this, uri ?? _provider.pathContext.toUri(path));
@override
void delete() {
bool hadOverlay = _provider.removeOverlay(path);
if (_resource.exists) {
_resource.delete();
} else if (!hadOverlay) {
throw new FileSystemException(path, 'does not exist');
}
}
@override
Uint8List readAsBytesSync() {
String content = _provider._getOverlayContent(path);
if (content != null) {
return utf8.encode(content) as Uint8List;
}
return _file.readAsBytesSync();
}
@override
String readAsStringSync() {
String content = _provider._getOverlayContent(path);
if (content != null) {
return content;
}
return _file.readAsStringSync();
}
@override
File renameSync(String newPath) {
File newFile = _file.renameSync(newPath);
if (_provider.hasOverlay(path)) {
_provider.setOverlay(newPath,
content: _provider._getOverlayContent(path),
modificationStamp: _provider._getOverlayModificationStamp(path));
_provider.removeOverlay(path);
}
return new _OverlayFile(_provider, newFile);
}
@override
void writeAsBytesSync(List<int> bytes) {
writeAsStringSync(new String.fromCharCodes(bytes));
}
@override
void writeAsStringSync(String content) {
if (_provider.hasOverlay(path)) {
throw new FileSystemException(
path, 'Cannot write a file with an overlay');
}
_file.writeAsStringSync(content);
}
}
/**
* A folder from an [OverlayResourceProvider].
*/
class _OverlayFolder extends _OverlayResource implements Folder {
/**
* Initialize a newly created folder to have the given [provider] and to
* correspond to the given [folder] from the provider's base resource
* provider.
*/
_OverlayFolder(OverlayResourceProvider provider, Folder folder)
: super(provider, folder);
@override
Stream<WatchEvent> get changes => _folder.changes;
@override
bool get exists => _provider._hasOverlayIn(path) || _resource.exists;
/**
* Return the folder from the base resource provider that corresponds to this
* folder.
*/
Folder get _folder => _resource as Folder;
@override
String canonicalizePath(String relPath) {
pathos.Context context = _provider.pathContext;
relPath = context.normalize(relPath);
String childPath = context.join(path, relPath);
childPath = context.normalize(childPath);
return childPath;
}
@override
bool contains(String path) => _folder.contains(path);
@override
Folder copyTo(Folder parentFolder) {
Folder destination = parentFolder.getChildAssumingFolder(shortName);
destination.create();
for (Resource child in getChildren()) {
child.copyTo(destination);
}
return destination;
}
@override
void create() {
_folder.create();
}
@override
Resource getChild(String relPath) =>
new _OverlayResource._from(_provider, _folder.getChild(relPath));
@override
File getChildAssumingFile(String relPath) =>
new _OverlayFile(_provider, _folder.getChildAssumingFile(relPath));
@override
Folder getChildAssumingFolder(String relPath) =>
new _OverlayFolder(_provider, _folder.getChildAssumingFolder(relPath));
@override
List<Resource> getChildren() {
Map<String, Resource> children = {};
try {
for (final child in _folder.getChildren()) {
children[child.path] = new _OverlayResource._from(_provider, child);
}
} on FileSystemException {
// We don't want to throw if we're a folder that only exists in the overlay
// and not on disk.
}
for (String overlayPath in _provider._overlaysInFolder(path)) {
pathos.Context context = _provider.pathContext;
if (context.dirname(overlayPath) == path) {
children.putIfAbsent(overlayPath, () => _provider.getFile(overlayPath));
} else {
String relativePath = context.relative(overlayPath, from: path);
String folderName = context.split(relativePath)[0];
String folderPath = context.join(path, folderName);
children.putIfAbsent(folderPath, () => _provider.getFolder(folderPath));
}
}
return children.values.toList();
}
}
/**
* The base class for resources from an [OverlayResourceProvider].
*/
abstract class _OverlayResource implements Resource {
/**
* The resource provider associated with this resource.
*/
final OverlayResourceProvider _provider;
/**
* The resource from the provider's base provider that corresponds to this
* resource.
*/
final Resource _resource;
/**
* Initialize a newly created instance of a resource to have the given
* [_provider] and to represent the [_resource] from the provider's base
* resource provider.
*/
_OverlayResource(this._provider, this._resource);
/**
* Return an instance of the subclass of this class corresponding to the given
* [resource] that is associated with the given [provider].
*/
factory _OverlayResource._from(
OverlayResourceProvider provider, Resource resource) {
if (resource is Folder) {
return new _OverlayFolder(provider, resource);
} else if (resource is File) {
return new _OverlayFile(provider, resource);
}
throw new ArgumentError('Unknown resource type: ${resource.runtimeType}');
}
@override
int get hashCode => path.hashCode;
@override
Folder get parent {
Folder parent = _resource.parent;
if (parent == null) {
return null;
}
return new _OverlayFolder(_provider, parent);
}
@override
String get path => _resource.path;
@override
String get shortName => _resource.shortName;
@override
bool operator ==(other) {
if (runtimeType != other.runtimeType) {
return false;
}
return path == other.path;
}
@override
void delete() {
_resource.delete();
}
@override
bool isOrContains(String path) {
return _resource.isOrContains(path);
}
@override
Resource resolveSymbolicLinksSync() => new _OverlayResource._from(
_provider, _resource.resolveSymbolicLinksSync());
@override
Uri toUri() => _resource.toUri();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/exception/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.
/**
* An exception that occurred during the analysis of one or more sources.
*/
class AnalysisException implements Exception {
/**
* The message that explains why the exception occurred.
*/
final String message;
/**
* The exception that caused this exception, or `null` if this exception was
* not caused by another exception.
*/
final CaughtException cause;
/**
* Initialize a newly created exception to have the given [message] and
* [cause].
*/
AnalysisException([this.message = 'Exception', this.cause]);
String toString() {
StringBuffer buffer = new StringBuffer();
buffer.write('$runtimeType: ');
buffer.writeln(message);
if (cause != null) {
buffer.write('Caused by ');
cause._writeOn(buffer);
}
return buffer.toString();
}
}
/**
* An exception that was caught and has an associated stack trace.
*/
class CaughtException implements Exception {
/**
* The exception that was caught.
*/
final Object exception;
/**
* The stack trace associated with the exception.
*/
StackTrace stackTrace;
/**
* Initialize a newly created caught exception to have the given [exception]
* and [stackTrace].
*/
CaughtException(this.exception, stackTrace) {
if (stackTrace == null) {
try {
throw this;
} catch (_, st) {
stackTrace = st;
}
}
this.stackTrace = stackTrace;
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
_writeOn(buffer);
return buffer.toString();
}
/**
* Write a textual representation of the caught exception and its associated
* stack trace.
*/
void _writeOn(StringBuffer buffer) {
if (exception is AnalysisException) {
AnalysisException analysisException = exception;
buffer.writeln(analysisException.message);
if (stackTrace != null) {
buffer.writeln(stackTrace.toString());
}
CaughtException cause = analysisException.cause;
if (cause != null) {
buffer.write('Caused by ');
cause._writeOn(buffer);
}
} else {
buffer.writeln(exception.toString());
if (stackTrace != null) {
buffer.writeln(stackTrace.toString());
}
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/string_source.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/src/generated/engine.dart' show TimestampedData;
import 'package:analyzer/src/generated/source.dart';
/**
* An implementation of [Source] that's based on an in-memory Dart string.
*/
class StringSource extends Source {
/**
* The content of the source.
*/
final String _contents;
@override
final String fullName;
@override
final Uri uri;
@override
final int modificationStamp;
StringSource(this._contents, String fullName, {Uri uri})
: this.fullName = fullName,
uri = uri ?? (fullName == null ? null : new Uri.file(fullName)),
modificationStamp = new DateTime.now().millisecondsSinceEpoch;
@override
TimestampedData<String> get contents =>
new TimestampedData(modificationStamp, _contents);
@override
String get encoding => uri.toString();
@override
int get hashCode => _contents.hashCode ^ fullName.hashCode;
@override
bool get isInSystemLibrary => false;
@override
String get shortName => fullName;
@override
UriKind get uriKind => UriKind.FILE_URI;
/**
* Return `true` if the given [object] is a string source that is equal to
* this source.
*/
@override
bool operator ==(Object object) {
return object is StringSource &&
object._contents == _contents &&
object.fullName == fullName;
}
@override
bool exists() => true;
@override
String toString() => 'StringSource ($fullName)';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/error.dart | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/error/error.dart';
/// A wrapper around [AnalysisError] that provides a more user-friendly string
/// representation.
class AnalyzerError implements Exception {
final AnalysisError error;
AnalyzerError(this.error);
String get message => toString();
@override
String toString() {
var builder = new StringBuffer();
// Print a less friendly string representation to ensure that
// error.source.contents is not executed, as .contents it isn't async
String sourceName = error.source.shortName;
sourceName ??= '<unknown source>';
builder.write("Error in $sourceName: ${error.message}");
// var content = error.source.contents.data;
// var beforeError = content.substring(0, error.offset);
// var lineNumber = "\n".allMatches(beforeError).length + 1;
// builder.writeln("Error on line $lineNumber of ${error.source.fullName}: "
// "${error.message}");
// var errorLineIndex = beforeError.lastIndexOf("\n") + 1;
// var errorEndOfLineIndex = content.indexOf("\n", error.offset);
// if (errorEndOfLineIndex == -1) errorEndOfLineIndex = content.length;
// var errorLine = content.substring(
// errorLineIndex, errorEndOfLineIndex);
// var errorColumn = error.offset - errorLineIndex;
// var errorLength = error.length;
//
// // Ensure that the error line we display isn't too long.
// if (errorLine.length > _MAX_ERROR_LINE_LENGTH) {
// var leftLength = errorColumn;
// var rightLength = errorLine.length - leftLength;
// if (leftLength > _MAX_ERROR_LINE_LENGTH ~/ 2 &&
// rightLength > _MAX_ERROR_LINE_LENGTH ~/ 2) {
// errorLine = "..." + errorLine.substring(
// errorColumn - _MAX_ERROR_LINE_LENGTH ~/ 2 + 3,
// errorColumn + _MAX_ERROR_LINE_LENGTH ~/ 2 - 3)
// + "...";
// errorColumn = _MAX_ERROR_LINE_LENGTH ~/ 2;
// } else if (rightLength > _MAX_ERROR_LINE_LENGTH ~/ 2) {
// errorLine = errorLine.substring(0, _MAX_ERROR_LINE_LENGTH - 3) + "...";
// } else {
// assert(leftLength > _MAX_ERROR_LINE_LENGTH ~/ 2);
// errorColumn -= errorLine.length - _MAX_ERROR_LINE_LENGTH;
// errorLine = "..." + errorLine.substring(
// errorLine.length - _MAX_ERROR_LINE_LENGTH + 3, errorLine.length);
// }
// errorLength = math.min(errorLength, _MAX_ERROR_LINE_LENGTH - errorColumn);
// }
// builder.writeln(errorLine);
//
// for (var i = 0; i < errorColumn; i++) builder.write(" ");
// for (var i = 0; i < errorLength; i++) builder.write("^");
builder.writeln();
return builder.toString();
}
}
/// An error class that collects multiple [AnalyzerError]s that are emitted
/// during a single analysis.
class AnalyzerErrorGroup implements Exception {
final List<AnalyzerError> _errors;
AnalyzerErrorGroup(Iterable<AnalyzerError> errors)
: _errors = errors.toList();
/// Creates an [AnalyzerErrorGroup] from a list of lower-level
/// [AnalysisError]s.
AnalyzerErrorGroup.fromAnalysisErrors(Iterable<AnalysisError> errors)
: this(errors.map((e) => new AnalyzerError(e)));
/// The errors in this collection.
List<AnalyzerError> get errors =>
new UnmodifiableListView<AnalyzerError>(_errors);
String get message => toString();
@override
String toString() => errors.join("\n");
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dartdoc/dartdoc_directive_info.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.
/// Information about the directives found in Dartdoc comments.
class DartdocDirectiveInfo {
// TODO(brianwilkerson) Consider moving the method
// DartUnitHoverComputer.computeDocumentation to this class.
/// A regular expression used to match a macro directive. There is one group
/// that contains the name of the template.
static final macroRegExp = new RegExp(r'{@macro\s+([^}]+)}');
/// A regular expression used to match a template directive. There are two
/// groups. The first contains the name of the template, the second contains
/// the body of the template.
static final templateRegExp = new RegExp(
r'[ ]*{@template\s+(.+?)}([\s\S]+?){@endtemplate}[ ]*\n?',
multiLine: true);
/// A regular expression used to match a youtube or animation directive.
///
/// These are in the form:
/// `{@youtube 560 315 https://www.youtube.com/watch?v=2uaoEDOgk_I}`.
static final videoRegExp =
new RegExp(r'{@(youtube|animation)\s+[^}]+\s+[^}]+\s+([^}]+)}');
/// A table mapping the names of templates to the unprocessed bodies of the
/// templates.
final Map<String, String> templateMap = {};
/// Initialize a newly created set of information about Dartdoc directives.
DartdocDirectiveInfo();
/// Add corresponding pairs from the [names] and [values] to the set of
/// defined templates.
void addTemplateNamesAndValues(List<String> names, List<String> values) {
int length = names.length;
assert(length == values.length);
for (int i = 0; i < length; i++) {
templateMap[names[i]] = values[i];
}
}
/// Process the given Dartdoc [comment], extracting the template directive if
/// there is one.
void extractTemplate(String comment) {
for (Match match in templateRegExp.allMatches(comment)) {
String name = match.group(1).trim();
String body = match.group(2).trim();
templateMap[name] = _stripDelimiters(body).join('\n');
}
}
/// Process the given Dartdoc [comment], replacing any known dartdoc
/// directives with the associated content.
///
/// Macro directives are replaced with the body of the corresponding template.
///
/// Youtube and animation directives are replaced with markdown hyperlinks.
String processDartdoc(String comment) {
List<String> lines = _stripDelimiters(comment);
for (int i = lines.length - 1; i >= 0; i--) {
String line = lines[i];
Match match = macroRegExp.firstMatch(line);
if (match != null) {
String name = match.group(1);
String value = templateMap[name];
if (value != null) {
lines[i] = value;
}
continue;
}
match = videoRegExp.firstMatch(line);
if (match != null) {
String uri = match.group(2);
if (uri != null && uri.isNotEmpty) {
String label = uri;
if (label.startsWith('https://')) {
label = label.substring('https://'.length);
}
lines[i] = '[$label]($uri)';
}
continue;
}
}
return lines.join('\n');
}
/// Remove the delimiters from the given [comment].
List<String> _stripDelimiters(String comment) {
if (comment == null) {
return null;
}
//
// Remove /** */.
//
if (comment.startsWith('/**')) {
comment = comment.substring(3);
}
if (comment.endsWith('*/')) {
comment = comment.substring(0, comment.length - 2);
}
comment = comment.trim();
//
// Remove leading '* ' and '/// '.
//
List<String> lines = comment.split('\n');
int firstNonEmpty = lines.length + 1;
int lastNonEmpty = -1;
for (var i = 0; i < lines.length; i++) {
String line = lines[i];
line = line.trim();
if (line.startsWith('*')) {
line = line.substring(1);
if (line.startsWith(' ')) {
line = line.substring(1);
}
} else if (line.startsWith('///')) {
line = line.substring(3);
if (line.startsWith(' ')) {
line = line.substring(1);
}
}
if (line.isNotEmpty) {
if (i < firstNonEmpty) {
firstNonEmpty = i;
}
if (i > lastNonEmpty) {
lastNonEmpty = i;
}
}
lines[i] = line;
}
if (lastNonEmpty < firstNonEmpty) {
// All of the lines are empty.
return <String>[];
}
return lines.sublist(firstNonEmpty, lastNonEmpty + 1);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/context/context_root.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
/**
* Information about the root directory associated with an analysis context.
*
* Clients may not extend, implement or mix-in this class.
*/
class ContextRoot {
/**
* The path context to use when manipulating paths.
*/
final path.Context pathContext;
/**
* The absolute path of the root directory containing the files to be
* analyzed.
*/
final String root;
/**
* A list of the absolute paths of files and directories within the root
* directory that should not be analyzed.
*/
final List<String> exclude;
/**
* An informative value for the file path that the analysis options were read
* from. This value can be `null` if there is no analysis options file or if
* the location of the file has not yet been discovered.
*/
String optionsFilePath;
/**
* Initialize a newly created context root.
*/
ContextRoot(this.root, this.exclude, {@required path.Context pathContext})
: pathContext = pathContext ?? path.context;
@override
int get hashCode {
int hash = 0;
hash = JenkinsSmiHash.combine(hash, root.hashCode);
hash = JenkinsSmiHash.combine(hash, exclude.hashCode);
return JenkinsSmiHash.finish(hash);
}
@override
bool operator ==(other) {
if (other is ContextRoot) {
return root == other.root &&
_listEqual(exclude, other.exclude, (String a, String b) => a == b);
}
return false;
}
/**
* Return `true` if the file with the given [filePath] is contained within
* this context root. A file contained in a context root if it is within the
* context [root] neither explicitly excluded or within one of the excluded
* directories.
*/
bool containsFile(String filePath) {
if (!pathContext.isWithin(root, filePath)) {
return false;
}
for (String excluded in exclude) {
if (filePath == excluded || pathContext.isWithin(excluded, filePath)) {
return false;
}
}
return true;
}
/**
* Compare the lists [listA] and [listB], using [itemEqual] to compare
* list elements.
*/
bool _listEqual<T>(List<T> listA, List<T> listB, bool itemEqual(T a, T b)) {
if (listA == null) {
return listB == null;
}
if (listB == null) {
return false;
}
if (listA.length != listB.length) {
return false;
}
for (int i = 0; i < listA.length; i++) {
if (!itemEqual(listA[i], listB[i])) {
return false;
}
}
return true;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/context/source.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:collection';
import 'dart:math' show min;
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_dart.dart' as utils;
import 'package:analyzer/src/source/package_map_resolver.dart';
import 'package:analyzer/src/util/uri.dart';
import 'package:package_config/packages.dart';
/**
* Instances of the class `SourceFactory` resolve possibly relative URI's
* against an existing [Source].
*/
class SourceFactoryImpl implements SourceFactory {
@override
AnalysisContext context;
/**
* URI processor used to find mappings for `package:` URIs found in a
* `.packages` config file.
*/
final Packages _packages;
/**
* Resource provider used in working with package maps.
*/
final ResourceProvider _resourceProvider;
/**
* The resolvers used to resolve absolute URI's.
*/
final List<UriResolver> resolvers;
/**
* The predicate to determine is [Source] is local.
*/
LocalSourcePredicate _localSourcePredicate = LocalSourcePredicate.NOT_SDK;
/**
* Cache of mapping of absolute [Uri]s to [Source]s.
*/
final HashMap<Uri, Source> _absoluteUriToSourceCache =
new HashMap<Uri, Source>();
/**
* Initialize a newly created source factory with the given absolute URI
* [resolvers] and optional [_packages] resolution helper.
*/
SourceFactoryImpl(this.resolvers,
[this._packages, ResourceProvider resourceProvider])
: _resourceProvider =
resourceProvider ?? PhysicalResourceProvider.INSTANCE;
@override
DartSdk get dartSdk {
List<UriResolver> resolvers = this.resolvers;
int length = resolvers.length;
for (int i = 0; i < length; i++) {
UriResolver resolver = resolvers[i];
if (resolver is DartUriResolver) {
DartUriResolver dartUriResolver = resolver;
return dartUriResolver.dartSdk;
}
}
return null;
}
@override
void set localSourcePredicate(LocalSourcePredicate localSourcePredicate) {
this._localSourcePredicate = localSourcePredicate;
}
@override
Map<String, List<Folder>> get packageMap {
// Start by looking in .packages.
if (_packages != null) {
Map<String, List<Folder>> packageMap = <String, List<Folder>>{};
var pathContext = _resourceProvider.pathContext;
_packages.asMap().forEach((String name, Uri uri) {
if (uri.scheme == 'file' || uri.scheme == '' /* unspecified */) {
String path = fileUriToNormalizedPath(pathContext, uri);
packageMap[name] = <Folder>[_resourceProvider.getFolder(path)];
}
});
return packageMap;
}
// Default to the PackageMapUriResolver.
PackageMapUriResolver resolver = resolvers
.firstWhere((r) => r is PackageMapUriResolver, orElse: () => null);
return resolver?.packageMap;
}
@override
void clearCache() {
_absoluteUriToSourceCache.clear();
for (var resolver in resolvers) {
resolver.clearCache();
}
}
@override
SourceFactory clone() {
SourceFactory factory =
new SourceFactory(resolvers, _packages, _resourceProvider);
factory.localSourcePredicate = _localSourcePredicate;
return factory;
}
@override
Source forUri(String absoluteUri) {
try {
Uri uri = Uri.parse(absoluteUri);
if (uri.isAbsolute) {
return _internalResolveUri(null, uri);
}
} catch (exception, stackTrace) {
AnalysisEngine.instance.logger.logError(
"Could not resolve URI: $absoluteUri",
new CaughtException(exception, stackTrace));
}
return null;
}
@override
Source forUri2(Uri absoluteUri) {
if (absoluteUri.isAbsolute) {
try {
return _internalResolveUri(null, absoluteUri);
} on AnalysisException catch (exception, stackTrace) {
AnalysisEngine.instance.logger.logError(
"Could not resolve URI: $absoluteUri",
new CaughtException(exception, stackTrace));
}
}
return null;
}
@override
Source fromEncoding(String encoding) {
Source source = forUri(encoding);
if (source == null) {
throw new ArgumentError("Invalid source encoding: '$encoding'");
}
return source;
}
@override
bool isLocalSource(Source source) => _localSourcePredicate.isLocal(source);
@override
Source resolveUri(Source containingSource, String containedUri) {
if (containedUri == null || containedUri.isEmpty) {
return null;
}
try {
// Force the creation of an escaped URI to deal with spaces, etc.
return _internalResolveUri(containingSource, Uri.parse(containedUri));
} on FormatException {
return null;
} catch (exception, stackTrace) {
String containingFullName =
containingSource != null ? containingSource.fullName : '<null>';
AnalysisEngine.instance.logger.logInformation(
"Could not resolve URI ($containedUri) "
"relative to source ($containingFullName)",
new CaughtException(exception, stackTrace));
return null;
}
}
@override
Uri restoreUri(Source source) {
for (UriResolver resolver in resolvers) {
// First see if a resolver can restore the URI.
Uri uri = resolver.restoreAbsolute(source);
if (uri != null) {
// See if there's a package mapping.
Uri packageMappedUri = _getPackageMapping(uri);
if (packageMappedUri != null) {
return packageMappedUri;
}
// Else fall back to the resolver's computed URI.
return uri;
}
}
return null;
}
Uri _getPackageMapping(Uri sourceUri) {
if (_packages == null) {
return null;
}
if (sourceUri.scheme != 'file') {
// TODO(pquitslund): verify this works for non-file URIs.
return null;
}
Map<String, Uri> packagesMap = _packages.asMap();
for (String name in packagesMap.keys) {
final Uri uri = packagesMap[name];
if (utils.startsWith(sourceUri, uri)) {
String relativePath = sourceUri.path
.substring(min(uri.path.length, sourceUri.path.length));
return new Uri(scheme: 'package', path: '$name/$relativePath');
}
}
return null;
}
/**
* Return a source object representing the URI that results from resolving
* the given (possibly relative) contained URI against the URI associated
* with an existing source object, or `null` if the URI could not be resolved.
*
* @param containingSource the source containing the given URI
* @param containedUri the (possibly relative) URI to be resolved against the
* containing source
* @return the source representing the contained URI
* @throws AnalysisException if either the contained URI is invalid or if it
* cannot be resolved against the source object's URI
*/
Source _internalResolveUri(Source containingSource, Uri containedUri) {
if (!containedUri.isAbsolute) {
if (containingSource == null) {
throw new AnalysisException(
"Cannot resolve a relative URI without a containing source: "
"$containedUri");
}
containedUri =
utils.resolveRelativeUri(containingSource.uri, containedUri);
}
Uri actualUri = containedUri;
// Check .packages and update target and actual URIs as appropriate.
if (_packages != null && containedUri.scheme == 'package') {
Uri packageUri;
try {
packageUri =
_packages.resolve(containedUri, notFound: (Uri packageUri) => null);
} on ArgumentError {
// Fall through to try resolvers.
}
if (packageUri != null) {
// Ensure scheme is set.
if (packageUri.scheme == '') {
packageUri = packageUri.replace(scheme: 'file');
}
containedUri = packageUri;
}
}
return _absoluteUriToSourceCache.putIfAbsent(actualUri, () {
for (UriResolver resolver in resolvers) {
Source result = resolver.resolveAbsolute(containedUri, actualUri);
if (result != null) {
return result;
}
}
return null;
});
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/context/cache.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:analyzer/src/generated/engine.dart';
class AnalysisCache {
AnalysisCache(List<CachePartition> partitions);
}
abstract class CachePartition {
final InternalAnalysisContext context;
CachePartition(this.context);
}
class SdkCachePartition extends CachePartition {
SdkCachePartition(InternalAnalysisContext context) : super(context);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/context/builder.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'dart:core';
import 'package:analyzer/dart/analysis/analysis_context.dart' as api;
import 'package:analyzer/dart/analysis/context_locator.dart' as api;
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/analysis_options/analysis_options_provider.dart';
import 'package:analyzer/src/command_line/arguments.dart'
show
applyAnalysisOptionFlags,
bazelAnalysisOptionsPath,
flutterAnalysisOptionsPath;
import 'package:analyzer/src/context/context.dart';
import 'package:analyzer/src/context/context_root.dart';
import 'package:analyzer/src/dart/analysis/byte_store.dart';
import 'package:analyzer/src/dart/analysis/context_root.dart' as api;
import 'package:analyzer/src/dart/analysis/driver.dart'
show AnalysisDriver, AnalysisDriverScheduler;
import 'package:analyzer/src/dart/analysis/driver_based_analysis_context.dart'
as api;
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:analyzer/src/dart/analysis/performance_logger.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/hint/sdk_constraint_extractor.dart';
import 'package:analyzer/src/plugin/resolver_provider.dart';
import 'package:analyzer/src/summary/package_bundle_reader.dart';
import 'package:analyzer/src/summary/summary_sdk.dart';
import 'package:analyzer/src/task/options.dart';
import 'package:analyzer/src/util/uri.dart';
import 'package:analyzer/src/workspace/basic.dart';
import 'package:analyzer/src/workspace/bazel.dart';
import 'package:analyzer/src/workspace/gn.dart';
import 'package:analyzer/src/workspace/package_build.dart';
import 'package:analyzer/src/workspace/pub.dart';
import 'package:analyzer/src/workspace/workspace.dart';
import 'package:args/args.dart';
import 'package:package_config/packages.dart';
import 'package:package_config/packages_file.dart';
import 'package:package_config/src/packages_impl.dart';
import 'package:path/src/context.dart';
import 'package:yaml/yaml.dart';
/**
* A utility class used to build an analysis context for a given directory.
*
* The construction of analysis contexts is as follows:
*
* 1. Determine how package: URI's are to be resolved. This follows the lookup
* algorithm defined by the [package specification][1].
*
* 2. Using the results of step 1, look in each package for an embedder file
* (_embedder.yaml). If one exists then it defines the SDK. If multiple such
* files exist then use the first one found. Otherwise, use the default SDK.
*
* 3. Look in each package for an SDK extension file (_sdkext). For each such
* file, add the specified files to the SDK.
*
* 4. Look for an analysis options file (`analysis_options.yaml` or
* `.analysis_options`) and process the options in the file.
*
* 5. Create a new context. Initialize its source factory based on steps 1, 2
* and 3. Initialize its analysis options from step 4.
*
* [1]: https://github.com/dart-lang/dart_enhancement_proposals/blob/master/Accepted/0005%20-%20Package%20Specification/DEP-pkgspec.md.
*/
class ContextBuilder {
/**
* A callback for when analysis drivers are created, which takes all the same
* arguments as the dart analysis driver constructor so that plugins may
* create their own drivers with the same tools, in theory. Here as a stopgap
* until the official plugin API is complete
*/
static Function onCreateAnalysisDriver;
/**
* The [ResourceProvider] by which paths are converted into [Resource]s.
*/
final ResourceProvider resourceProvider;
/**
* The manager used to manage the DartSdk's that have been created so that
* they can be shared across contexts.
*/
final DartSdkManager sdkManager;
/**
* The cache containing the contents of overlaid files. If this builder will
* be used to build analysis drivers, set the [fileContentOverlay] instead.
*/
final ContentCache contentCache;
/**
* The options used by the context builder.
*/
final ContextBuilderOptions builderOptions;
/**
* The resolver provider used to create a package: URI resolver, or `null` if
* the normal (Package Specification DEP) lookup mechanism is to be used.
*/
ResolverProvider packageResolverProvider;
/**
* The resolver provider used to create a file: URI resolver, or `null` if
* the normal file URI resolver is to be used.
*/
ResolverProvider fileResolverProvider;
/**
* The scheduler used by any analysis drivers created through this interface.
*/
AnalysisDriverScheduler analysisDriverScheduler;
/**
* The performance log used by any analysis drivers created through this
* interface.
*/
PerformanceLog performanceLog;
/**
* The byte store used by any analysis drivers created through this interface.
*/
ByteStore byteStore;
/**
* The file content overlay used by analysis drivers. If this builder will be
* used to build analysis contexts, set the [contentCache] instead.
*/
FileContentOverlay fileContentOverlay;
/**
* Whether any analysis driver created through this interface should support
* indexing and search.
*/
bool enableIndex = false;
/**
* Initialize a newly created builder to be ready to build a context rooted in
* the directory with the given [rootDirectoryPath].
*/
ContextBuilder(this.resourceProvider, this.sdkManager, this.contentCache,
{ContextBuilderOptions options})
: builderOptions = options ?? new ContextBuilderOptions();
/**
* Return an analysis context that is configured correctly to analyze code in
* the directory with the given [path].
*
* *Note:* This method is not yet fully implemented and should not be used.
*/
AnalysisContext buildContext(String path) {
InternalAnalysisContext context =
AnalysisEngine.instance.createAnalysisContext();
AnalysisOptionsImpl options = getAnalysisOptions(path);
context.sourceFactory = createSourceFactory(path, options);
context.analysisOptions = options;
//_processAnalysisOptions(context, optionMap);
declareVariables(context);
return context;
}
/**
* Return an analysis driver that is configured correctly to analyze code in
* the directory with the given [path].
*/
AnalysisDriver buildDriver(ContextRoot contextRoot) {
String path = contextRoot.root;
AnalysisOptions options =
getAnalysisOptions(path, contextRoot: contextRoot);
//_processAnalysisOptions(context, optionMap);
SummaryDataStore summaryData;
if (builderOptions.librarySummaryPaths != null) {
summaryData = SummaryDataStore(builderOptions.librarySummaryPaths);
}
final sf = createSourceFactory(path, options, summaryData: summaryData);
AnalysisDriver driver = new AnalysisDriver(
analysisDriverScheduler,
performanceLog,
resourceProvider,
byteStore,
fileContentOverlay,
contextRoot,
sf,
options,
enableIndex: enableIndex,
externalSummaries: summaryData);
// Set API AnalysisContext for the driver.
var apiContextRoots = api.ContextLocator(
resourceProvider: resourceProvider,
).locateRoots(
includedPaths: [contextRoot.root],
excludedPaths: contextRoot.exclude,
);
driver.analysisContext = api.DriverBasedAnalysisContext(
resourceProvider,
apiContextRoots.first,
driver,
);
// temporary plugin support:
if (onCreateAnalysisDriver != null) {
onCreateAnalysisDriver(driver, analysisDriverScheduler, performanceLog,
resourceProvider, byteStore, fileContentOverlay, path, sf, options);
}
declareVariablesInDriver(driver);
return driver;
}
Map<String, List<Folder>> convertPackagesToMap(Packages packages) {
Map<String, List<Folder>> folderMap = new HashMap<String, List<Folder>>();
if (packages != null && packages != Packages.noPackages) {
var pathContext = resourceProvider.pathContext;
packages.asMap().forEach((String packageName, Uri uri) {
String path = fileUriToNormalizedPath(pathContext, uri);
folderMap[packageName] = [resourceProvider.getFolder(path)];
});
}
return folderMap;
}
// void _processAnalysisOptions(
// AnalysisContext context, Map<String, YamlNode> optionMap) {
// List<OptionsProcessor> optionsProcessors =
// AnalysisEngine.instance.optionsPlugin.optionsProcessors;
// try {
// optionsProcessors.forEach(
// (OptionsProcessor p) => p.optionsProcessed(context, optionMap));
//
// // Fill in lint rule defaults in case lints are enabled and rules are
// // not specified in an options file.
// if (context.analysisOptions.lint && !containsLintRuleEntry(optionMap)) {
// setLints(context, linterPlugin.contributedRules);
// }
//
// // Ask engine to further process options.
// if (optionMap != null) {
// configureContextOptions(context, optionMap);
// }
// } on Exception catch (e) {
// optionsProcessors.forEach((OptionsProcessor p) => p.onError(e));
// }
// }
/**
* Return an analysis options object containing the default option values.
*/
AnalysisOptions createDefaultOptions() {
AnalysisOptions defaultOptions = builderOptions.defaultOptions;
if (defaultOptions == null) {
return new AnalysisOptionsImpl();
}
return new AnalysisOptionsImpl.from(defaultOptions);
}
Packages createPackageMap(String rootDirectoryPath) {
String filePath = builderOptions.defaultPackageFilePath;
if (filePath != null) {
File configFile = resourceProvider.getFile(filePath);
List<int> bytes = configFile.readAsBytesSync();
Map<String, Uri> map = parse(bytes, configFile.toUri());
resolveSymbolicLinks(map);
return new MapPackages(map);
}
String directoryPath = builderOptions.defaultPackagesDirectoryPath;
if (directoryPath != null) {
Folder folder = resourceProvider.getFolder(directoryPath);
return getPackagesFromFolder(folder);
}
return findPackagesFromFile(rootDirectoryPath);
}
SourceFactory createSourceFactory(String rootPath, AnalysisOptions options,
{SummaryDataStore summaryData}) {
Workspace workspace =
ContextBuilder.createWorkspace(resourceProvider, rootPath, this);
DartSdk sdk = findSdk(workspace.packageMap, options);
if (summaryData != null && sdk is SummaryBasedDartSdk) {
summaryData.addBundle(null, sdk.bundle);
}
return workspace.createSourceFactory(sdk, summaryData);
}
/**
* Add any [declaredVariables] to the list of declared variables used by the
* given [context].
*/
void declareVariables(AnalysisContextImpl context) {
Map<String, String> variables = builderOptions.declaredVariables;
if (variables != null && variables.isNotEmpty) {
context.declaredVariables = new DeclaredVariables.fromMap(variables);
}
}
/**
* Add any [declaredVariables] to the list of declared variables used by the
* given analysis [driver].
*/
void declareVariablesInDriver(AnalysisDriver driver) {
Map<String, String> variables = builderOptions.declaredVariables;
if (variables != null && variables.isNotEmpty) {
driver.declaredVariables = new DeclaredVariables.fromMap(variables);
}
}
/**
* Finds a package resolution strategy for the directory at the given absolute
* [path].
*
* This function first tries to locate a `.packages` file in the directory. If
* that is not found, it instead checks for the presence of a `packages/`
* directory in the same place. If that also fails, it starts checking parent
* directories for a `.packages` file, and stops if it finds it. Otherwise it
* gives up and returns [Packages.noPackages].
*/
Packages findPackagesFromFile(String path) {
Resource location = _findPackagesLocation(path);
if (location is File) {
List<int> fileBytes = location.readAsBytesSync();
Map<String, Uri> map;
try {
map =
parse(fileBytes, resourceProvider.pathContext.toUri(location.path));
} catch (exception) {
// If we cannot read the file, then we respond as if the file did not
// exist.
return Packages.noPackages;
}
resolveSymbolicLinks(map);
return new MapPackages(map);
} else if (location is Folder) {
return getPackagesFromFolder(location);
}
return Packages.noPackages;
}
/**
* Return the SDK that should be used to analyze code. Use the given
* [packageMap] and [analysisOptions] to locate the SDK.
*/
DartSdk findSdk(
Map<String, List<Folder>> packageMap, AnalysisOptions analysisOptions) {
String summaryPath = builderOptions.dartSdkSummaryPath;
if (summaryPath != null) {
return new SummaryBasedDartSdk(summaryPath, true,
resourceProvider: resourceProvider);
} else if (packageMap != null) {
SdkExtensionFinder extFinder = new SdkExtensionFinder(packageMap);
List<String> extFilePaths = extFinder.extensionFilePaths;
EmbedderYamlLocator locator = new EmbedderYamlLocator(packageMap);
Map<Folder, YamlMap> embedderYamls = locator.embedderYamls;
EmbedderSdk embedderSdk =
new EmbedderSdk(resourceProvider, embedderYamls);
if (embedderSdk.sdkLibraries.isNotEmpty) {
//
// There is an embedder file that defines the content of the SDK and
// there might be an extension file that extends it.
//
List<String> paths = <String>[];
for (Folder folder in embedderYamls.keys) {
paths.add(folder
.getChildAssumingFile(EmbedderYamlLocator.EMBEDDER_FILE_NAME)
.path);
}
paths.addAll(extFilePaths);
SdkDescription description = new SdkDescription(paths, analysisOptions);
DartSdk dartSdk = sdkManager.getSdk(description, () {
if (extFilePaths.isNotEmpty) {
embedderSdk.addExtensions(extFinder.urlMappings);
}
embedderSdk.analysisOptions = analysisOptions;
embedderSdk.useSummary = sdkManager.canUseSummaries;
return embedderSdk;
});
return dartSdk;
} else if (extFilePaths != null && extFilePaths.isNotEmpty) {
//
// We have an extension file, but no embedder file.
//
String sdkPath = sdkManager.defaultSdkDirectory;
List<String> paths = <String>[sdkPath];
paths.addAll(extFilePaths);
SdkDescription description = new SdkDescription(paths, analysisOptions);
return sdkManager.getSdk(description, () {
FolderBasedDartSdk sdk = new FolderBasedDartSdk(
resourceProvider, resourceProvider.getFolder(sdkPath));
if (extFilePaths.isNotEmpty) {
sdk.addExtensions(extFinder.urlMappings);
}
sdk.analysisOptions = analysisOptions;
sdk.useSummary = sdkManager.canUseSummaries;
return sdk;
});
}
}
String sdkPath = sdkManager.defaultSdkDirectory;
SdkDescription description =
new SdkDescription(<String>[sdkPath], analysisOptions);
return sdkManager.getSdk(description, () {
FolderBasedDartSdk sdk = new FolderBasedDartSdk(
resourceProvider, resourceProvider.getFolder(sdkPath), true);
sdk.analysisOptions = analysisOptions;
sdk.useSummary = sdkManager.canUseSummaries;
return sdk;
});
}
/**
* Return the analysis options that should be used to analyze code in the
* directory with the given [path]. Use [verbosePrint] to echo verbose
* information about the analysis options selection process.
*/
AnalysisOptions getAnalysisOptions(String path,
{void verbosePrint(String text), ContextRoot contextRoot}) {
void verbose(String text) {
if (verbosePrint != null) {
verbosePrint(text);
}
}
// TODO(danrubel) restructure so that we don't create a workspace
// both here and in createSourceFactory
Workspace workspace =
ContextBuilder.createWorkspace(resourceProvider, path, this);
SourceFactory sourceFactory = workspace.createSourceFactory(null, null);
AnalysisOptionsProvider optionsProvider =
new AnalysisOptionsProvider(sourceFactory);
AnalysisOptionsImpl options = createDefaultOptions();
File optionsFile = getOptionsFile(path);
YamlMap optionMap;
if (optionsFile != null) {
try {
optionMap = optionsProvider.getOptionsFromFile(optionsFile);
if (contextRoot != null) {
contextRoot.optionsFilePath = optionsFile.path;
}
verbose('Loaded analysis options from ${optionsFile.path}');
} catch (e) {
// Ignore exceptions thrown while trying to load the options file.
verbose('Exception: $e\n when loading ${optionsFile.path}');
}
} else {
// Search for the default analysis options.
// TODO(danrubel) determine if bazel or gn project depends upon flutter
Source source;
if (workspace.hasFlutterDependency) {
source = sourceFactory.forUri(flutterAnalysisOptionsPath);
}
if (source == null || !source.exists()) {
source = sourceFactory.forUri(bazelAnalysisOptionsPath);
}
if (source != null && source.exists()) {
try {
optionMap = optionsProvider.getOptionsFromSource(source);
if (contextRoot != null) {
contextRoot.optionsFilePath = source.fullName;
}
verbose('Loaded analysis options from ${source.fullName}');
} catch (e) {
// Ignore exceptions thrown while trying to load the options file.
verbose('Exception: $e\n when loading ${source.fullName}');
}
}
}
if (optionMap != null) {
applyToAnalysisOptions(options, optionMap);
if (builderOptions.argResults != null) {
applyAnalysisOptionFlags(options, builderOptions.argResults,
verbosePrint: verbosePrint);
}
} else {
verbose('Using default analysis options');
}
var pubspecFile = _findPubspecFile(path);
if (pubspecFile != null) {
var extractor = new SdkConstraintExtractor(pubspecFile);
var sdkVersionConstraint = extractor.constraint();
if (sdkVersionConstraint != null) {
options.sdkVersionConstraint = sdkVersionConstraint;
}
}
return options;
}
/**
* Return the analysis options file that should be used when analyzing code in
* the directory with the given [path].
*
* If [forceSearch] is true, then don't return the default analysis options
* path. This allows cli to locate what *would* have been the analysis options
* file path, and super-impose the defaults over it in-place.
*/
File getOptionsFile(String path, {bool forceSearch: false}) {
if (!forceSearch) {
String filePath = builderOptions.defaultAnalysisOptionsFilePath;
if (filePath != null) {
return resourceProvider.getFile(filePath);
}
}
Folder root = resourceProvider.getFolder(path);
for (Folder folder = root; folder != null; folder = folder.parent) {
File file =
folder.getChildAssumingFile(AnalysisEngine.ANALYSIS_OPTIONS_FILE);
if (file.exists) {
return file;
}
file = folder
.getChildAssumingFile(AnalysisEngine.ANALYSIS_OPTIONS_YAML_FILE);
if (file.exists) {
return file;
}
}
return null;
}
/**
* Create a [Packages] object for a 'package' directory ([folder]).
*
* Package names are resolved as relative to sub-directories of the package
* directory.
*/
Packages getPackagesFromFolder(Folder folder) {
Context pathContext = resourceProvider.pathContext;
Map<String, Uri> map = new HashMap<String, Uri>();
for (Resource child in folder.getChildren()) {
if (child is Folder) {
// Inline resolveSymbolicLinks for performance reasons.
String packageName = pathContext.basename(child.path);
String folderPath = resolveSymbolicLink(child);
String uriPath = pathContext.join(folderPath, '.');
map[packageName] = pathContext.toUri(uriPath);
}
}
return new MapPackages(map);
}
/**
* Resolve any symbolic links encoded in the path to the given [folder].
*/
String resolveSymbolicLink(Folder folder) {
try {
return folder.resolveSymbolicLinksSync().path;
} on FileSystemException {
return folder.path;
}
}
/**
* Resolve any symbolic links encoded in the URI's in the given [map] by
* replacing the values in the map.
*/
void resolveSymbolicLinks(Map<String, Uri> map) {
Context pathContext = resourceProvider.pathContext;
for (String packageName in map.keys) {
var uri = map[packageName];
String path = fileUriToNormalizedPath(pathContext, uri);
Folder folder = resourceProvider.getFolder(path);
String folderPath = resolveSymbolicLink(folder);
// Add a '.' so that the URI is suitable for resolving relative URI's
// against it.
String uriPath = pathContext.join(folderPath, '.');
map[packageName] = pathContext.toUri(uriPath);
}
}
/**
* Find the location of the package resolution file/directory for the
* directory at the given absolute [path].
*
* Checks for a `.packages` file in the [path]. If not found,
* checks for a `packages` directory in the same directory. If still not
* found, starts checking parent directories for `.packages` until reaching
* the root directory.
*
* Return a [File] object representing a `.packages` file if one is found, a
* [Folder] object for the `packages/` directory if that is found, or `null`
* if neither is found.
*/
Resource _findPackagesLocation(String path) {
Folder folder = resourceProvider.getFolder(path);
if (!folder.exists) {
return null;
}
File checkForConfigFile(Folder folder) {
File file = folder.getChildAssumingFile('.packages');
if (file.exists) {
return file;
}
return null;
}
// Check for $cwd/.packages
File packagesCfgFile = checkForConfigFile(folder);
if (packagesCfgFile != null) {
return packagesCfgFile;
}
// Check for $cwd/packages/
Folder packagesDir = folder.getChildAssumingFolder("packages");
if (packagesDir.exists) {
return packagesDir;
}
// Check for cwd(/..)+/.packages
Folder parentDir = folder.parent;
while (parentDir != null) {
packagesCfgFile = checkForConfigFile(parentDir);
if (packagesCfgFile != null) {
return packagesCfgFile;
}
parentDir = parentDir.parent;
}
return null;
}
/**
* Return the `pubspec.yaml` file that should be used when analyzing code in
* the directory with the given [path], possibly `null`.
*/
File _findPubspecFile(String path) {
var resource = resourceProvider.getResource(path);
while (resource != null) {
if (resource is Folder) {
File pubspecFile = resource.getChildAssumingFile('pubspec.yaml');
if (pubspecFile.exists) {
return pubspecFile;
}
}
resource = resource.parent;
}
return null;
}
/**
* Return `true` if either the directory at [rootPath] or a parent of that
* directory contains a `.packages` file.
*/
static bool _hasPackageFileInPath(
ResourceProvider resourceProvider, String rootPath) {
Folder folder = resourceProvider.getFolder(rootPath);
while (folder != null) {
File file = folder.getChildAssumingFile('.packages');
if (file.exists) {
return true;
}
folder = folder.parent;
}
return false;
}
static Workspace createWorkspace(ResourceProvider resourceProvider,
String rootPath, ContextBuilder contextBuilder) {
if (_hasPackageFileInPath(resourceProvider, rootPath)) {
// A Bazel or Gn workspace that includes a '.packages' file is treated
// like a normal (non-Bazel/Gn) directory. But may still use
// package:build or Pub.
return PackageBuildWorkspace.find(
resourceProvider, rootPath, contextBuilder) ??
PubWorkspace.find(resourceProvider, rootPath, contextBuilder) ??
BasicWorkspace.find(resourceProvider, rootPath, contextBuilder);
}
Workspace workspace = BazelWorkspace.find(resourceProvider, rootPath);
workspace ??= GnWorkspace.find(resourceProvider, rootPath);
workspace ??=
PackageBuildWorkspace.find(resourceProvider, rootPath, contextBuilder);
workspace ??= PubWorkspace.find(resourceProvider, rootPath, contextBuilder);
return workspace ??
BasicWorkspace.find(resourceProvider, rootPath, contextBuilder);
}
}
/**
* Options used by a [ContextBuilder].
*/
class ContextBuilderOptions {
/**
* The results of parsing the command line arguments as defined by
* [defineAnalysisArguments] or `null` if none.
*/
ArgResults argResults;
/**
* The file path of the file containing the summary of the SDK that should be
* used to "analyze" the SDK. This option should only be specified by
* command-line tools such as 'dartanalyzer' or 'ddc'.
*/
String dartSdkSummaryPath;
/**
* The file path of the analysis options file that should be used in place of
* any file in the root directory or a parent of the root directory, or `null`
* if the normal lookup mechanism should be used.
*/
String defaultAnalysisOptionsFilePath;
/**
* A table mapping variable names to values for the declared variables, or
* `null` if no additional variables should be declared.
*/
Map<String, String> declaredVariables;
/**
* The default analysis options that should be used unless some or all of them
* are overridden in the analysis options file, or `null` if the default
* defaults should be used.
*/
AnalysisOptions defaultOptions;
/**
* The file path of the .packages file that should be used in place of any
* file found using the normal (Package Specification DEP) lookup mechanism,
* or `null` if the normal lookup mechanism should be used.
*/
String defaultPackageFilePath;
/**
* The file path of the packages directory that should be used in place of any
* file found using the normal (Package Specification DEP) lookup mechanism,
* or `null` if the normal lookup mechanism should be used.
*/
String defaultPackagesDirectoryPath;
/**
* A list of the paths of summary files that are to be used, or `null` if no
* summary information is available.
*/
List<String> librarySummaryPaths;
/**
* Initialize a newly created set of options
*/
ContextBuilderOptions();
}
/**
* Given a package map, check in each package's lib directory for the existence
* of an `_embedder.yaml` file. If the file contains a top level YamlMap, it
* will be added to the [embedderYamls] map.
*/
class EmbedderYamlLocator {
/**
* The name of the embedder files being searched for.
*/
static const String EMBEDDER_FILE_NAME = '_embedder.yaml';
/**
* A mapping from a package's library directory to the parsed YamlMap.
*/
final Map<Folder, YamlMap> embedderYamls = new HashMap<Folder, YamlMap>();
/**
* Initialize a newly created locator by processing the packages in the given
* [packageMap].
*/
EmbedderYamlLocator(Map<String, List<Folder>> packageMap) {
if (packageMap != null) {
_processPackageMap(packageMap);
}
}
/**
* Programmatically add an `_embedder.yaml` mapping.
*/
void addEmbedderYaml(Folder libDir, String embedderYaml) {
_processEmbedderYaml(libDir, embedderYaml);
}
/**
* Refresh the map of located files to those found by processing the given
* [packageMap].
*/
void refresh(Map<String, List<Folder>> packageMap) {
// Clear existing.
embedderYamls.clear();
if (packageMap != null) {
_processPackageMap(packageMap);
}
}
/**
* Given the yaml for an embedder ([embedderYaml]) and a folder ([libDir]),
* setup the uri mapping.
*/
void _processEmbedderYaml(Folder libDir, String embedderYaml) {
try {
YamlNode yaml = loadYaml(embedderYaml);
if (yaml is YamlMap) {
embedderYamls[libDir] = yaml;
}
} catch (_) {
// Ignored
}
}
/**
* Given a package [name] and a list of folders ([libDirs]), process any
* `_embedder.yaml` files that are found in any of the folders.
*/
void _processPackage(String name, List<Folder> libDirs) {
for (Folder libDir in libDirs) {
String embedderYaml = _readEmbedderYaml(libDir);
if (embedderYaml != null) {
_processEmbedderYaml(libDir, embedderYaml);
}
}
}
/**
* Process each of the entries in the [packageMap].
*/
void _processPackageMap(Map<String, List<Folder>> packageMap) {
packageMap.forEach(_processPackage);
}
/**
* Read and return the contents of [libDir]/[EMBEDDER_FILE_NAME], or `null` if
* the file doesn't exist.
*/
String _readEmbedderYaml(Folder libDir) {
File file = libDir.getChild(EMBEDDER_FILE_NAME);
try {
return file.readAsStringSync();
} on FileSystemException {
// File can't be read.
return null;
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/context/context.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:analyzer/src/context/cache.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/sdk.dart' show DartSdk;
import 'package:analyzer/src/generated/source.dart';
/**
* An [AnalysisContext] in which analysis can be performed.
*/
class AnalysisContextImpl implements InternalAnalysisContext {
/**
* The set of analysis options controlling the behavior of this context.
*/
AnalysisOptionsImpl _options = new AnalysisOptionsImpl();
/**
* The source factory used to create the sources that can be analyzed in this
* context.
*/
SourceFactory _sourceFactory;
/**
* The set of declared variables used when computing constant values.
*/
DeclaredVariables _declaredVariables = new DeclaredVariables();
/**
* The [TypeProvider] for this context, `null` if not yet created.
*/
TypeProvider _typeProvider;
/**
* The [TypeSystem] for this context, `null` if not yet created.
*/
TypeSystem _typeSystem;
/**
* Initialize a newly created analysis context.
*/
AnalysisContextImpl();
@override
AnalysisOptions get analysisOptions => _options;
@override
void set analysisOptions(AnalysisOptions options) {
this._options = options;
}
@override
DeclaredVariables get declaredVariables => _declaredVariables;
/**
* Set the declared variables to the give collection of declared [variables].
*/
void set declaredVariables(DeclaredVariables variables) {
_declaredVariables = variables;
}
@override
SourceFactory get sourceFactory => _sourceFactory;
@override
void set sourceFactory(SourceFactory factory) {
_sourceFactory = factory;
}
@override
TypeProvider get typeProvider {
return _typeProvider;
}
/**
* Sets the [TypeProvider] for this context.
*/
@override
void set typeProvider(TypeProvider typeProvider) {
_typeProvider = typeProvider;
}
@override
TypeSystem get typeSystem {
return _typeSystem ??= Dart2TypeSystem(typeProvider);
}
@override
void applyChanges(ChangeSet changeSet) {
throw UnimplementedError();
}
/**
* Create an analysis cache based on the given source [factory].
*/
AnalysisCache createCacheFromSourceFactory(SourceFactory factory) {
throw UnimplementedError();
}
}
/**
* An object that manages the partitions that can be shared between analysis
* contexts.
*/
class PartitionManager {
/**
* Clear any cached data being maintained by this manager.
*/
void clearCache() {}
/**
* Return the partition being used for the given [sdk], creating the partition
* if necessary.
*/
SdkCachePartition forSdk(DartSdk sdk) {
throw UnimplementedError();
}
}
/**
* An [AnalysisContext] that only contains sources for a Dart SDK.
*/
class SdkAnalysisContext extends AnalysisContextImpl {
/**
* Initialize a newly created SDK analysis context with the given [options].
* Analysis options cannot be changed afterwards. If the given [options] are
* `null`, then default options are used.
*/
SdkAnalysisContext(AnalysisOptions options) {
if (options != null) {
super.analysisOptions = options;
}
}
@override
void set analysisOptions(AnalysisOptions options) {
throw new StateError('AnalysisOptions of SDK context cannot be changed.');
}
@override
AnalysisCache createCacheFromSourceFactory(SourceFactory factory) {
throw UnimplementedError();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/command_line/arguments.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/context/builder.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:args/args.dart';
import 'package:path/path.dart';
const String analysisOptionsFileOption = 'options';
const String bazelAnalysisOptionsPath =
'package:dart.analysis_options/default.yaml';
const String defineVariableOption = 'D';
const String enableInitializingFormalAccessFlag = 'initializing-formal-access';
@deprecated
const String enableSuperMixinFlag = 'supermixin';
const String flutterAnalysisOptionsPath =
'package:flutter/analysis_options_user.yaml';
const String ignoreUnrecognizedFlagsFlag = 'ignore-unrecognized-flags';
const String implicitCastsFlag = 'implicit-casts';
const String lintsFlag = 'lints';
const String noImplicitDynamicFlag = 'no-implicit-dynamic';
const String packageRootOption = 'package-root';
const String packagesOption = 'packages';
const String sdkPathOption = 'dart-sdk';
const String sdkSummaryPathOption = 'dart-sdk-summary';
/**
* Update [options] with the value of each analysis option command line flag.
*/
void applyAnalysisOptionFlags(AnalysisOptionsImpl options, ArgResults args,
{void verbosePrint(String text)}) {
void verbose(String text) {
if (verbosePrint != null) {
verbosePrint('Analysis options: $text');
}
}
if (args.wasParsed(implicitCastsFlag)) {
options.implicitCasts = args[implicitCastsFlag];
verbose('$implicitCastsFlag = ${options.implicitCasts}');
}
if (args.wasParsed(noImplicitDynamicFlag)) {
options.implicitDynamic = !args[noImplicitDynamicFlag];
verbose('$noImplicitDynamicFlag = ${options.implicitDynamic}');
}
try {
if (args.wasParsed(lintsFlag)) {
options.lint = args[lintsFlag];
verbose('$lintsFlag = ${options.lint}');
}
} on ArgumentError {
// lints were not defined - ignore and fall through
}
}
/**
* Use the given [resourceProvider], [contentCache] and command-line [args] to
* create a context builder.
*/
ContextBuilderOptions createContextBuilderOptions(ArgResults args,
{bool trackCacheDependencies}) {
ContextBuilderOptions builderOptions = new ContextBuilderOptions();
builderOptions.argResults = args;
//
// File locations.
//
builderOptions.dartSdkSummaryPath = args[sdkSummaryPathOption];
builderOptions.defaultAnalysisOptionsFilePath =
args[analysisOptionsFileOption];
builderOptions.defaultPackageFilePath = args[packagesOption];
builderOptions.defaultPackagesDirectoryPath = args[packageRootOption];
//
// Analysis options.
//
AnalysisOptionsImpl defaultOptions = new AnalysisOptionsImpl();
applyAnalysisOptionFlags(defaultOptions, args);
if (trackCacheDependencies != null) {
defaultOptions.trackCacheDependencies = trackCacheDependencies;
}
builderOptions.defaultOptions = defaultOptions;
//
// Declared variables.
//
Map<String, String> declaredVariables = <String, String>{};
List<String> variables = (args[defineVariableOption] as List).cast<String>();
for (String variable in variables) {
int index = variable.indexOf('=');
if (index < 0) {
// TODO (brianwilkerson) Decide the semantics we want in this case.
// The VM prints "No value given to -D option", then tries to load '-Dfoo'
// as a file and dies. Unless there was nothing after the '-D', in which
// case it prints the warning and ignores the option.
} else {
String name = variable.substring(0, index);
if (name.isNotEmpty) {
// TODO (brianwilkerson) Decide the semantics we want in the case where
// there is no name. If there is no name, the VM tries to load a file
// named '-D' and dies.
declaredVariables[name] = variable.substring(index + 1);
}
}
}
builderOptions.declaredVariables = declaredVariables;
return builderOptions;
}
/**
* Use the given [resourceProvider] and command-line [args] to create a Dart SDK
* manager. The manager will use summary information if [useSummaries] is `true`
* and if the summary information exists.
*/
DartSdkManager createDartSdkManager(
ResourceProvider resourceProvider, bool useSummaries, ArgResults args) {
String sdkPath = args[sdkPathOption];
bool canUseSummaries = useSummaries &&
args.rest.every((String sourcePath) {
sourcePath = context.absolute(sourcePath);
sourcePath = context.normalize(sourcePath);
return !context.isWithin(sdkPath, sourcePath);
});
return new DartSdkManager(
sdkPath ?? FolderBasedDartSdk.defaultSdkDirectory(resourceProvider)?.path,
canUseSummaries);
}
/**
* Add the standard flags and options to the given [parser]. The standard flags
* are those that are typically used to control the way in which the code is
* analyzed.
*
* TODO(danrubel) Update DDC to support all the options defined in this method
* then remove the [ddc] named argument from this method.
*/
void defineAnalysisArguments(ArgParser parser, {bool hide: true, ddc: false}) {
parser.addOption(sdkPathOption,
help: 'The path to the Dart SDK.', hide: ddc && hide);
parser.addOption(analysisOptionsFileOption,
help: 'Path to an analysis options file.', hide: ddc && hide);
parser.addOption(packageRootOption,
help: 'The path to a package root directory (deprecated). '
'This option cannot be used with --packages.',
hide: ddc && hide);
parser.addFlag('strong',
help: 'Enable strong mode (deprecated); this option is now ignored.',
defaultsTo: true,
hide: true,
negatable: true);
parser.addFlag('declaration-casts',
negatable: true,
help: 'Disable declaration casts in strong mode (https://goo.gl/cTLz40)\n'
'This option is now ignored and will be removed in a future release.',
hide: ddc && hide);
parser.addFlag(implicitCastsFlag,
negatable: true,
help: 'Disable implicit casts in strong mode (https://goo.gl/cTLz40).',
hide: ddc && hide);
parser.addFlag(noImplicitDynamicFlag,
negatable: false,
help: 'Disable implicit dynamic (https://goo.gl/m0UgXD).',
hide: ddc && hide);
//
// Hidden flags and options.
//
parser.addMultiOption(defineVariableOption,
abbr: 'D',
help: 'Define environment variables. For example, "-Dfoo=bar" defines an '
'environment variable named "foo" whose value is "bar".',
hide: hide);
parser.addOption(packagesOption,
help: 'The path to the package resolution configuration file, which '
'supplies a mapping of package names\nto paths. This option cannot be '
'used with --package-root.',
hide: ddc);
parser.addOption(sdkSummaryPathOption,
help: 'The path to the Dart SDK summary file.', hide: hide);
parser.addFlag(enableInitializingFormalAccessFlag,
help:
'Enable support for allowing access to field formal parameters in a '
'constructor\'s initializer list (deprecated).',
defaultsTo: false,
negatable: false,
hide: hide || ddc);
if (!ddc) {
parser.addFlag(lintsFlag,
help: 'Show lint results.', defaultsTo: false, negatable: true);
}
}
/**
* Find arguments of the form -Dkey=value
* or argument pairs of the form -Dkey value
* and place those key/value pairs into [definedVariables].
* Return a list of arguments with the key/value arguments removed.
*/
List<String> extractDefinedVariables(
List<String> args, Map<String, String> definedVariables) {
//TODO(danrubel) extracting defined variables is already handled by the
// createContextBuilderOptions method.
// Long term we should switch to using that instead.
int count = args.length;
List<String> remainingArgs = <String>[];
for (int i = 0; i < count; i++) {
String arg = args[i];
if (arg == '--') {
while (i < count) {
remainingArgs.add(args[i++]);
}
} else if (arg.startsWith("-D")) {
int end = arg.indexOf('=');
if (end > 2) {
definedVariables[arg.substring(2, end)] = arg.substring(end + 1);
} else if (i + 1 < count) {
definedVariables[arg.substring(2)] = args[++i];
} else {
remainingArgs.add(arg);
}
} else {
remainingArgs.add(arg);
}
}
return remainingArgs;
}
/**
* Return a list of command-line arguments containing all of the given [args]
* that are defined by the given [parser]. An argument is considered to be
* defined by the parser if
* - it starts with '--' and the rest of the argument (minus any value
* introduced by '=') is the name of a known option,
* - it starts with '-' and the rest of the argument (minus any value
* introduced by '=') is the name of a known abbreviation, or
* - it starts with something other than '--' or '-'.
*
* This function allows command-line tools to implement the
* '--ignore-unrecognized-flags' option.
*/
List<String> filterUnknownArguments(List<String> args, ArgParser parser) {
Set<String> knownOptions = new HashSet<String>();
Set<String> knownAbbreviations = new HashSet<String>();
parser.options.forEach((String name, Option option) {
knownOptions.add(name);
String abbreviation = option.abbr;
if (abbreviation != null) {
knownAbbreviations.add(abbreviation);
}
if (option.negatable) {
knownOptions.add('no-$name');
}
});
String optionName(int prefixLength, String argument) {
int equalsOffset = argument.lastIndexOf('=');
if (equalsOffset < 0) {
return argument.substring(prefixLength);
}
return argument.substring(prefixLength, equalsOffset);
}
List<String> filtered = <String>[];
for (int i = 0; i < args.length; i++) {
String argument = args[i];
if (argument.startsWith('--') && argument.length > 2) {
if (knownOptions.contains(optionName(2, argument))) {
filtered.add(argument);
}
} else if (argument.startsWith('-') && argument.length > 1) {
if (knownAbbreviations.contains(optionName(1, argument))) {
filtered.add(argument);
}
} else {
filtered.add(argument);
}
}
return filtered;
}
/**
* Use the given [parser] to parse the given command-line [args], and return the
* result.
*/
ArgResults parse(
ResourceProvider provider, ArgParser parser, List<String> args) {
args = preprocessArgs(provider, args);
if (args.contains('--$ignoreUnrecognizedFlagsFlag')) {
args = filterUnknownArguments(args, parser);
}
return parser.parse(args);
}
/**
* Preprocess the given list of command line [args].
* If the final arg is `@file_path` (Bazel worker mode),
* then read in all the lines of that file and add those as args.
* Always returns a new modifiable list.
*/
List<String> preprocessArgs(ResourceProvider provider, List<String> args) {
args = new List.from(args);
if (args.isEmpty) {
return args;
}
String lastArg = args.last;
if (lastArg.startsWith('@')) {
File argsFile = provider.getFile(lastArg.substring(1));
try {
args.removeLast();
args.addAll(argsFile
.readAsStringSync()
.replaceAll('\r\n', '\n')
.replaceAll('\r', '\n')
.split('\n')
.where((String line) => line.isNotEmpty));
} on FileSystemException catch (e) {
throw new Exception('Failed to read file specified by $lastArg : $e');
}
}
return args;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/ignore_comments/ignore_info.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:collection';
import 'package:analyzer/source/line_info.dart';
import 'package:analyzer/src/generated/source.dart';
/// Information about analysis `//ignore:` and `//ignore_for_file` comments
/// within a source file.
class IgnoreInfo {
/// Instance shared by all cases without matches.
static final IgnoreInfo _EMPTY_INFO = new IgnoreInfo();
/// A regular expression for matching 'ignore' comments. Produces matches
/// containing 2 groups. For example:
///
/// * ['//ignore: error_code', 'error_code']
///
/// Resulting codes may be in a list ('error_code_1,error_code2').
static final RegExp _IGNORE_MATCHER =
new RegExp(r'//+[ ]*ignore:(.*)$', multiLine: true);
/// A regular expression for matching 'ignore_for_file' comments. Produces
/// matches containing 2 groups. For example:
///
/// * ['//ignore_for_file: error_code', 'error_code']
///
/// Resulting codes may be in a list ('error_code_1,error_code2').
static final RegExp _IGNORE_FOR_FILE_MATCHER =
new RegExp(r'//[ ]*ignore_for_file:(.*)$', multiLine: true);
final Map<int, List<String>> _ignoreMap = new HashMap<int, List<String>>();
final Set<String> _ignoreForFileSet = new HashSet<String>();
/// Whether this info object defines any ignores.
bool get hasIgnores => ignores.isNotEmpty || _ignoreForFileSet.isNotEmpty;
/// Iterable of error codes ignored for the whole file.
Iterable<String> get ignoreForFiles => _ignoreForFileSet;
/// Map of line numbers to associated ignored error codes.
Map<int, Iterable<String>> get ignores => _ignoreMap;
/// Ignore this [errorCode] at [line].
void add(int line, String errorCode) {
_ignoreMap.putIfAbsent(line, () => new List<String>()).add(errorCode);
}
/// Ignore these [errorCodes] at [line].
void addAll(int line, Iterable<String> errorCodes) {
_ignoreMap.putIfAbsent(line, () => new List<String>()).addAll(errorCodes);
}
/// Ignore these [errorCodes] in the whole file.
void addAllForFile(Iterable<String> errorCodes) {
_ignoreForFileSet.addAll(errorCodes);
}
/// Test whether this [errorCode] is ignored at the given [line].
bool ignoredAt(String errorCode, int line) =>
_ignoreForFileSet.contains(errorCode) ||
_ignoreMap[line]?.contains(errorCode) == true;
/// Calculate ignores for the given [content] with line [info].
static IgnoreInfo calculateIgnores(String content, LineInfo info) {
Iterable<Match> matches = _IGNORE_MATCHER.allMatches(content);
Iterable<Match> fileMatches = _IGNORE_FOR_FILE_MATCHER.allMatches(content);
if (matches.isEmpty && fileMatches.isEmpty) {
return _EMPTY_INFO;
}
IgnoreInfo ignoreInfo = new IgnoreInfo();
for (Match match in matches) {
// See _IGNORE_MATCHER for format --- note the possibility of error lists.
Iterable<String> codes = match
.group(1)
.split(',')
.map((String code) => code.trim().toLowerCase());
CharacterLocation location = info.getLocation(match.start);
int lineNumber = location.lineNumber;
String beforeMatch = content.substring(
info.getOffsetOfLine(lineNumber - 1),
info.getOffsetOfLine(lineNumber - 1) + location.columnNumber - 1);
if (beforeMatch.trim().isEmpty) {
// The comment is on its own line, so it refers to the next line.
ignoreInfo.addAll(lineNumber + 1, codes);
} else {
// The comment sits next to code, so it refers to its own line.
ignoreInfo.addAll(lineNumber, codes);
}
}
for (Match match in fileMatches) {
Iterable<String> codes = match
.group(1)
.split(',')
.map((String code) => code.trim().toLowerCase());
ignoreInfo.addAllForFile(codes);
}
return ignoreInfo;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/ddc.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:collection';
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:analyzer/src/dart/analysis/restricted_analysis_context.dart';
import 'package:analyzer/src/dart/analysis/session.dart';
import 'package:analyzer/src/dart/element/type_provider.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary/package_bundle_reader.dart';
import 'package:analyzer/src/summary/summarize_elements.dart';
import 'package:analyzer/src/summary2/informative_data.dart';
import 'package:analyzer/src/summary2/link.dart' as summary2;
import 'package:analyzer/src/summary2/linked_bundle_context.dart' as summary2;
import 'package:analyzer/src/summary2/linked_element_factory.dart' as summary2;
import 'package:analyzer/src/summary2/reference.dart' as summary2;
import 'package:meta/meta.dart';
class DevCompilerResynthesizerBuilder {
final FileSystemState _fsState;
final SourceFactory _sourceFactory;
final DeclaredVariables _declaredVariables;
final AnalysisOptionsImpl _analysisOptions;
final SummaryDataStore _summaryData;
final List<Uri> _explicitSources;
_SourceCrawler _fileCrawler;
final List<_UnitInformativeData> _informativeData = [];
final PackageBundleAssembler _assembler;
List<int> summaryBytes;
RestrictedAnalysisContext context;
summary2.LinkedElementFactory elementFactory;
DevCompilerResynthesizerBuilder({
@required FileSystemState fsState,
@required SourceFactory sourceFactory,
@required DeclaredVariables declaredVariables,
@required AnalysisOptionsImpl analysisOptions,
@required SummaryDataStore summaryData,
@required List<Uri> explicitSources,
}) : _fsState = fsState,
_sourceFactory = sourceFactory,
_declaredVariables = declaredVariables,
_analysisOptions = analysisOptions,
_summaryData = summaryData,
_explicitSources = explicitSources,
_assembler = PackageBundleAssembler();
/// URIs of libraries that should be linked.
List<String> get libraryUris => _fileCrawler.libraryUris;
/// Link explicit sources, serialize [PackageBundle] into [summaryBytes].
///
/// Create a new [context], [resynthesizer] and [elementFactory].
void build() {
_fileCrawler = _SourceCrawler(
_fsState,
_sourceFactory,
_summaryData,
_explicitSources,
);
_fileCrawler.crawl();
_computeLinkedLibraries2();
summaryBytes = _assembler.assemble().toBuffer();
var bundle = PackageBundle.fromBuffer(summaryBytes);
// Create an analysis context to contain the state for this build unit.
var synchronousSession = SynchronousSession(
_analysisOptions,
_declaredVariables,
);
context = RestrictedAnalysisContext(synchronousSession, _sourceFactory);
_createElementFactory(bundle);
}
/// Link libraries, and fill [_assembler].
void _computeLinkedLibraries2() {
var inputLibraries = <summary2.LinkInputLibrary>[];
var sourceToUnit = _fileCrawler.sourceToUnit;
var librarySourcesToLink = <Source>[]
..addAll(_fileCrawler.librarySources)
..addAll(_fileCrawler._invalidLibrarySources);
for (var librarySource in librarySourcesToLink) {
var libraryUriStr = '${librarySource.uri}';
var unit = sourceToUnit[librarySource];
var inputUnits = <summary2.LinkInputUnit>[];
inputUnits.add(
summary2.LinkInputUnit(null, librarySource, false, unit),
);
_informativeData.add(
_UnitInformativeData(
libraryUriStr,
libraryUriStr,
createInformativeData(unit),
),
);
for (var directive in unit.directives) {
if (directive is PartDirective) {
var partRelativeUriStr = directive.uri.stringValue;
var partSource = _sourceFactory.resolveUri(
librarySource,
partRelativeUriStr,
);
// Add empty synthetic units for unresolved `part` URIs.
if (partSource == null) {
inputUnits.add(
summary2.LinkInputUnit(
partRelativeUriStr,
null,
true,
_fsState.unresolvedFile.parse(),
),
);
continue;
}
var partUnit = sourceToUnit[partSource];
inputUnits.add(
summary2.LinkInputUnit(
partRelativeUriStr,
partSource,
partSource == null,
partUnit,
),
);
var unitUriStr = '${partSource.uri}';
_informativeData.add(
_UnitInformativeData(
libraryUriStr,
unitUriStr,
createInformativeData(partUnit),
),
);
}
}
inputLibraries.add(
summary2.LinkInputLibrary(librarySource, inputUnits),
);
}
var analysisContext = RestrictedAnalysisContext(
SynchronousSession(_analysisOptions, _declaredVariables),
_sourceFactory,
);
var elementFactory = summary2.LinkedElementFactory(
analysisContext,
null,
summary2.Reference.root(),
);
for (var bundle in _summaryData.bundles) {
elementFactory.addBundle(
summary2.LinkedBundleContext(elementFactory, bundle.bundle2),
);
}
var linkResult = summary2.link(elementFactory, inputLibraries);
_assembler.setBundle2(linkResult.bundle);
}
void _createElementFactory(PackageBundle newBundle) {
elementFactory = summary2.LinkedElementFactory(
context,
null,
summary2.Reference.root(),
);
for (var bundle in _summaryData.bundles) {
elementFactory.addBundle(
summary2.LinkedBundleContext(elementFactory, bundle.bundle2),
);
}
elementFactory.addBundle(
summary2.LinkedBundleContext(elementFactory, newBundle.bundle2),
);
for (var unitData in _informativeData) {
elementFactory.setInformativeData(
unitData.libraryUriStr,
unitData.unitUriStr,
unitData.data,
);
}
var dartCore = elementFactory.libraryOfUri('dart:core');
var dartAsync = elementFactory.libraryOfUri('dart:async');
var typeProvider = TypeProviderImpl(dartCore, dartAsync);
context.typeProvider = typeProvider;
dartCore.createLoadLibraryFunction(typeProvider);
dartAsync.createLoadLibraryFunction(typeProvider);
}
}
class _SourceCrawler {
final FileSystemState _fsState;
final SourceFactory _sourceFactory;
final SummaryDataStore _summaryData;
final List<Uri> _explicitSources;
/// The pending list of sources to visit.
var _pendingSource = Queue<Uri>();
/// The sources that have been added to [_pendingSource], used to ensure
/// we only visit a given source once.
var _knownSources = Set<Uri>();
/// The set of URIs that expected to be libraries.
///
/// Some of the might turn out to have `part of` directive, and so reported
/// later. However we still must be able to provide some element for them
/// when requested via `import` or `export` directives.
final Set<Uri> _expectedLibraryUris = Set<Uri>();
/// The list of sources with URIs that [_expectedLibraryUris], but turned
/// out to be parts. We still add them into summaries, but don't resolve
/// them as units.
final List<Source> _invalidLibrarySources = [];
final Map<Source, CompilationUnit> sourceToUnit = {};
final List<String> libraryUris = [];
final List<Source> librarySources = [];
_SourceCrawler(
this._fsState,
this._sourceFactory,
this._summaryData,
this._explicitSources,
);
/// Starting with [_explicitSources], visit all transitive imports, exports,
/// parts, and create an unlinked unit for each (unless it is provided by an
/// input summary from [_summaryData]).
void crawl() {
_pendingSource.addAll(_explicitSources);
_knownSources.addAll(_explicitSources);
// Collect the unlinked units for all transitive sources.
//
// TODO(jmesserly): consider using parallelism via asynchronous IO here,
// once we fix debugger extension (web/web_command.dart) to allow async.
//
// It would let computation tasks (parsing/serializing unlinked units)
// proceed in parallel with reading the sources from disk.
while (_pendingSource.isNotEmpty) {
_visit(_pendingSource.removeFirst());
}
}
/// Visit the file with the given [uri], and fill its data.
void _visit(Uri uri) {
var uriStr = uri.toString();
// Maybe an input package contains the source.
if (_summaryData.hasUnlinkedUnit(uriStr)) {
return;
}
var source = _sourceFactory.forUri2(uri);
if (source == null) {
return;
}
var file = _fsState.getFileForPath(source.fullName);
var unit = file.parse();
sourceToUnit[source] = unit;
void enqueueSource(String relativeUri, bool shouldBeLibrary) {
var sourceUri = resolveRelativeUri(uri, Uri.parse(relativeUri));
if (_knownSources.add(sourceUri)) {
_pendingSource.add(sourceUri);
if (shouldBeLibrary) {
_expectedLibraryUris.add(sourceUri);
}
}
}
// Add reachable imports/exports/parts, if any.
var isPart = false;
for (var directive in unit.directives) {
if (directive is UriBasedDirective) {
if (directive is NamespaceDirective) {
enqueueSource(directive.uri.stringValue, true);
for (var config in directive.configurations) {
enqueueSource(config.uri.stringValue, true);
}
} else {
enqueueSource(directive.uri.stringValue, false);
}
} else if (directive is PartOfDirective) {
isPart = true;
}
}
// Remember library URIs, for linking and compiling.
if (!isPart) {
libraryUris.add(uriStr);
librarySources.add(source);
} else if (_expectedLibraryUris.contains(uri)) {
_invalidLibrarySources.add(source);
}
}
}
class _UnitInformativeData {
final String libraryUriStr;
final String unitUriStr;
final List<UnlinkedInformativeData> data;
_UnitInformativeData(this.libraryUriStr, this.unitUriStr, this.data);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/referenced_names.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
/**
* Compute the set of external names referenced in the [unit].
*/
Set<String> computeReferencedNames(CompilationUnit unit) {
_ReferencedNamesComputer computer = new _ReferencedNamesComputer();
unit.accept(computer);
return computer.names;
}
/**
* Compute the set of names which are used in `extends`, `with` or `implements`
* clauses in the file. Import prefixes and type arguments are not included.
*/
Set<String> computeSubtypedNames(CompilationUnit unit) {
Set<String> subtypedNames = new Set<String>();
void _addSubtypedName(TypeName type) {
if (type != null) {
Identifier name = type.name;
if (name is SimpleIdentifier) {
subtypedNames.add(name.name);
} else if (name is PrefixedIdentifier) {
subtypedNames.add(name.identifier.name);
}
}
}
void _addSubtypedNames(List<TypeName> types) {
types?.forEach(_addSubtypedName);
}
for (CompilationUnitMember declaration in unit.declarations) {
if (declaration is ClassDeclaration) {
_addSubtypedName(declaration.extendsClause?.superclass);
_addSubtypedNames(declaration.withClause?.mixinTypes);
_addSubtypedNames(declaration.implementsClause?.interfaces);
} else if (declaration is ClassTypeAlias) {
_addSubtypedName(declaration.superclass);
_addSubtypedNames(declaration.withClause?.mixinTypes);
_addSubtypedNames(declaration.implementsClause?.interfaces);
} else if (declaration is MixinDeclaration) {
_addSubtypedNames(declaration.onClause?.superclassConstraints);
_addSubtypedNames(declaration.implementsClause?.interfaces);
}
}
return subtypedNames;
}
/**
* Chained set of local names, that hide corresponding external names.
*/
class _LocalNameScope {
final _LocalNameScope enclosing;
Set<String> names;
_LocalNameScope(this.enclosing);
factory _LocalNameScope.forBlock(_LocalNameScope enclosing, Block node) {
_LocalNameScope scope = new _LocalNameScope(enclosing);
for (Statement statement in node.statements) {
if (statement is FunctionDeclarationStatement) {
scope.add(statement.functionDeclaration.name);
} else if (statement is VariableDeclarationStatement) {
scope.addVariableNames(statement.variables);
}
}
return scope;
}
factory _LocalNameScope.forClass(
_LocalNameScope enclosing, ClassDeclaration node) {
_LocalNameScope scope = new _LocalNameScope(enclosing);
scope.addTypeParameters(node.typeParameters);
for (ClassMember member in node.members) {
if (member is FieldDeclaration) {
scope.addVariableNames(member.fields);
} else if (member is MethodDeclaration) {
scope.add(member.name);
}
}
return scope;
}
factory _LocalNameScope.forClassTypeAlias(
_LocalNameScope enclosing, ClassTypeAlias node) {
_LocalNameScope scope = new _LocalNameScope(enclosing);
scope.addTypeParameters(node.typeParameters);
return scope;
}
factory _LocalNameScope.forConstructor(
_LocalNameScope enclosing, ConstructorDeclaration node) {
_LocalNameScope scope = new _LocalNameScope(enclosing);
scope.addFormalParameters(node.parameters);
return scope;
}
factory _LocalNameScope.forFunction(
_LocalNameScope enclosing, FunctionDeclaration node) {
_LocalNameScope scope = new _LocalNameScope(enclosing);
scope.addTypeParameters(node.functionExpression.typeParameters);
scope.addFormalParameters(node.functionExpression.parameters);
return scope;
}
factory _LocalNameScope.forFunctionTypeAlias(
_LocalNameScope enclosing, FunctionTypeAlias node) {
_LocalNameScope scope = new _LocalNameScope(enclosing);
scope.addTypeParameters(node.typeParameters);
return scope;
}
factory _LocalNameScope.forMethod(
_LocalNameScope enclosing, MethodDeclaration node) {
_LocalNameScope scope = new _LocalNameScope(enclosing);
scope.addTypeParameters(node.typeParameters);
scope.addFormalParameters(node.parameters);
return scope;
}
factory _LocalNameScope.forUnit(CompilationUnit node) {
_LocalNameScope scope = new _LocalNameScope(null);
for (CompilationUnitMember declaration in node.declarations) {
if (declaration is NamedCompilationUnitMember) {
scope.add(declaration.name);
} else if (declaration is TopLevelVariableDeclaration) {
scope.addVariableNames(declaration.variables);
}
}
return scope;
}
void add(SimpleIdentifier identifier) {
if (identifier != null) {
names ??= new Set<String>();
names.add(identifier.name);
}
}
void addFormalParameters(FormalParameterList parameterList) {
if (parameterList != null) {
parameterList.parameters
.map((p) => p is NormalFormalParameter ? p.identifier : null)
.forEach(add);
}
}
void addTypeParameters(TypeParameterList typeParameterList) {
if (typeParameterList != null) {
typeParameterList.typeParameters.map((p) => p.name).forEach(add);
}
}
void addVariableNames(VariableDeclarationList variableList) {
for (VariableDeclaration variable in variableList.variables) {
add(variable.name);
}
}
bool contains(String name) {
if (names != null && names.contains(name)) {
return true;
}
if (enclosing != null) {
return enclosing.contains(name);
}
return false;
}
}
class _ReferencedNamesComputer extends GeneralizingAstVisitor {
final Set<String> names = new Set<String>();
final Set<String> importPrefixNames = new Set<String>();
_LocalNameScope localScope = new _LocalNameScope(null);
@override
visitBlock(Block node) {
_LocalNameScope outerScope = localScope;
try {
localScope = new _LocalNameScope.forBlock(localScope, node);
super.visitBlock(node);
} finally {
localScope = outerScope;
}
}
@override
visitClassDeclaration(ClassDeclaration node) {
_LocalNameScope outerScope = localScope;
try {
localScope = new _LocalNameScope.forClass(localScope, node);
super.visitClassDeclaration(node);
} finally {
localScope = outerScope;
}
}
@override
visitClassTypeAlias(ClassTypeAlias node) {
_LocalNameScope outerScope = localScope;
try {
localScope = new _LocalNameScope.forClassTypeAlias(localScope, node);
super.visitClassTypeAlias(node);
} finally {
localScope = outerScope;
}
}
@override
visitCompilationUnit(CompilationUnit node) {
localScope = new _LocalNameScope.forUnit(node);
super.visitCompilationUnit(node);
}
@override
visitConstructorDeclaration(ConstructorDeclaration node) {
_LocalNameScope outerScope = localScope;
try {
localScope = new _LocalNameScope.forConstructor(localScope, node);
super.visitConstructorDeclaration(node);
} finally {
localScope = outerScope;
}
}
@override
visitConstructorName(ConstructorName node) {
if (node.parent is! ConstructorDeclaration) {
super.visitConstructorName(node);
}
}
@override
visitFunctionDeclaration(FunctionDeclaration node) {
_LocalNameScope outerScope = localScope;
try {
localScope = new _LocalNameScope.forFunction(localScope, node);
super.visitFunctionDeclaration(node);
} finally {
localScope = outerScope;
}
}
@override
visitFunctionTypeAlias(FunctionTypeAlias node) {
_LocalNameScope outerScope = localScope;
try {
localScope = new _LocalNameScope.forFunctionTypeAlias(localScope, node);
super.visitFunctionTypeAlias(node);
} finally {
localScope = outerScope;
}
}
@override
visitImportDirective(ImportDirective node) {
if (node.prefix != null) {
importPrefixNames.add(node.prefix.name);
}
super.visitImportDirective(node);
}
@override
visitMethodDeclaration(MethodDeclaration node) {
_LocalNameScope outerScope = localScope;
try {
localScope = new _LocalNameScope.forMethod(localScope, node);
super.visitMethodDeclaration(node);
} finally {
localScope = outerScope;
}
}
@override
visitSimpleIdentifier(SimpleIdentifier node) {
// Ignore all declarations.
if (node.inDeclarationContext()) {
return;
}
// Ignore class names references from constructors.
AstNode parent = node.parent;
if (parent is ConstructorDeclaration && parent.returnType == node) {
return;
}
// Prepare name.
String name = node.name;
// Ignore names shadowed by local elements.
if (node.isQualified || _isNameExpressionLabel(parent)) {
// Cannot be local.
} else {
if (localScope.contains(name)) {
return;
}
if (importPrefixNames.contains(name)) {
return;
}
}
// Do add the name.
names.add(name);
}
static bool _isNameExpressionLabel(AstNode parent) {
if (parent is Label) {
AstNode parent2 = parent?.parent;
return parent2 is NamedExpression && parent2.name == parent;
}
return false;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/byte_store.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 'cache.dart';
/**
* Store of bytes associated with string keys.
*
* Each key must be not longer than 100 characters and consist of only `[a-z]`,
* `[0-9]`, `.` and `_` characters. The key cannot be an empty string, the
* literal `.`, or contain the sequence `..`.
*
* Note that associations are not guaranteed to be persistent. The value
* associated with a key can change or become `null` at any point in time.
*
* TODO(scheglov) Research using asynchronous API.
*/
abstract class ByteStore {
/**
* Return the bytes associated with the given [key].
* Return `null` if the association does not exist.
*/
List<int> get(String key);
/**
* Associate the given [bytes] with the [key].
*/
void put(String key, List<int> bytes);
}
/**
* [ByteStore] which stores data only in memory.
*/
class MemoryByteStore implements ByteStore {
final Map<String, List<int>> _map = {};
@override
List<int> get(String key) {
return _map[key];
}
@override
void put(String key, List<int> bytes) {
_map[key] = bytes;
}
}
/**
* A wrapper around [ByteStore] which adds an in-memory LRU cache to it.
*/
class MemoryCachingByteStore implements ByteStore {
final ByteStore _store;
final Cache<String, List<int>> _cache;
MemoryCachingByteStore(this._store, int maxSizeBytes)
: _cache = new Cache<String, List<int>>(maxSizeBytes, (v) => v.length);
@override
List<int> get(String key) {
return _cache.get(key, () => _store.get(key));
}
@override
void put(String key, List<int> bytes) {
_store.put(key, bytes);
_cache.put(key, bytes);
}
}
/**
* [ByteStore] which does not store any data.
*/
class NullByteStore implements ByteStore {
@override
List<int> get(String key) => null;
@override
void put(String key, List<int> bytes) {}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/analysis_context_collection.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/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/dart/analysis/context_locator.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/dart/analysis/byte_store.dart';
import 'package:analyzer/src/dart/analysis/context_builder.dart';
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:meta/meta.dart';
/// An implementation of [AnalysisContextCollection].
class AnalysisContextCollectionImpl implements AnalysisContextCollection {
/// The resource provider used to access the file system.
final ResourceProvider resourceProvider;
/// The list of analysis contexts.
final List<AnalysisContext> contexts = [];
/// Initialize a newly created analysis context manager.
AnalysisContextCollectionImpl(
{bool enableIndex: false,
@deprecated ByteStore byteStore,
@deprecated FileContentOverlay fileContentOverlay,
@required List<String> includedPaths,
List<String> excludedPaths,
ResourceProvider resourceProvider,
String sdkPath})
: resourceProvider =
resourceProvider ?? PhysicalResourceProvider.INSTANCE {
_throwIfAnyNotAbsoluteNormalizedPath(includedPaths);
if (sdkPath != null) {
_throwIfNotAbsoluteNormalizedPath(sdkPath);
}
var contextLocator = new ContextLocator(
resourceProvider: this.resourceProvider,
);
var roots = contextLocator.locateRoots(
includedPaths: includedPaths,
excludedPaths: excludedPaths,
);
for (var root in roots) {
var contextBuilder = new ContextBuilderImpl(
resourceProvider: this.resourceProvider,
);
var context = contextBuilder.createContext(
byteStore: byteStore,
contextRoot: root,
enableIndex: enableIndex,
fileContentOverlay: fileContentOverlay,
sdkPath: sdkPath,
);
contexts.add(context);
}
}
@override
AnalysisContext contextFor(String path) {
_throwIfNotAbsoluteNormalizedPath(path);
for (var context in contexts) {
if (context.contextRoot.isAnalyzed(path)) {
return context;
}
}
throw new StateError('Unable to find the context to $path');
}
/// Check every element with [_throwIfNotAbsoluteNormalizedPath].
void _throwIfAnyNotAbsoluteNormalizedPath(List<String> paths) {
for (var path in paths) {
_throwIfNotAbsoluteNormalizedPath(path);
}
}
/// The driver supports only absolute normalized paths, this method is used
/// to validate any input paths to prevent errors later.
void _throwIfNotAbsoluteNormalizedPath(String path) {
var pathContext = resourceProvider.pathContext;
if (!pathContext.isAbsolute(path) || pathContext.normalize(path) != path) {
throw new ArgumentError(
'Only absolute normalized paths are supported: $path');
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/file_byte_store.dart | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:path/path.dart';
import 'byte_store.dart';
import 'fletcher16.dart';
/**
* The request that is sent from the main isolate to the clean-up isolate.
*/
class CacheCleanUpRequest {
final String cachePath;
final int maxSizeBytes;
final SendPort replyTo;
CacheCleanUpRequest(this.cachePath, this.maxSizeBytes, this.replyTo);
}
/**
* [ByteStore] that stores values as files and performs cache eviction.
*
* Only the process that manages the cache, e.g. Analysis Server, should use
* this class. Other processes, e.g. Analysis Server plugins, should use
* [FileByteStore] instead and let the main process to perform eviction.
*/
class EvictingFileByteStore implements ByteStore {
static bool _cleanUpSendPortShouldBePrepared = true;
static SendPort _cleanUpSendPort;
final String _cachePath;
final int _maxSizeBytes;
final FileByteStore _fileByteStore;
int _bytesWrittenSinceCleanup = 0;
bool _evictionIsolateIsRunning = false;
EvictingFileByteStore(this._cachePath, this._maxSizeBytes)
: _fileByteStore = new FileByteStore(_cachePath) {
_requestCacheCleanUp();
}
@override
List<int> get(String key) => _fileByteStore.get(key);
@override
void put(String key, List<int> bytes) {
_fileByteStore.put(key, bytes);
// Update the current size.
_bytesWrittenSinceCleanup += bytes.length;
if (_bytesWrittenSinceCleanup > _maxSizeBytes ~/ 8) {
_requestCacheCleanUp();
}
}
/**
* If the cache clean up process has not been requested yet, request it.
*/
Future<void> _requestCacheCleanUp() async {
if (_cleanUpSendPortShouldBePrepared) {
_cleanUpSendPortShouldBePrepared = false;
ReceivePort response = new ReceivePort();
await Isolate.spawn(_cacheCleanUpFunction, response.sendPort);
_cleanUpSendPort = await response.first as SendPort;
} else {
while (_cleanUpSendPort == null) {
await new Future.delayed(new Duration(milliseconds: 100), () {});
}
}
if (!_evictionIsolateIsRunning) {
_evictionIsolateIsRunning = true;
try {
ReceivePort response = new ReceivePort();
_cleanUpSendPort.send(new CacheCleanUpRequest(
_cachePath, _maxSizeBytes, response.sendPort));
await response.first;
} finally {
_evictionIsolateIsRunning = false;
_bytesWrittenSinceCleanup = 0;
}
}
}
/**
* This function is started in a new isolate, receives cache folder clean up
* requests and evicts older files from the folder.
*/
static void _cacheCleanUpFunction(message) {
SendPort initialReplyTo = message;
ReceivePort port = new ReceivePort();
initialReplyTo.send(port.sendPort);
port.listen((request) {
if (request is CacheCleanUpRequest) {
_cleanUpFolder(request.cachePath, request.maxSizeBytes);
// Let the client know that we're done.
request.replyTo.send(true);
}
});
}
static void _cleanUpFolder(String cachePath, int maxSizeBytes) {
// Prepare the list of files and their statistics.
List<File> files = <File>[];
Map<File, FileStat> fileStatMap = {};
int currentSizeBytes = 0;
List<FileSystemEntity> resources =
new Directory(cachePath).listSync(recursive: true);
for (FileSystemEntity resource in resources) {
if (resource is File) {
try {
final FileStat fileStat = resource.statSync();
// Make sure that the file was not deleted out from under us (a return
// value of FileSystemEntityType.notFound).
if (fileStat.type == FileSystemEntityType.file) {
files.add(resource);
fileStatMap[resource] = fileStat;
currentSizeBytes += fileStat.size;
}
} catch (_) {}
}
}
files.sort((a, b) {
return fileStatMap[a].accessed.millisecondsSinceEpoch -
fileStatMap[b].accessed.millisecondsSinceEpoch;
});
// Delete files until the current size is less than the max.
for (File file in files) {
if (currentSizeBytes < maxSizeBytes) {
break;
}
try {
file.deleteSync();
} catch (_) {}
currentSizeBytes -= fileStatMap[file].size;
}
}
}
/**
* [ByteStore] that stores values as files.
*/
class FileByteStore implements ByteStore {
static final FileByteStoreValidator _validator = new FileByteStoreValidator();
static final _dotCodeUnit = '.'.codeUnitAt(0);
final String _cachePath;
final String _tempSuffix;
final Map<String, List<int>> _writeInProgress = {};
final FuturePool _pool = new FuturePool(20);
/**
* If the same cache path is used from more than one isolate of the same
* process, then a unique [tempNameSuffix] must be provided for each isolate.
*/
FileByteStore(this._cachePath, {String tempNameSuffix: ''})
: _tempSuffix =
'-temp-$pid${tempNameSuffix.isEmpty ? '' : '-$tempNameSuffix'}';
@override
List<int> get(String key) {
if (!_canShard(key)) return null;
List<int> bytes = _writeInProgress[key];
if (bytes != null) {
return bytes;
}
try {
var shardPath = _getShardPath(key);
var path = join(shardPath, key);
var bytes = new File(path).readAsBytesSync();
return _validator.getData(bytes);
} catch (_) {
// ignore exceptions
return null;
}
}
@override
void put(String key, List<int> bytes) {
if (!_canShard(key)) return;
_writeInProgress[key] = bytes;
final List<int> wrappedBytes = _validator.wrapData(bytes);
// We don't wait for the write and rename to complete.
_pool.execute(() {
var tempPath = join(_cachePath, '$key$_tempSuffix');
var tempFile = new File(tempPath);
return tempFile.writeAsBytes(wrappedBytes).then((_) {
var shardPath = _getShardPath(key);
return Directory(shardPath).create(recursive: true).then((_) {
var path = join(shardPath, key);
return tempFile.rename(path);
});
}).catchError((_) {
// ignore exceptions
}).whenComplete(() {
if (_writeInProgress[key] == bytes) {
_writeInProgress.remove(key);
}
});
});
}
String _getShardPath(String key) {
var shardName = key.substring(0, 2);
return join(_cachePath, shardName);
}
static bool _canShard(String key) {
return key.length > 2 &&
key.codeUnitAt(0) != _dotCodeUnit &&
key.codeUnitAt(1) != _dotCodeUnit;
}
}
/**
* Generally speaking, we cannot guarantee that any data written into a file
* will stay the same - there is always a chance of a hardware problem, file
* system problem, truncated data, etc.
*
* So, we need to embed some validation into data itself. This class append the
* version and the checksum to data.
*/
class FileByteStoreValidator {
static const List<int> _VERSION = const [0x01, 0x00];
/**
* If the [rawBytes] have the valid version and checksum, extract and
* return the data from it. Otherwise return `null`.
*/
List<int> getData(List<int> rawBytes) {
// There must be at least the version and the checksum in the raw bytes.
if (rawBytes.length < 4) {
return null;
}
int len = rawBytes.length - 4;
// Check the version.
if (rawBytes[len + 0] != _VERSION[0] || rawBytes[len + 1] != _VERSION[1]) {
return null;
}
// Check the checksum of the data.
List<int> data = rawBytes.sublist(0, len);
int checksum = fletcher16(data);
if (rawBytes[len + 2] != checksum & 0xFF ||
rawBytes[len + 3] != (checksum >> 8) & 0xFF) {
return null;
}
// OK, the data is probably valid.
return data;
}
/**
* Return bytes that include the given [data] plus the current version and
* the checksum of the [data].
*/
List<int> wrapData(List<int> data) {
int len = data.length;
var bytes = new Uint8List(len + 4);
// Put the data.
bytes.setRange(0, len, data);
// Put the version.
bytes[len + 0] = _VERSION[0];
bytes[len + 1] = _VERSION[1];
// Put the checksum of the data.
int checksum = fletcher16(data);
bytes[len + 2] = checksum & 0xFF;
bytes[len + 3] = (checksum >> 8) & 0xFF;
return bytes;
}
}
class FuturePool {
int _available;
List waiting = [];
FuturePool(this._available);
void execute(Future Function() fn) {
if (_available > 0) {
_run(fn);
} else {
waiting.add(fn);
}
}
void _run(Future Function() fn) {
_available--;
fn().whenComplete(() {
_available++;
if (waiting.isNotEmpty) {
_run(waiting.removeAt(0));
}
});
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/restricted_analysis_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.
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/src/context/context.dart';
import 'package:analyzer/src/dart/analysis/session.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/type_system.dart';
/// This class is a temporary step toward migrating Analyzer clients to the
/// new API. It guards against attempts to use any [AnalysisContext]
/// functionality (which is task based), except what we intend to expose
/// through the new API.
class RestrictedAnalysisContext implements AnalysisContextImpl {
final SynchronousSession synchronousSession;
@override
final SourceFactory sourceFactory;
RestrictedAnalysisContext(this.synchronousSession, this.sourceFactory);
@override
AnalysisOptionsImpl get analysisOptions => synchronousSession.analysisOptions;
@override
DeclaredVariables get declaredVariables =>
synchronousSession.declaredVariables;
@override
TypeProvider get typeProvider => synchronousSession.typeProvider;
@override
set typeProvider(TypeProvider typeProvider) {
synchronousSession.typeProvider = typeProvider;
}
@override
TypeSystem get typeSystem => synchronousSession.typeSystem;
noSuchMethod(Invocation invocation) {
return super.noSuchMethod(invocation);
}
void clearTypeProvider() {
synchronousSession.clearTypeProvider();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/driver_based_analysis_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.
import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/context_root.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/driver.dart' show AnalysisDriver;
import 'package:analyzer/src/generated/engine.dart' show AnalysisOptions;
/**
* An analysis context whose implementation is based on an analysis driver.
*/
class DriverBasedAnalysisContext implements AnalysisContext {
/**
* The resource provider used to access the file system.
*/
final ResourceProvider resourceProvider;
@override
final ContextRoot contextRoot;
/**
* The driver on which this context is based.
*/
final AnalysisDriver driver;
/**
* Initialize a newly created context that uses the given [resourceProvider]
* to access the file system and that is based on the given analysis [driver].
*/
DriverBasedAnalysisContext(
this.resourceProvider, this.contextRoot, this.driver) {
driver.analysisContext = this;
}
@override
AnalysisOptions get analysisOptions => driver.analysisOptions;
@override
AnalysisSession get currentSession => driver.currentSession;
@deprecated
@override
List<String> get excludedPaths => contextRoot.excludedPaths.toList();
@deprecated
@override
List<String> get includedPaths => contextRoot.includedPaths.toList();
@deprecated
@override
Iterable<String> analyzedFiles() {
return contextRoot.analyzedFiles();
}
@deprecated
@override
bool isAnalyzed(String path) {
return contextRoot.isAnalyzed(path);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/library_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.
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/element/element.dart'
show CompilationUnitElement, LibraryElement;
import 'package:analyzer/src/dart/analysis/byte_store.dart';
import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:analyzer/src/dart/analysis/library_graph.dart';
import 'package:analyzer/src/dart/analysis/performance_logger.dart';
import 'package:analyzer/src/dart/analysis/restricted_analysis_context.dart';
import 'package:analyzer/src/dart/analysis/session.dart';
import 'package:analyzer/src/dart/element/inheritance_manager3.dart';
import 'package:analyzer/src/dart/element/type_provider.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisContext, AnalysisOptions;
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary/package_bundle_reader.dart';
import 'package:analyzer/src/summary2/link.dart' as link2;
import 'package:analyzer/src/summary2/linked_bundle_context.dart';
import 'package:analyzer/src/summary2/linked_element_factory.dart';
import 'package:analyzer/src/summary2/reference.dart';
import 'package:meta/meta.dart';
var counterLinkedLibraries = 0;
var counterLoadedLibraries = 0;
var timerBundleToBytes = Stopwatch();
var timerInputLibraries = Stopwatch();
var timerLinking = Stopwatch();
var timerLoad2 = Stopwatch();
/**
* Context information necessary to analyze one or more libraries within an
* [AnalysisDriver].
*
* Currently this is implemented as a wrapper around [AnalysisContext].
*/
class LibraryContext {
static const _maxLinkedDataInBytes = 64 * 1024 * 1024;
final PerformanceLog logger;
final ByteStore byteStore;
final AnalysisSession analysisSession;
final SummaryDataStore externalSummaries;
final SummaryDataStore store = new SummaryDataStore([]);
/// The size of the linked data that is loaded by this context.
/// When it reaches [_maxLinkedDataInBytes] the whole context is thrown away.
/// We use it as an approximation for the heap size of elements.
int _linkedDataInBytes = 0;
RestrictedAnalysisContext analysisContext;
LinkedElementFactory elementFactory;
InheritanceManager3 inheritanceManager;
var loadedBundles = Set<LibraryCycle>.identity();
LibraryContext({
@required AnalysisSession session,
@required PerformanceLog logger,
@required ByteStore byteStore,
@required FileSystemState fsState,
@required AnalysisOptions analysisOptions,
@required DeclaredVariables declaredVariables,
@required SourceFactory sourceFactory,
@required this.externalSummaries,
@required FileState targetLibrary,
}) : this.logger = logger,
this.byteStore = byteStore,
this.analysisSession = session {
if (externalSummaries != null) {
store.addStore(externalSummaries);
}
var synchronousSession =
SynchronousSession(analysisOptions, declaredVariables);
analysisContext = new RestrictedAnalysisContext(
synchronousSession,
sourceFactory,
);
_createElementFactory();
load2(targetLibrary);
inheritanceManager = new InheritanceManager3(analysisContext.typeSystem);
}
/**
* The type provider used in this context.
*/
TypeProvider get typeProvider => analysisContext.typeProvider;
/**
* Computes a [CompilationUnitElement] for the given library/unit pair.
*/
CompilationUnitElement computeUnitElement(FileState library, FileState unit) {
var reference = elementFactory.rootReference
.getChild(library.uriStr)
.getChild('@unit')
.getChild(unit.uriStr);
return elementFactory.elementOfReference(reference);
}
/**
* Get the [LibraryElement] for the given library.
*/
LibraryElement getLibraryElement(FileState library) {
return elementFactory.libraryOfUri(library.uriStr);
}
/**
* Return `true` if the given [uri] is known to be a library.
*/
bool isLibraryUri(Uri uri) {
String uriStr = uri.toString();
return elementFactory.isLibraryUri(uriStr);
}
/// Load data required to access elements of the given [targetLibrary].
void load2(FileState targetLibrary) {
timerLoad2.start();
var inputBundles = <LinkedNodeBundle>[];
var librariesTotal = 0;
var librariesLoaded = 0;
var librariesLinked = 0;
var librariesLinkedTimer = Stopwatch();
var inputsTimer = Stopwatch();
var bytesGet = 0;
var bytesPut = 0;
void loadBundle(LibraryCycle cycle) {
if (!loadedBundles.add(cycle)) return;
librariesTotal += cycle.libraries.length;
cycle.directDependencies.forEach(loadBundle);
var key = cycle.transitiveSignature + '.linked_bundle';
var bytes = byteStore.get(key);
if (bytes == null) {
librariesLinkedTimer.start();
timerInputLibraries.start();
inputsTimer.start();
var inputLibraries = <link2.LinkInputLibrary>[];
for (var libraryFile in cycle.libraries) {
var librarySource = libraryFile.source;
if (librarySource == null) continue;
var inputUnits = <link2.LinkInputUnit>[];
var partIndex = -1;
for (var file in libraryFile.libraryFiles) {
var isSynthetic = !file.exists;
var unit = file.parse();
String partUriStr;
if (partIndex >= 0) {
partUriStr = libraryFile.unlinked2.parts[partIndex];
}
partIndex++;
inputUnits.add(
link2.LinkInputUnit(
partUriStr,
file.source,
isSynthetic,
unit,
),
);
}
inputLibraries.add(
link2.LinkInputLibrary(librarySource, inputUnits),
);
}
inputsTimer.stop();
timerInputLibraries.stop();
timerLinking.start();
var linkResult = link2.link(elementFactory, inputLibraries);
librariesLinked += cycle.libraries.length;
counterLinkedLibraries += linkResult.bundle.libraries.length;
timerLinking.stop();
timerBundleToBytes.start();
bytes = linkResult.bundle.toBuffer();
timerBundleToBytes.stop();
byteStore.put(key, bytes);
bytesPut += bytes.length;
counterUnlinkedLinkedBytes += bytes.length;
librariesLinkedTimer.stop();
} else {
// TODO(scheglov) Take / clear parsed units in files.
bytesGet += bytes.length;
librariesLoaded += cycle.libraries.length;
}
// We are about to load dart:core, but if we have just linked it, the
// linker might have set the type provider. So, clear it, and recreate
// the element factory - it is empty anyway.
if (!elementFactory.hasDartCore) {
analysisContext.clearTypeProvider();
_createElementFactory();
}
var bundle = LinkedNodeBundle.fromBuffer(bytes);
inputBundles.add(bundle);
elementFactory.addBundle(
LinkedBundleContext(elementFactory, bundle),
);
counterLoadedLibraries += bundle.libraries.length;
// Set informative data.
for (var libraryFile in cycle.libraries) {
for (var unitFile in libraryFile.libraryFiles) {
elementFactory.setInformativeData(
libraryFile.uriStr,
unitFile.uriStr,
unitFile.unlinked2.informativeData,
);
}
}
// We might have just linked dart:core, ensure the type provider.
_createElementFactoryTypeProvider();
}
logger.run('Prepare linked bundles', () {
var libraryCycle = targetLibrary.libraryCycle;
loadBundle(libraryCycle);
logger.writeln(
'[librariesTotal: $librariesTotal]'
'[librariesLoaded: $librariesLoaded]'
'[inputsTimer: ${inputsTimer.elapsedMilliseconds} ms]'
'[librariesLinked: $librariesLinked]'
'[librariesLinkedTimer: ${librariesLinkedTimer.elapsedMilliseconds} ms]'
'[bytesGet: $bytesGet][bytesPut: $bytesPut]',
);
});
// There might be a rare (and wrong) situation, when the external summaries
// already include the [targetLibrary]. When this happens, [loadBundle]
// exists without doing any work. But the type provider must be created.
_createElementFactoryTypeProvider();
timerLoad2.stop();
}
/// Return `true` if this context grew too large, and should be recreated.
///
/// It might have been used to analyze libraries that we don't need anymore,
/// and because loading libraries is not very expensive (but not free), the
/// simplest way to get rid of the garbage is to throw away everything.
bool pack() {
return _linkedDataInBytes > _maxLinkedDataInBytes;
}
void _createElementFactory() {
elementFactory = LinkedElementFactory(
analysisContext,
analysisSession,
Reference.root(),
);
if (externalSummaries != null) {
for (var bundle in externalSummaries.bundles) {
elementFactory.addBundle(
LinkedBundleContext(elementFactory, bundle.bundle2),
);
}
}
}
/// Ensure that type provider is created.
void _createElementFactoryTypeProvider() {
if (analysisContext.typeProvider != null) return;
var dartCore = elementFactory.libraryOfUri('dart:core');
var dartAsync = elementFactory.libraryOfUri('dart:async');
var typeProvider = TypeProviderImpl(dartCore, dartAsync);
analysisContext.typeProvider = typeProvider;
dartCore.createLoadLibraryFunction(typeProvider);
dartAsync.createLoadLibraryFunction(typeProvider);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/session.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:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/analysis/uri_converter.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/driver.dart' as driver;
import 'package:analyzer/src/dart/analysis/uri_converter.dart';
import 'package:analyzer/src/dart/element/type_provider.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl;
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
/// A concrete implementation of an analysis session.
class AnalysisSessionImpl implements AnalysisSession {
/// The analysis driver performing analysis for this session.
final driver.AnalysisDriver _driver;
/// The type provider being used by the analysis driver.
TypeProvider _typeProvider;
/// The type system being used by the analysis driver.
TypeSystem _typeSystem;
/// The URI converter used to convert between URI's and file paths.
UriConverter _uriConverter;
/// The cache of libraries for URIs.
final Map<String, LibraryElement> _uriToLibraryCache = {};
/// Initialize a newly created analysis session.
AnalysisSessionImpl(this._driver);
@override
AnalysisContext get analysisContext => _driver.analysisContext;
@override
DeclaredVariables get declaredVariables => _driver.declaredVariables;
@override
ResourceProvider get resourceProvider => _driver.resourceProvider;
@override
SourceFactory get sourceFactory => _driver.sourceFactory;
@override
Future<TypeProvider> get typeProvider async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
_checkConsistency();
if (_typeProvider == null) {
LibraryElement coreLibrary = await _driver.getLibraryByUri('dart:core');
LibraryElement asyncLibrary = await _driver.getLibraryByUri('dart:async');
_typeProvider = new TypeProviderImpl(coreLibrary, asyncLibrary);
}
return _typeProvider;
}
@override
Future<TypeSystem> get typeSystem async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
_checkConsistency();
if (_typeSystem == null) {
_typeSystem = new Dart2TypeSystem(await typeProvider);
}
return _typeSystem;
}
@override
UriConverter get uriConverter {
return _uriConverter ??= new DriverBasedUriConverter(_driver);
}
@deprecated
driver.AnalysisDriver getDriver() => _driver;
@override
Future<ErrorsResult> getErrors(String path) {
_checkConsistency();
return _driver.getErrors(path);
}
@override
FileResult getFile(String path) {
_checkConsistency();
return _driver.getFileSync(path);
}
@override
Future<LibraryElement> getLibraryByUri(String uri) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
_checkConsistency();
var libraryElement = _uriToLibraryCache[uri];
if (libraryElement == null) {
libraryElement = await _driver.getLibraryByUri(uri);
_uriToLibraryCache[uri] = libraryElement;
}
return libraryElement;
}
@deprecated
@override
Future<ParseResult> getParsedAst(String path) async => getParsedUnit(path);
@deprecated
@override
ParseResult getParsedAstSync(String path) => getParsedUnit(path);
@override
ParsedLibraryResult getParsedLibrary(String path) {
_checkConsistency();
return _driver.getParsedLibrary(path);
}
@override
ParsedLibraryResult getParsedLibraryByElement(LibraryElement element) {
_checkConsistency();
_checkElementOfThisSession(element);
return _driver.getParsedLibraryByUri(element.source.uri);
}
@override
ParsedUnitResult getParsedUnit(String path) {
_checkConsistency();
return _driver.parseFileSync(path);
}
@deprecated
@override
Future<ResolveResult> getResolvedAst(String path) => getResolvedUnit(path);
@override
Future<ResolvedLibraryResult> getResolvedLibrary(String path) {
_checkConsistency();
return _driver.getResolvedLibrary(path);
}
@override
Future<ResolvedLibraryResult> getResolvedLibraryByElement(
LibraryElement element) {
_checkConsistency();
_checkElementOfThisSession(element);
return _driver.getResolvedLibraryByUri(element.source.uri);
}
@override
Future<ResolvedUnitResult> getResolvedUnit(String path) {
_checkConsistency();
return _driver.getResult(path);
}
@override
Future<SourceKind> getSourceKind(String path) {
_checkConsistency();
return _driver.getSourceKind(path);
}
@override
Future<UnitElementResult> getUnitElement(String path) {
_checkConsistency();
return _driver.getUnitElement(path);
}
@override
Future<String> getUnitElementSignature(String path) {
_checkConsistency();
return _driver.getUnitElementSignature(path);
}
/// Check to see that results from this session will be consistent, and throw
/// an [InconsistentAnalysisException] if they might not be.
void _checkConsistency() {
if (_driver.currentSession != this) {
throw new InconsistentAnalysisException();
}
}
void _checkElementOfThisSession(Element element) {
if (element.session != this) {
throw new ArgumentError(
'(${element.runtimeType}) $element was not produced by '
'this session.');
}
}
}
/// Data structure containing information about the analysis session that is
/// available synchronously.
class SynchronousSession {
final AnalysisOptionsImpl analysisOptions;
final DeclaredVariables declaredVariables;
TypeProvider _typeProvider;
TypeSystem _typeSystem;
SynchronousSession(this.analysisOptions, this.declaredVariables);
TypeProvider get typeProvider => _typeProvider;
set typeProvider(TypeProvider typeProvider) {
if (_typeProvider != null) {
throw StateError('TypeProvider can be set only once.');
}
_typeProvider = typeProvider;
}
TypeSystem get typeSystem {
return _typeSystem ??= Dart2TypeSystem(
typeProvider,
implicitCasts: analysisOptions.implicitCasts,
strictInference: analysisOptions.strictInference,
);
}
void clearTypeProvider() {
_typeProvider = null;
_typeSystem = null;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/session_helper.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:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/element/element.dart';
/// A wrapper around [AnalysisSession] that provides additional utilities.
///
/// The methods in this class that return analysis results will throw an
/// [InconsistentAnalysisException] if the result to be returned might be
/// inconsistent with any previously returned results.
class AnalysisSessionHelper {
final AnalysisSession session;
final Map<String, ResolvedLibraryResult> _resolvedLibraries = {};
AnalysisSessionHelper(this.session);
/// Return the [ClassElement] with the given [className] that is exported
/// from the library with the given [libraryUri], or `null` if the library
/// does not export a class with such name.
Future<ClassElement> getClass(String libraryUri, String className) async {
var libraryElement = await session.getLibraryByUri(libraryUri);
var element = libraryElement.exportNamespace.get(className);
if (element is ClassElement) {
return element;
} else {
return null;
}
}
/// Return the declaration of the [element], or `null` is the [element]
/// is synthetic.
Future<ElementDeclarationResult> getElementDeclaration(
Element element) async {
var libraryPath = element.library.source.fullName;
var resolvedLibrary = await _getResolvedLibrary(libraryPath);
return resolvedLibrary.getElementDeclaration(element);
}
/// Return the resolved unit that declares the given [element].
Future<ResolvedUnitResult> getResolvedUnitByElement(Element element) async {
var libraryPath = element.library.source.fullName;
var resolvedLibrary = await _getResolvedLibrary(libraryPath);
var unitPath = element.source.fullName;
return resolvedLibrary.units.singleWhere((resolvedUnit) {
return resolvedUnit.path == unitPath;
});
}
/// Return the [PropertyAccessorElement] with the given [name] that is
/// exported from the library with the given [uri], or `null` if the
/// library does not export a top-level accessor with such name.
Future<PropertyAccessorElement> getTopLevelPropertyAccessor(
String uri, String name) async {
var libraryElement = await session.getLibraryByUri(uri);
var element = libraryElement.exportNamespace.get(name);
if (element is PropertyAccessorElement) {
return element;
} else {
return null;
}
}
/// Return a newly resolved, or cached library with the given [path].
Future<ResolvedLibraryResult> _getResolvedLibrary(String path) async {
var result = _resolvedLibraries[path];
if (result == null) {
result = await session.getResolvedLibrary(path);
_resolvedLibraries[path] = result;
}
return result;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/driver.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:typed_data';
import 'package:analyzer/dart/analysis/analysis_context.dart' as api;
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart' show LibraryElement;
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/context/context_root.dart';
import 'package:analyzer/src/dart/analysis/byte_store.dart';
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:analyzer/src/dart/analysis/file_tracker.dart';
import 'package:analyzer/src/dart/analysis/index.dart';
import 'package:analyzer/src/dart/analysis/library_analyzer.dart';
import 'package:analyzer/src/dart/analysis/library_context.dart';
import 'package:analyzer/src/dart/analysis/performance_logger.dart';
import 'package:analyzer/src/dart/analysis/results.dart';
import 'package:analyzer/src/dart/analysis/search.dart';
import 'package:analyzer/src/dart/analysis/session.dart';
import 'package:analyzer/src/dart/analysis/status.dart';
import 'package:analyzer/src/dart/analysis/testing_data.dart';
import 'package:analyzer/src/diagnostic/diagnostic.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart'
show
AnalysisContext,
AnalysisEngine,
AnalysisOptions,
AnalysisOptionsImpl,
PerformanceStatistics;
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:analyzer/src/lint/registry.dart' as linter;
import 'package:analyzer/src/summary/api_signature.dart';
import 'package:analyzer/src/summary/format.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary/package_bundle_reader.dart';
import 'package:meta/meta.dart';
/// TODO(scheglov) We could use generalized Function in [AnalysisDriverTestView],
/// but this breaks `AnalysisContext` and code generation. So, for now let's
/// work around them, and rewrite generators to [AnalysisDriver].
typedef Future<void> WorkToWaitAfterComputingResult(String path);
/// This class computes [AnalysisResult]s for Dart files.
///
/// Let the set of "explicitly analyzed files" denote the set of paths that have
/// been passed to [addFile] but not subsequently passed to [removeFile]. Let
/// the "current analysis results" denote the map from the set of explicitly
/// analyzed files to the most recent [AnalysisResult] delivered to [results]
/// for each file. Let the "current file state" represent a map from file path
/// to the file contents most recently read from that file, or fetched from the
/// content cache (considering all possible possible file paths, regardless of
/// whether they're in the set of explicitly analyzed files). Let the
/// "analysis state" be either "analyzing" or "idle".
///
/// (These are theoretical constructs; they may not necessarily reflect data
/// structures maintained explicitly by the driver).
///
/// Then we make the following guarantees:
///
/// - Whenever the analysis state is idle, the current analysis results are
/// consistent with the current file state.
///
/// - A call to [addFile] or [changeFile] causes the analysis state to
/// transition to "analyzing", and schedules the contents of the given
/// files to be read into the current file state prior to the next time
/// the analysis state transitions back to "idle".
///
/// - If at any time the client stops making calls to [addFile], [changeFile],
/// and [removeFile], the analysis state will eventually transition back to
/// "idle" after a finite amount of processing.
///
/// As a result of these guarantees, a client may ensure that the analysis
/// results are "eventually consistent" with the file system by simply calling
/// [changeFile] any time the contents of a file on the file system have changed.
///
/// TODO(scheglov) Clean up the list of implicitly analyzed files.
class AnalysisDriver implements AnalysisDriverGeneric {
/// The version of data format, should be incremented on every format change.
static const int DATA_VERSION = 88;
/// The number of exception contexts allowed to write. Once this field is
/// zero, we stop writing any new exception contexts in this process.
static int allowedNumberOfContextsToWrite = 10;
/// Whether summary2 should be used to resynthesize elements.
@Deprecated('Clients should assume summary2 is used. '
'Summary1 support has been removed.')
static bool get useSummary2 => true;
/// The scheduler that schedules analysis work in this, and possibly other
/// analysis drivers.
final AnalysisDriverScheduler _scheduler;
/// The logger to write performed operations and performance to.
final PerformanceLog _logger;
/// The resource provider for working with files.
final ResourceProvider _resourceProvider;
/// The byte storage to get and put serialized data.
///
/// It can be shared with other [AnalysisDriver]s.
final ByteStore _byteStore;
/// The optional store with externally provided unlinked and corresponding
/// linked summaries. These summaries are always added to the store for any
/// file analysis.
final SummaryDataStore _externalSummaries;
/// This [ContentCache] is consulted for a file content before reading
/// the content from the file.
final FileContentOverlay _contentOverlay;
/// The analysis options to analyze with.
AnalysisOptionsImpl _analysisOptions;
/// The [SourceFactory] is used to resolve URIs to paths and restore URIs
/// from file paths.
SourceFactory _sourceFactory;
/// The declared environment variables.
DeclaredVariables declaredVariables = new DeclaredVariables();
/// Information about the context root being analyzed by this driver.
final ContextRoot contextRoot;
/// The analysis context that created this driver / session.
api.AnalysisContext analysisContext;
/// The salt to mix into all hashes used as keys for unlinked data.
final Uint32List _unlinkedSalt =
new Uint32List(2 + AnalysisOptionsImpl.unlinkedSignatureLength);
/// The salt to mix into all hashes used as keys for linked data.
final Uint32List _linkedSalt =
new Uint32List(2 + AnalysisOptions.signatureLength);
/// The set of priority files, that should be analyzed sooner.
final _priorityFiles = new LinkedHashSet<String>();
/// The mapping from the files for which analysis was requested using
/// [getResult] to the [Completer]s to report the result.
final _requestedFiles = <String, List<Completer<ResolvedUnitResult>>>{};
/// The mapping from the files for which analysis was requested using
/// [getResolvedLibrary] to the [Completer]s to report the result.
final _requestedLibraries =
<String, List<Completer<ResolvedLibraryResult>>>{};
/// The task that discovers available files. If this field is not `null`,
/// and the task is not completed, it should be performed and completed
/// before any name searching task.
_DiscoverAvailableFilesTask _discoverAvailableFilesTask;
/// The list of tasks to compute files defining a class member name.
final _definingClassMemberNameTasks = <_FilesDefiningClassMemberNameTask>[];
/// The list of tasks to compute files referencing a name.
final _referencingNameTasks = <_FilesReferencingNameTask>[];
/// The mapping from the files for which the index was requested using
/// [getIndex] to the [Completer]s to report the result.
final _indexRequestedFiles =
<String, List<Completer<AnalysisDriverUnitIndex>>>{};
/// The mapping from the files for which the unit element key was requested
/// using [getUnitElementSignature] to the [Completer]s to report the result.
final _unitElementSignatureFiles = <String, List<Completer<String>>>{};
/// The mapping from the files for which the unit element key was requested
/// using [getUnitElementSignature], and which were found to be parts without
/// known libraries, to the [Completer]s to report the result.
final _unitElementSignatureParts = <String, List<Completer<String>>>{};
/// The mapping from the files for which the unit element was requested using
/// [getUnitElement] to the [Completer]s to report the result.
final _unitElementRequestedFiles =
<String, List<Completer<UnitElementResult>>>{};
/// The mapping from the files for which the unit element was requested using
/// [getUnitElement], and which were found to be parts without known libraries,
/// to the [Completer]s to report the result.
final _unitElementRequestedParts =
<String, List<Completer<UnitElementResult>>>{};
/// The mapping from the files for which analysis was requested using
/// [getResult], and which were found to be parts without known libraries,
/// to the [Completer]s to report the result.
final _requestedParts = <String, List<Completer<ResolvedUnitResult>>>{};
/// The set of part files that are currently scheduled for analysis.
final _partsToAnalyze = new LinkedHashSet<String>();
/// The controller for the [results] stream.
final _resultController = new StreamController<ResolvedUnitResult>();
/// The stream that will be written to when analysis results are produced.
Stream<ResolvedUnitResult> _onResults;
/// Resolution signatures of the most recently produced results for files.
final Map<String, String> _lastProducedSignatures = {};
/// Cached results for [_priorityFiles].
final Map<String, ResolvedUnitResult> _priorityResults = {};
/// The controller for the [exceptions] stream.
final StreamController<ExceptionResult> _exceptionController =
new StreamController<ExceptionResult>();
/// The instance of the [Search] helper.
Search _search;
AnalysisDriverTestView _testView;
FileSystemState _fsState;
/// The [FileTracker] used by this driver.
FileTracker _fileTracker;
/// When this flag is set to `true`, the set of analyzed files must not change,
/// and all [AnalysisResult]s are cached infinitely.
///
/// The flag is intended to be used for non-interactive clients, like DDC,
/// which start a new analysis session, load a set of files, resolve all of
/// them, process the resolved units, and then throw away that whole session.
///
/// The key problem that this flag is solving is that the driver analyzes the
/// whole library when the result for a unit of the library is requested. So,
/// when the client requests sequentially the defining unit, then the first
/// part, then the second part, the driver has to perform analysis of the
/// library three times and every time throw away all the units except the one
/// which was requested. With this flag set to `true`, the driver can analyze
/// once and cache all the resolved units.
final bool disableChangesAndCacheAllResults;
/// Whether resolved units should be indexed.
final bool enableIndex;
/// The cache to use with [disableChangesAndCacheAllResults].
final Map<String, AnalysisResult> _allCachedResults = {};
/// The current analysis session.
AnalysisSessionImpl _currentSession;
/// The current library context, consistent with the [_currentSession].
///
/// TODO(scheglov) We probably should tie it into the session.
LibraryContext _libraryContext;
/// This function is invoked when the current session is about to be discarded.
/// The argument represents the path of the resource causing the session
/// to be discarded or `null` if there are multiple or this is unknown.
void Function(String) onCurrentSessionAboutToBeDiscarded;
/// If testing data is being retained, a pointer to the object that is
/// retaining the testing data. Otherwise `null`.
final TestingData testingData;
/// Create a new instance of [AnalysisDriver].
///
/// The given [SourceFactory] is cloned to ensure that it does not contain a
/// reference to a [AnalysisContext] in which it could have been used.
AnalysisDriver(
this._scheduler,
PerformanceLog logger,
this._resourceProvider,
this._byteStore,
this._contentOverlay,
this.contextRoot,
SourceFactory sourceFactory,
this._analysisOptions,
{this.disableChangesAndCacheAllResults: false,
this.enableIndex: false,
SummaryDataStore externalSummaries,
bool retainDataForTesting: false})
: _logger = logger,
_sourceFactory = sourceFactory.clone(),
_externalSummaries = externalSummaries,
testingData = retainDataForTesting ? TestingData() : null {
_createNewSession(null);
_onResults = _resultController.stream.asBroadcastStream();
_testView = new AnalysisDriverTestView(this);
_createFileTracker();
_scheduler.add(this);
_search = new Search(this);
}
/// Return the set of files explicitly added to analysis using [addFile].
Set<String> get addedFiles => _fileTracker.addedFiles;
/// Return the analysis options used to control analysis.
AnalysisOptions get analysisOptions => _analysisOptions;
/// Return the current analysis session.
AnalysisSession get currentSession => _currentSession;
/// Return the stream that produces [ExceptionResult]s.
Stream<ExceptionResult> get exceptions => _exceptionController.stream;
/// The current file system state.
FileSystemState get fsState => _fsState;
@override
bool get hasFilesToAnalyze {
return _fileTracker.hasChangedFiles ||
_requestedFiles.isNotEmpty ||
_requestedParts.isNotEmpty ||
_fileTracker.hasPendingFiles ||
_partsToAnalyze.isNotEmpty;
}
/// Return the set of files that are known at this moment. This set does not
/// always include all added files or all implicitly used file. If a file has
/// not been processed yet, it might be missing.
Set<String> get knownFiles => _fsState.knownFilePaths;
/// Return the path of the folder at the root of the context.
String get name => contextRoot?.root ?? '';
/// Return the number of files scheduled for analysis.
int get numberOfFilesToAnalyze => _fileTracker.numberOfPendingFiles;
/// Return the list of files that the driver should try to analyze sooner.
List<String> get priorityFiles => _priorityFiles.toList(growable: false);
@override
void set priorityFiles(List<String> priorityPaths) {
_priorityResults.keys
.toSet()
.difference(priorityPaths.toSet())
.forEach(_priorityResults.remove);
_priorityFiles.clear();
_priorityFiles.addAll(priorityPaths);
_scheduler.notify(this);
}
/// Return the [ResourceProvider] that is used to access the file system.
ResourceProvider get resourceProvider => _resourceProvider;
/// Return the [Stream] that produces [AnalysisResult]s for added files.
///
/// Note that the stream supports only one single subscriber.
///
/// Analysis starts when the [AnalysisDriverScheduler] is started and the
/// driver is added to it. The analysis state transitions to "analyzing" and
/// an analysis result is produced for every added file prior to the next time
/// the analysis state transitions to "idle".
///
/// At least one analysis result is produced for every file passed to
/// [addFile] or [changeFile] prior to the next time the analysis state
/// transitions to "idle", unless the file is later removed from analysis
/// using [removeFile]. Analysis results for other files are produced only if
/// the changes affect analysis results of other files.
///
/// More than one result might be produced for the same file, even if the
/// client does not change the state of the files.
///
/// Results might be produced even for files that have never been added
/// using [addFile], for example when [getResult] was called for a file.
Stream<ResolvedUnitResult> get results => _onResults;
/// Return the search support for the driver.
Search get search => _search;
/// Return the source factory used to resolve URIs to paths and restore URIs
/// from file paths.
SourceFactory get sourceFactory => _sourceFactory;
@visibleForTesting
AnalysisDriverTestView get test => _testView;
@override
AnalysisDriverPriority get workPriority {
if (_requestedFiles.isNotEmpty) {
return AnalysisDriverPriority.interactive;
}
if (_requestedLibraries.isNotEmpty) {
return AnalysisDriverPriority.interactive;
}
if (_discoverAvailableFilesTask != null &&
!_discoverAvailableFilesTask.isCompleted) {
return AnalysisDriverPriority.interactive;
}
if (_definingClassMemberNameTasks.isNotEmpty ||
_referencingNameTasks.isNotEmpty) {
return AnalysisDriverPriority.interactive;
}
if (_indexRequestedFiles.isNotEmpty) {
return AnalysisDriverPriority.interactive;
}
if (_unitElementSignatureFiles.isNotEmpty) {
return AnalysisDriverPriority.interactive;
}
if (_unitElementRequestedFiles.isNotEmpty) {
return AnalysisDriverPriority.interactive;
}
if (_priorityFiles.isNotEmpty) {
for (String path in _priorityFiles) {
if (_fileTracker.isFilePending(path)) {
return AnalysisDriverPriority.priority;
}
}
}
if (_fileTracker.hasChangedFiles) {
return AnalysisDriverPriority.changedFiles;
}
if (_fileTracker.hasPendingChangedFiles) {
return AnalysisDriverPriority.generalChanged;
}
if (_fileTracker.hasPendingImportFiles) {
return AnalysisDriverPriority.generalImportChanged;
}
if (_fileTracker.hasPendingErrorFiles) {
return AnalysisDriverPriority.generalWithErrors;
}
if (_fileTracker.hasPendingFiles) {
return AnalysisDriverPriority.general;
}
if (_requestedParts.isNotEmpty ||
_partsToAnalyze.isNotEmpty ||
_unitElementSignatureParts.isNotEmpty ||
_unitElementRequestedParts.isNotEmpty) {
return AnalysisDriverPriority.general;
}
_libraryContext = null;
return AnalysisDriverPriority.nothing;
}
@override
void addFile(String path) {
_throwIfNotAbsolutePath(path);
if (!_fsState.hasUri(path)) {
return;
}
if (AnalysisEngine.isDartFileName(path)) {
_fileTracker.addFile(path);
// If the file is known, it has already been read, even if it did not
// exist. Now we are notified that the file exists, so we need to
// re-read it and make sure that we invalidate signature of the files
// that reference it.
if (_fsState.knownFilePaths.contains(path)) {
_changeFile(path);
}
}
}
/// The file with the given [path] might have changed - updated, added or
/// removed. Or not, we don't know. Or it might have, but then changed back.
///
/// The [path] must be absolute and normalized.
///
/// The [path] can be any file - explicitly or implicitly analyzed, or neither.
///
/// Causes the analysis state to transition to "analyzing" (if it is not in
/// that state already). Schedules the file contents for [path] to be read
/// into the current file state prior to the next time the analysis state
/// transitions to "idle".
///
/// Invocation of this method will not prevent a [Future] returned from
/// [getResult] from completing with a result, but the result is not
/// guaranteed to be consistent with the new current file state after this
/// [changeFile] invocation.
void changeFile(String path) {
_throwIfNotAbsolutePath(path);
_throwIfChangesAreNotAllowed();
_changeFile(path);
}
/// Some state on which analysis depends has changed, so the driver needs to be
/// re-configured with the new state.
///
/// At least one of the optional parameters should be provided, but only those
/// that represent state that has actually changed need be provided.
void configure(
{AnalysisOptions analysisOptions, SourceFactory sourceFactory}) {
if (analysisOptions != null) {
_analysisOptions = analysisOptions;
}
if (sourceFactory != null) {
_sourceFactory = sourceFactory;
}
Iterable<String> addedFiles = _fileTracker.addedFiles;
_createFileTracker();
_fileTracker.addFiles(addedFiles);
}
/// Return a [Future] that completes when discovery of all files that are
/// potentially available is done, so that they are included in [knownFiles].
Future<void> discoverAvailableFiles() {
if (_discoverAvailableFilesTask != null &&
_discoverAvailableFilesTask.isCompleted) {
return new Future.value();
}
_discoverAvailableFiles();
_scheduler.notify(this);
return _discoverAvailableFilesTask.completer.future;
}
@override
void dispose() {
_scheduler.remove(this);
}
/// Return the cached [ResolvedUnitResult] for the Dart file with the given
/// [path]. If there is no cached result, return `null`. Usually only results
/// of priority files are cached.
///
/// The [path] must be absolute and normalized.
///
/// The [path] can be any file - explicitly or implicitly analyzed, or neither.
ResolvedUnitResult getCachedResult(String path) {
_throwIfNotAbsolutePath(path);
ResolvedUnitResult result = _priorityResults[path];
if (disableChangesAndCacheAllResults) {
result ??= _allCachedResults[path];
}
return result;
}
/// Return a [Future] that completes with the [ErrorsResult] for the Dart
/// file with the given [path]. If the file is not a Dart file or cannot
/// be analyzed, the [Future] completes with `null`.
///
/// The [path] must be absolute and normalized.
///
/// This method does not use analysis priorities, and must not be used in
/// interactive analysis, such as Analysis Server or its plugins.
Future<ErrorsResult> getErrors(String path) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
_throwIfNotAbsolutePath(path);
// Ask the analysis result without unit, so return cached errors.
// If no cached analysis result, it will be computed.
ResolvedUnitResult analysisResult = _computeAnalysisResult(path);
// If not computed yet, because a part file without a known library,
// we have to compute the full analysis result, with the unit.
analysisResult ??= await getResult(path);
if (analysisResult == null) {
return null;
}
return new ErrorsResultImpl(currentSession, path, analysisResult.uri,
analysisResult.lineInfo, analysisResult.isPart, analysisResult.errors);
}
/// Return a [Future] that completes with the list of added files that
/// define a class member with the given [name].
Future<List<String>> getFilesDefiningClassMemberName(String name) {
_discoverAvailableFiles();
var task = new _FilesDefiningClassMemberNameTask(this, name);
_definingClassMemberNameTasks.add(task);
_scheduler.notify(this);
return task.completer.future;
}
/// Return a [Future] that completes with the list of known files that
/// reference the given external [name].
Future<List<String>> getFilesReferencingName(String name) {
_discoverAvailableFiles();
var task = new _FilesReferencingNameTask(this, name);
_referencingNameTasks.add(task);
_scheduler.notify(this);
return task.completer.future;
}
/// Return the [FileResult] for the Dart file with the given [path].
///
/// The [path] must be absolute and normalized.
FileResult getFileSync(String path) {
_throwIfNotAbsolutePath(path);
FileState file = _fileTracker.verifyApiSignature(path);
return new FileResultImpl(
_currentSession, path, file.uri, file.lineInfo, file.isPart);
}
/// Return a [Future] that completes with the [AnalysisDriverUnitIndex] for
/// the file with the given [path], or with `null` if the file cannot be
/// analyzed.
Future<AnalysisDriverUnitIndex> getIndex(String path) {
_throwIfNotAbsolutePath(path);
if (!enableIndex) {
throw new ArgumentError('Indexing is not enabled.');
}
if (!_fsState.hasUri(path)) {
return new Future.value();
}
var completer = new Completer<AnalysisDriverUnitIndex>();
_indexRequestedFiles
.putIfAbsent(path, () => <Completer<AnalysisDriverUnitIndex>>[])
.add(completer);
_scheduler.notify(this);
return completer.future;
}
/// Return a [Future] that completes with the [LibraryElement] for the given
/// [uri], which is either resynthesized from the provided external summary
/// store, or built for a file to which the given [uri] is resolved.
///
/// Throw [ArgumentError] if the [uri] does not correspond to a file.
///
/// Throw [ArgumentError] if the [uri] corresponds to a part.
Future<LibraryElement> getLibraryByUri(String uri) async {
var uriObj = Uri.parse(uri);
var file = _fsState.getFileForUri(uriObj);
if (file.isUnresolved) {
throw ArgumentError('$uri cannot be resolved to a file.');
}
if (file.isExternalLibrary) {
return _createLibraryContext(file).getLibraryElement(file);
}
if (file.isPart) {
throw ArgumentError('$uri is not a library.');
}
UnitElementResult unitResult = await getUnitElement(file.path);
return unitResult.element.library;
}
/// Return a [ParsedLibraryResult] for the library with the given [path].
///
/// Throw [ArgumentError] if the given [path] is not the defining compilation
/// unit for a library (that is, is a part of a library).
///
/// The [path] must be absolute and normalized.
ParsedLibraryResult getParsedLibrary(String path) {
FileState file = _fsState.getFileForPath(path);
if (file.isExternalLibrary) {
return ParsedLibraryResultImpl.external(currentSession, file.uri);
}
if (file.isPart) {
throw ArgumentError('Is a part: $path');
}
var units = <ParsedUnitResult>[];
for (var unitFile in file.libraryFiles) {
var unitPath = unitFile.path;
if (unitPath != null) {
var unitResult = parseFileSync(unitPath);
units.add(unitResult);
}
}
return ParsedLibraryResultImpl(currentSession, path, file.uri, units);
}
/// Return a [ParsedLibraryResult] for the library with the given [uri].
///
/// Throw [ArgumentError] if the given [uri] is not the defining compilation
/// unit for a library (that is, is a part of a library).
ParsedLibraryResult getParsedLibraryByUri(Uri uri) {
FileState file = _fsState.getFileForUri(uri);
if (file.isExternalLibrary) {
return ParsedLibraryResultImpl.external(currentSession, file.uri);
}
if (file.isPart) {
throw ArgumentError('Is a part: $uri');
}
// The file is a local file, we can get the result.
return getParsedLibrary(file.path);
}
/// Return a [Future] that completes with a [ResolvedLibraryResult] for the
/// Dart library file with the given [path]. If the file is not a Dart file
/// or cannot be analyzed, the [Future] completes with `null`.
///
/// Throw [ArgumentError] if the given [path] is not the defining compilation
/// unit for a library (that is, is a part of a library).
///
/// The [path] must be absolute and normalized.
///
/// The [path] can be any file - explicitly or implicitly analyzed, or neither.
///
/// Invocation of this method causes the analysis state to transition to
/// "analyzing" (if it is not in that state already), the driver will produce
/// the resolution result for it, which is consistent with the current file
/// state (including new states of the files previously reported using
/// [changeFile]), prior to the next time the analysis state transitions
/// to "idle".
Future<ResolvedLibraryResult> getResolvedLibrary(String path) {
_throwIfNotAbsolutePath(path);
if (!_fsState.hasUri(path)) {
return new Future.value();
}
FileState file = _fsState.getFileForPath(path);
if (file.isExternalLibrary) {
return Future.value(
ResolvedLibraryResultImpl.external(currentSession, file.uri),
);
}
if (file.isPart) {
throw ArgumentError('Is a part: $path');
}
// Schedule analysis.
var completer = new Completer<ResolvedLibraryResult>();
_requestedLibraries
.putIfAbsent(path, () => <Completer<ResolvedLibraryResult>>[])
.add(completer);
_scheduler.notify(this);
return completer.future;
}
/// Return a [Future] that completes with a [ResolvedLibraryResult] for the
/// Dart library file with the given [uri].
///
/// Throw [ArgumentError] if the given [uri] is not the defining compilation
/// unit for a library (that is, is a part of a library).
///
/// Invocation of this method causes the analysis state to transition to
/// "analyzing" (if it is not in that state already), the driver will produce
/// the resolution result for it, which is consistent with the current file
/// state (including new states of the files previously reported using
/// [changeFile]), prior to the next time the analysis state transitions
/// to "idle".
Future<ResolvedLibraryResult> getResolvedLibraryByUri(Uri uri) {
FileState file = _fsState.getFileForUri(uri);
if (file.isExternalLibrary) {
return Future.value(
ResolvedLibraryResultImpl.external(currentSession, file.uri),
);
}
if (file.isPart) {
throw ArgumentError('Is a part: $uri');
}
// The file is a local file, we can get the result.
return getResolvedLibrary(file.path);
}
ApiSignature getResolvedUnitKeyByPath(String path) {
_throwIfNotAbsolutePath(path);
ApiSignature signature = getUnitKeyByPath(path);
var file = fsState.getFileForPath(path);
signature.addString(file.contentHash);
return signature;
}
/// Return a [Future] that completes with a [ResolvedUnitResult] for the Dart
/// file with the given [path]. If the file is not a Dart file or cannot
/// be analyzed, the [Future] completes with `null`.
///
/// The [path] must be absolute and normalized.
///
/// The [path] can be any file - explicitly or implicitly analyzed, or neither.
///
/// If the driver has the cached analysis result for the file, it is returned.
/// If [sendCachedToStream] is `true`, then the result is also reported into
/// the [results] stream, just as if it were freshly computed.
///
/// Otherwise causes the analysis state to transition to "analyzing" (if it is
/// not in that state already), the driver will produce the analysis result for
/// it, which is consistent with the current file state (including new states
/// of the files previously reported using [changeFile]), prior to the next
/// time the analysis state transitions to "idle".
Future<ResolvedUnitResult> getResult(String path,
{bool sendCachedToStream: false}) {
_throwIfNotAbsolutePath(path);
if (!_fsState.hasUri(path)) {
return new Future.value();
}
// Return the cached result.
{
ResolvedUnitResult result = getCachedResult(path);
if (result != null) {
if (sendCachedToStream) {
_resultController.add(result);
}
return new Future.value(result);
}
}
// Schedule analysis.
var completer = new Completer<ResolvedUnitResult>();
_requestedFiles
.putIfAbsent(path, () => <Completer<ResolvedUnitResult>>[])
.add(completer);
_scheduler.notify(this);
return completer.future;
}
/// Return a [Future] that completes with the [SourceKind] for the Dart
/// file with the given [path]. If the file is not a Dart file or cannot
/// be analyzed, the [Future] completes with `null`.
///
/// The [path] must be absolute and normalized.
Future<SourceKind> getSourceKind(String path) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
_throwIfNotAbsolutePath(path);
if (AnalysisEngine.isDartFileName(path)) {
FileState file = _fsState.getFileForPath(path);
return file.isPart ? SourceKind.PART : SourceKind.LIBRARY;
}
return null;
}
/// Return a [Future] that completes with the [UnitElementResult] for the
/// file with the given [path], or with `null` if the file cannot be analyzed.
Future<UnitElementResult> getUnitElement(String path) {
_throwIfNotAbsolutePath(path);
if (!_fsState.hasUri(path)) {
return new Future.value();
}
var completer = new Completer<UnitElementResult>();
_unitElementRequestedFiles
.putIfAbsent(path, () => <Completer<UnitElementResult>>[])
.add(completer);
_scheduler.notify(this);
return completer.future;
}
/// Return a [Future] that completes with the signature for the
/// [UnitElementResult] for the file with the given [path], or with `null` if
/// the file cannot be analyzed.
///
/// The signature is based the APIs of the files of the library (including
/// the file itself) of the requested file and the transitive closure of files
/// imported and exported by the library.
Future<String> getUnitElementSignature(String path) {
_throwIfNotAbsolutePath(path);
if (!_fsState.hasUri(path)) {
return new Future.value();
}
var completer = new Completer<String>();
_unitElementSignatureFiles
.putIfAbsent(path, () => <Completer<String>>[])
.add(completer);
_scheduler.notify(this);
return completer.future;
}
ApiSignature getUnitKeyByPath(String path) {
_throwIfNotAbsolutePath(path);
var file = fsState.getFileForPath(path);
ApiSignature signature = new ApiSignature();
signature.addUint32List(_linkedSalt);
signature.addString(file.transitiveSignature);
return signature;
}
/// Return `true` is the file with the given absolute [uri] is a library,
/// or `false` if it is a part. More specifically, return `true` if the file
/// is not known to be a part.
///
/// Correspondingly, return `true` if the [uri] does not correspond to a file,
/// for any reason, e.g. the file does not exist, or the [uri] cannot be
/// resolved to a file path, or the [uri] is invalid, e.g. a `package:` URI
/// without a package name. In these cases we cannot prove that the file is
/// not a part, so it must be a library.
bool isLibraryByUri(Uri uri) {
return !_fsState.getFileForUri(uri).isPart;
}
/// Return a [Future] that completes with a [ParsedUnitResult] for the file
/// with the given [path].
///
/// The [path] must be absolute and normalized.
///
/// The [path] can be any file - explicitly or implicitly analyzed, or neither.
///
/// The parsing is performed in the method itself, and the result is not
/// produced through the [results] stream (just because it is not a fully
/// resolved unit).
Future<ParsedUnitResult> parseFile(String path) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
return parseFileSync(path);
}
/// Return a [ParsedUnitResult] for the file with the given [path].
///
/// The [path] must be absolute and normalized.
///
/// The [path] can be any file - explicitly or implicitly analyzed, or neither.
///
/// The parsing is performed in the method itself, and the result is not
/// produced through the [results] stream (just because it is not a fully
/// resolved unit).
ParsedUnitResult parseFileSync(String path) {
_throwIfNotAbsolutePath(path);
FileState file = _fileTracker.verifyApiSignature(path);
RecordingErrorListener listener = new RecordingErrorListener();
CompilationUnit unit = file.parse(listener);
return new ParsedUnitResultImpl(currentSession, file.path, file.uri,
file.content, file.lineInfo, file.isPart, unit, listener.errors);
}
@override
Future<void> performWork() async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
if (_fileTracker.verifyChangedFilesIfNeeded()) {
return;
}
// Analyze a requested file.
if (_requestedFiles.isNotEmpty) {
String path = _requestedFiles.keys.first;
try {
AnalysisResult result = _computeAnalysisResult(path, withUnit: true);
// If a part without a library, delay its analysis.
if (result == null) {
_requestedParts
.putIfAbsent(path, () => [])
.addAll(_requestedFiles.remove(path));
return;
}
// Notify the completers.
_requestedFiles.remove(path).forEach((completer) {
completer.complete(result);
});
// Remove from to be analyzed and produce it now.
_fileTracker.fileWasAnalyzed(path);
_resultController.add(result);
} catch (exception, stackTrace) {
_fileTracker.fileWasAnalyzed(path);
_requestedFiles.remove(path).forEach((completer) {
completer.completeError(exception, stackTrace);
});
}
return;
}
// Analyze a requested library.
if (_requestedLibraries.isNotEmpty) {
String path = _requestedLibraries.keys.first;
try {
var result = _computeResolvedLibrary(path);
_requestedLibraries.remove(path).forEach((completer) {
completer.complete(result);
});
} catch (exception, stackTrace) {
_requestedLibraries.remove(path).forEach((completer) {
completer.completeError(exception, stackTrace);
});
}
return;
}
// Process an index request.
if (_indexRequestedFiles.isNotEmpty) {
String path = _indexRequestedFiles.keys.first;
AnalysisDriverUnitIndex index = _computeIndex(path);
_indexRequestedFiles.remove(path).forEach((completer) {
completer.complete(index);
});
return;
}
// Process a unit element key request.
if (_unitElementSignatureFiles.isNotEmpty) {
String path = _unitElementSignatureFiles.keys.first;
String signature = _computeUnitElementSignature(path);
var completers = _unitElementSignatureFiles.remove(path);
if (signature != null) {
completers.forEach((completer) {
completer.complete(signature);
});
} else {
_unitElementSignatureParts
.putIfAbsent(path, () => [])
.addAll(completers);
}
return;
}
// Process a unit element request.
if (_unitElementRequestedFiles.isNotEmpty) {
String path = _unitElementRequestedFiles.keys.first;
UnitElementResult result = _computeUnitElement(path);
var completers = _unitElementRequestedFiles.remove(path);
if (result != null) {
completers.forEach((completer) {
completer.complete(result);
});
} else {
_unitElementRequestedParts
.putIfAbsent(path, () => [])
.addAll(completers);
}
return;
}
// Discover available files.
if (_discoverAvailableFilesTask != null &&
!_discoverAvailableFilesTask.isCompleted) {
_discoverAvailableFilesTask.perform();
return;
}
// Compute files defining a name.
if (_definingClassMemberNameTasks.isNotEmpty) {
_FilesDefiningClassMemberNameTask task =
_definingClassMemberNameTasks.first;
bool isDone = task.perform();
if (isDone) {
_definingClassMemberNameTasks.remove(task);
}
return;
}
// Compute files referencing a name.
if (_referencingNameTasks.isNotEmpty) {
_FilesReferencingNameTask task = _referencingNameTasks.first;
bool isDone = task.perform();
if (isDone) {
_referencingNameTasks.remove(task);
}
return;
}
// Analyze a priority file.
if (_priorityFiles.isNotEmpty) {
for (String path in _priorityFiles) {
if (_fileTracker.isFilePending(path)) {
try {
AnalysisResult result =
_computeAnalysisResult(path, withUnit: true);
if (result == null) {
_partsToAnalyze.add(path);
} else {
_resultController.add(result);
}
} catch (exception, stackTrace) {
_reportException(path, exception, stackTrace);
} finally {
_fileTracker.fileWasAnalyzed(path);
}
return;
}
}
}
// Analyze a general file.
if (_fileTracker.hasPendingFiles) {
String path = _fileTracker.anyPendingFile;
try {
AnalysisResult result = _computeAnalysisResult(path,
withUnit: false, skipIfSameSignature: true);
if (result == null) {
_partsToAnalyze.add(path);
} else if (result == AnalysisResult._UNCHANGED) {
// We found that the set of errors is the same as we produced the
// last time, so we don't need to produce it again now.
} else {
_resultController.add(result);
_lastProducedSignatures[result.path] = result._signature;
}
} catch (exception, stackTrace) {
_reportException(path, exception, stackTrace);
} finally {
_fileTracker.fileWasAnalyzed(path);
}
return;
}
// Analyze a requested part file.
if (_requestedParts.isNotEmpty) {
String path = _requestedParts.keys.first;
try {
AnalysisResult result = _computeAnalysisResult(path,
withUnit: true, asIsIfPartWithoutLibrary: true);
// Notify the completers.
_requestedParts.remove(path).forEach((completer) {
completer.complete(result);
});
// Remove from to be analyzed and produce it now.
_partsToAnalyze.remove(path);
_resultController.add(result);
} catch (exception, stackTrace) {
_partsToAnalyze.remove(path);
_requestedParts.remove(path).forEach((completer) {
completer.completeError(exception, stackTrace);
});
}
return;
}
// Analyze a general part.
if (_partsToAnalyze.isNotEmpty) {
String path = _partsToAnalyze.first;
_partsToAnalyze.remove(path);
try {
AnalysisResult result = _computeAnalysisResult(path,
withUnit: _priorityFiles.contains(path),
asIsIfPartWithoutLibrary: true);
_resultController.add(result);
} catch (exception, stackTrace) {
_reportException(path, exception, stackTrace);
}
return;
}
// Process a unit element signature request for a part.
if (_unitElementSignatureParts.isNotEmpty) {
String path = _unitElementSignatureParts.keys.first;
String signature =
_computeUnitElementSignature(path, asIsIfPartWithoutLibrary: true);
_unitElementSignatureParts.remove(path).forEach((completer) {
completer.complete(signature);
});
return;
}
// Process a unit element request for a part.
if (_unitElementRequestedParts.isNotEmpty) {
String path = _unitElementRequestedParts.keys.first;
UnitElementResult result =
_computeUnitElement(path, asIsIfPartWithoutLibrary: true);
_unitElementRequestedParts.remove(path).forEach((completer) {
completer.complete(result);
});
return;
}
}
/// Remove the file with the given [path] from the list of files to analyze.
///
/// The [path] must be absolute and normalized.
///
/// The results of analysis of the file might still be produced by the
/// [results] stream. The driver will try to stop producing these results,
/// but does not guarantee this.
void removeFile(String path) {
_throwIfNotAbsolutePath(path);
_throwIfChangesAreNotAllowed();
_fileTracker.removeFile(path);
_libraryContext = null;
_priorityResults.clear();
}
/// Reset URI resolution, read again all files, build files graph, and ensure
/// that for all added files new results are reported.
void resetUriResolution() {
_fsState.resetUriResolution();
_fileTracker.scheduleAllAddedFiles();
_changeHook(null);
}
/// Implementation for [changeFile].
void _changeFile(String path) {
_fileTracker.changeFile(path);
_libraryContext = null;
_priorityResults.clear();
}
/// Handles a notification from the [FileTracker] that there has been a change
/// of state.
void _changeHook(String path) {
_createNewSession(path);
_libraryContext = null;
_priorityResults.clear();
_scheduler.notify(this);
}
/// Return the cached or newly computed analysis result of the file with the
/// given [path].
///
/// The result will have the fully resolved unit and will always be newly
/// compute only if [withUnit] is `true`.
///
/// Return `null` if the file is a part of an unknown library, so cannot be
/// analyzed yet. But [asIsIfPartWithoutLibrary] is `true`, then the file is
/// analyzed anyway, even without a library.
///
/// Return [AnalysisResult._UNCHANGED] if [skipIfSameSignature] is `true` and
/// the resolved signature of the file in its library is the same as the one
/// that was the most recently produced to the client.
AnalysisResult _computeAnalysisResult(String path,
{bool withUnit: false,
bool asIsIfPartWithoutLibrary: false,
bool skipIfSameSignature: false}) {
FileState file = _fsState.getFileForPath(path);
// Prepare the library - the file itself, or the known library.
FileState library = file.isPart ? file.library : file;
if (library == null) {
if (asIsIfPartWithoutLibrary) {
library = file;
} else {
return null;
}
}
// Prepare the signature and key.
String signature = _getResolvedUnitSignature(library, file);
String key = _getResolvedUnitKey(signature);
// Skip reading if the signature, so errors, are the same as the last time.
if (skipIfSameSignature) {
assert(!withUnit);
if (_lastProducedSignatures[path] == signature) {
return AnalysisResult._UNCHANGED;
}
}
// If we don't need the fully resolved unit, check for the cached result.
if (!withUnit) {
List<int> bytes = DriverPerformance.cache.makeCurrentWhile(() {
return _byteStore.get(key);
});
if (bytes != null) {
return _getAnalysisResultFromBytes(file, signature, bytes);
}
}
// We need the fully resolved unit, or the result is not cached.
return _logger.run('Compute analysis result for $path', () {
_logger.writeln('Work in $name');
try {
_testView.numOfAnalyzedLibraries++;
if (!_fsState.getFileForUri(Uri.parse('dart:core')).exists) {
return _newMissingDartLibraryResult(file, 'dart:core');
}
if (!_fsState.getFileForUri(Uri.parse('dart:async')).exists) {
return _newMissingDartLibraryResult(file, 'dart:async');
}
var libraryContext = _createLibraryContext(library);
LibraryAnalyzer analyzer = new LibraryAnalyzer(
analysisOptions,
declaredVariables,
sourceFactory,
libraryContext.isLibraryUri,
libraryContext.analysisContext,
libraryContext.elementFactory,
libraryContext.inheritanceManager,
library,
_resourceProvider,
testingData: testingData);
Map<FileState, UnitAnalysisResult> results = analyzer.analyze();
List<int> bytes;
CompilationUnit resolvedUnit;
for (FileState unitFile in results.keys) {
UnitAnalysisResult unitResult = results[unitFile];
List<int> unitBytes =
_serializeResolvedUnit(unitResult.unit, unitResult.errors);
String unitSignature = _getResolvedUnitSignature(library, unitFile);
String unitKey = _getResolvedUnitKey(unitSignature);
_byteStore.put(unitKey, unitBytes);
if (unitFile == file) {
bytes = unitBytes;
resolvedUnit = unitResult.unit;
}
if (disableChangesAndCacheAllResults) {
AnalysisResult result = _getAnalysisResultFromBytes(
unitFile, unitSignature, unitBytes,
content: unitFile.content, resolvedUnit: unitResult.unit);
_allCachedResults[unitFile.path] = result;
}
}
// Return the result, full or partial.
_logger.writeln('Computed new analysis result.');
AnalysisResult result = _getAnalysisResultFromBytes(
file, signature, bytes,
content: withUnit ? file.content : null,
resolvedUnit: withUnit ? resolvedUnit : null);
if (withUnit && _priorityFiles.contains(path)) {
_priorityResults[path] = result;
}
return result;
} catch (exception, stackTrace) {
String contextKey =
_storeExceptionContext(path, library, exception, stackTrace);
throw new _ExceptionState(exception, stackTrace, contextKey);
}
});
}
AnalysisDriverUnitIndex _computeIndex(String path) {
AnalysisResult analysisResult = _computeAnalysisResult(path,
withUnit: false, asIsIfPartWithoutLibrary: true);
return analysisResult._index;
}
/// Return the newly computed resolution result of the library with the
/// given [path].
ResolvedLibraryResultImpl _computeResolvedLibrary(String path) {
FileState library = _fsState.getFileForPath(path);
return _logger.run('Compute resolved library $path', () {
_testView.numOfAnalyzedLibraries++;
var libraryContext = _createLibraryContext(library);
LibraryAnalyzer analyzer = new LibraryAnalyzer(
analysisOptions,
declaredVariables,
sourceFactory,
libraryContext.isLibraryUri,
libraryContext.analysisContext,
libraryContext.elementFactory,
libraryContext.inheritanceManager,
library,
_resourceProvider,
testingData: testingData);
Map<FileState, UnitAnalysisResult> unitResults = analyzer.analyze();
var resolvedUnits = <ResolvedUnitResult>[];
for (var unitFile in unitResults.keys) {
if (unitFile.path != null) {
var unitResult = unitResults[unitFile];
resolvedUnits.add(
new AnalysisResult(
currentSession,
_sourceFactory,
unitFile.path,
unitFile.uri,
unitFile.exists,
unitFile.content,
unitFile.lineInfo,
unitFile.isPart,
null,
unitResult.unit,
unitResult.errors,
null,
),
);
}
}
return new ResolvedLibraryResultImpl(
currentSession,
library.path,
library.uri,
resolvedUnits.first.libraryElement,
libraryContext.typeProvider,
resolvedUnits,
);
});
}
UnitElementResult _computeUnitElement(String path,
{bool asIsIfPartWithoutLibrary: false}) {
FileState file = _fsState.getFileForPath(path);
// Prepare the library - the file itself, or the known library.
FileState library = file.isPart ? file.library : file;
if (library == null) {
if (asIsIfPartWithoutLibrary) {
library = file;
} else {
return null;
}
}
return _logger.run('Compute unit element for $path', () {
_logger.writeln('Work in $name');
var libraryContext = _createLibraryContext(library);
var element = libraryContext.computeUnitElement(library, file);
return new UnitElementResultImpl(
currentSession,
path,
file.uri,
library.transitiveSignature,
element,
);
});
}
String _computeUnitElementSignature(String path,
{bool asIsIfPartWithoutLibrary: false}) {
FileState file = _fsState.getFileForPath(path);
// Prepare the library - the file itself, or the known library.
FileState library = file.isPart ? file.library : file;
if (library == null) {
if (asIsIfPartWithoutLibrary) {
library = file;
} else {
return null;
}
}
return library.transitiveSignature;
}
/// Creates new [FileSystemState] and [FileTracker] objects.
///
/// This is used both on initial construction and whenever the configuration
/// changes.
void _createFileTracker() {
_fillSalt();
_fsState = new FileSystemState(
_logger,
_byteStore,
_contentOverlay,
_resourceProvider,
name,
sourceFactory,
analysisOptions,
_unlinkedSalt,
_linkedSalt,
externalSummaries: _externalSummaries,
);
_fileTracker = new FileTracker(_logger, _fsState, _changeHook);
}
/// Return the context in which the [library] should be analyzed.
LibraryContext _createLibraryContext(FileState library) {
if (_libraryContext != null) {
if (_libraryContext.pack()) {
_libraryContext = null;
}
}
if (_libraryContext == null) {
_libraryContext = new LibraryContext(
session: currentSession,
logger: _logger,
fsState: fsState,
byteStore: _byteStore,
analysisOptions: _analysisOptions,
declaredVariables: declaredVariables,
sourceFactory: _sourceFactory,
externalSummaries: _externalSummaries,
targetLibrary: library,
);
} else {
_libraryContext.load2(library);
}
return _libraryContext;
}
/// Create a new analysis session, so invalidating the current one.
void _createNewSession(String path) {
if (onCurrentSessionAboutToBeDiscarded != null) {
onCurrentSessionAboutToBeDiscarded(path);
}
_currentSession = new AnalysisSessionImpl(this);
}
/// If this has not been done yet, schedule discovery of all files that are
/// potentially available, so that they are included in [knownFiles].
void _discoverAvailableFiles() {
_discoverAvailableFilesTask ??= new _DiscoverAvailableFilesTask(this);
}
/// Fill [_unlinkedSalt] and [_linkedSalt] with data.
void _fillSalt() {
_unlinkedSalt[0] = DATA_VERSION;
_unlinkedSalt[1] = enableIndex ? 1 : 0;
_unlinkedSalt.setAll(2, _analysisOptions.unlinkedSignature);
_linkedSalt[0] = DATA_VERSION;
_linkedSalt[1] = enableIndex ? 1 : 0;
_linkedSalt.setAll(2, _analysisOptions.signature);
}
/// Load the [AnalysisResult] for the given [file] from the [bytes]. Set
/// optional [content] and [resolvedUnit].
AnalysisResult _getAnalysisResultFromBytes(
FileState file, String signature, List<int> bytes,
{String content, CompilationUnit resolvedUnit}) {
var unit = new AnalysisDriverResolvedUnit.fromBuffer(bytes);
List<AnalysisError> errors = _getErrorsFromSerialized(file, unit.errors);
_updateHasErrorOrWarningFlag(file, errors);
return new AnalysisResult(
currentSession,
_sourceFactory,
file.path,
file.uri,
file.exists,
content,
file.lineInfo,
file.isPart,
signature,
resolvedUnit,
errors,
unit.index);
}
/// Return [AnalysisError]s for the given [serialized] errors.
List<AnalysisError> _getErrorsFromSerialized(
FileState file, List<AnalysisDriverUnitError> serialized) {
List<AnalysisError> errors = <AnalysisError>[];
for (AnalysisDriverUnitError error in serialized) {
String errorName = error.uniqueName;
ErrorCode errorCode =
errorCodeByUniqueName(errorName) ?? _lintCodeByUniqueName(errorName);
if (errorCode == null) {
// This could fail because the error code is no longer defined, or, in
// the case of a lint rule, if the lint rule has been disabled since the
// errors were written.
AnalysisEngine.instance.instrumentationService
.logError('No error code for "$error" in "$file"');
} else {
List<DiagnosticMessageImpl> contextMessages;
if (error.contextMessages.isNotEmpty) {
contextMessages = <DiagnosticMessageImpl>[];
for (var message in error.contextMessages) {
contextMessages.add(DiagnosticMessageImpl(
filePath: message.filePath,
length: message.length,
message: message.message,
offset: message.offset));
}
}
errors.add(new AnalysisError.forValues(
file.source,
error.offset,
error.length,
errorCode,
error.message,
error.correction.isEmpty ? null : error.correction,
contextMessages: contextMessages ?? const []));
}
}
return errors;
}
/// Return the key to store fully resolved results for the [signature].
String _getResolvedUnitKey(String signature) {
return '$signature.resolved';
}
/// Return the signature that identifies fully resolved results for the [file]
/// in the [library], e.g. element model, errors, index, etc.
String _getResolvedUnitSignature(FileState library, FileState file) {
ApiSignature signature = new ApiSignature();
signature.addUint32List(_linkedSalt);
signature.addString(library.transitiveSignature);
signature.addString(file.contentHash);
return signature.toHex();
}
/// Return the lint code with the given [errorName], or `null` if there is no
/// lint registered with that name.
ErrorCode _lintCodeByUniqueName(String errorName) {
const String lintPrefix = 'LintCode.';
if (errorName.startsWith(lintPrefix)) {
String lintName = errorName.substring(lintPrefix.length);
return linter.Registry.ruleRegistry.getRule(lintName)?.lintCode;
}
const String lintPrefixOld = '_LintCode.';
if (errorName.startsWith(lintPrefixOld)) {
String lintName = errorName.substring(lintPrefixOld.length);
return linter.Registry.ruleRegistry.getRule(lintName)?.lintCode;
}
return null;
}
/// We detected that one of the required `dart` libraries is missing.
/// Return the empty analysis result with the error.
AnalysisResult _newMissingDartLibraryResult(
FileState file, String missingUri) {
// TODO(scheglov) Find a better way to report this.
return new AnalysisResult(
currentSession,
_sourceFactory,
file.path,
file.uri,
file.exists,
null,
file.lineInfo,
file.isPart,
null,
null,
[
new AnalysisError(file.source, 0, 0,
CompileTimeErrorCode.MISSING_DART_LIBRARY, [missingUri])
],
null);
}
void _reportException(String path, exception, StackTrace stackTrace) {
String contextKey;
if (exception is _ExceptionState) {
var state = exception as _ExceptionState;
exception = state.exception;
stackTrace = state.stackTrace;
contextKey = state.contextKey;
}
CaughtException caught = new CaughtException(exception, stackTrace);
_exceptionController.add(new ExceptionResult(path, caught, contextKey));
}
/// Serialize the given [resolvedUnit] errors and index into bytes.
List<int> _serializeResolvedUnit(
CompilationUnit resolvedUnit, List<AnalysisError> errors) {
AnalysisDriverUnitIndexBuilder index = enableIndex
? indexUnit(resolvedUnit)
: new AnalysisDriverUnitIndexBuilder();
return new AnalysisDriverResolvedUnitBuilder(
errors: errors.map((error) {
List<DiagnosticMessageBuilder> contextMessages;
if (error.contextMessages != null) {
contextMessages = <DiagnosticMessageBuilder>[];
for (var message in error.contextMessages) {
contextMessages.add(DiagnosticMessageBuilder(
filePath: message.filePath,
length: message.length,
message: message.message,
offset: message.offset));
}
}
return new AnalysisDriverUnitErrorBuilder(
offset: error.offset,
length: error.length,
uniqueName: error.errorCode.uniqueName,
message: error.message,
correction: error.correction,
contextMessages: contextMessages);
}).toList(),
index: index)
.toBuffer();
}
String _storeExceptionContext(
String path, FileState libraryFile, exception, StackTrace stackTrace) {
if (allowedNumberOfContextsToWrite <= 0) {
return null;
} else {
allowedNumberOfContextsToWrite--;
}
try {
List<AnalysisDriverExceptionFileBuilder> contextFiles = libraryFile
.transitiveFiles
.map((file) => new AnalysisDriverExceptionFileBuilder(
path: file.path, content: file.content))
.toList();
contextFiles.sort((a, b) => a.path.compareTo(b.path));
AnalysisDriverExceptionContextBuilder contextBuilder =
new AnalysisDriverExceptionContextBuilder(
path: path,
exception: exception.toString(),
stackTrace: stackTrace.toString(),
files: contextFiles);
List<int> bytes = contextBuilder.toBuffer();
String _twoDigits(int n) {
if (n >= 10) return '$n';
return '0$n';
}
String _threeDigits(int n) {
if (n >= 100) return '$n';
if (n >= 10) return '0$n';
return '00$n';
}
DateTime time = new DateTime.now();
String m = _twoDigits(time.month);
String d = _twoDigits(time.day);
String h = _twoDigits(time.hour);
String min = _twoDigits(time.minute);
String sec = _twoDigits(time.second);
String ms = _threeDigits(time.millisecond);
String key = 'exception_${time.year}$m$d' '_$h$min$sec' + '_$ms';
_byteStore.put(key, bytes);
return key;
} catch (_) {
return null;
}
}
/// If the driver is used in the read-only mode with infinite cache,
/// we should not allow invocations that change files.
void _throwIfChangesAreNotAllowed() {
if (disableChangesAndCacheAllResults) {
throw new StateError('Changing files is not allowed for this driver.');
}
}
/// The driver supports only absolute paths, this method is used to validate
/// any input paths to prevent errors later.
void _throwIfNotAbsolutePath(String path) {
if (!_resourceProvider.pathContext.isAbsolute(path)) {
throw new ArgumentError('Only absolute paths are supported: $path');
}
}
/// Given the list of [errors] for the [file], update the [file]'s
/// [FileState.hasErrorOrWarning] flag.
void _updateHasErrorOrWarningFlag(
FileState file, List<AnalysisError> errors) {
for (AnalysisError error in errors) {
ErrorSeverity severity = error.errorCode.errorSeverity;
if (severity == ErrorSeverity.ERROR ||
severity == ErrorSeverity.WARNING) {
file.hasErrorOrWarning = true;
return;
}
}
file.hasErrorOrWarning = false;
}
}
/// A generic schedulable interface via the AnalysisDriverScheduler. Currently
/// only implemented by [AnalysisDriver] and the angular plugin, at least as
/// a temporary measure until the official plugin API is ready (and a different
/// scheduler is used)
abstract class AnalysisDriverGeneric {
/// Return `true` if the driver has a file to analyze.
bool get hasFilesToAnalyze;
/// Set the list of files that the driver should try to analyze sooner.
///
/// Every path in the list must be absolute and normalized.
///
/// The driver will produce the results through the [results] stream. The
/// exact order in which results are produced is not defined, neither
/// between priority files, nor between priority and non-priority files.
void set priorityFiles(List<String> priorityPaths);
/// Return the priority of work that the driver needs to perform.
AnalysisDriverPriority get workPriority;
/// Add the file with the given [path] to the set of files that are explicitly
/// being analyzed.
///
/// The [path] must be absolute and normalized.
///
/// The results of analysis are eventually produced by the [results] stream.
void addFile(String path);
/// Notify the driver that the client is going to stop using it.
void dispose();
/// Perform a single chunk of work and produce [results].
Future<void> performWork();
}
/// Priorities of [AnalysisDriver] work. The farther a priority to the beginning
/// of the list, the earlier the corresponding [AnalysisDriver] should be asked
/// to perform work.
enum AnalysisDriverPriority {
nothing,
general,
generalWithErrors,
generalImportChanged,
generalChanged,
changedFiles,
priority,
interactive
}
/// Instances of this class schedule work in multiple [AnalysisDriver]s so that
/// work with the highest priority is performed first.
class AnalysisDriverScheduler {
/// Time interval in milliseconds before pumping the event queue.
///
/// Relinquishing execution flow and running the event loop after every task
/// has too much overhead. Instead we use a fixed length of time, so we can
/// spend less time overall and still respond quickly enough.
static const int _MS_BEFORE_PUMPING_EVENT_QUEUE = 2;
/// Event queue pumping is required to allow IO and other asynchronous data
/// processing while analysis is active. For example Analysis Server needs to
/// be able to process `updateContent` or `setPriorityFiles` requests while
/// background analysis is in progress.
///
/// The number of pumpings is arbitrary, might be changed if we see that
/// analysis or other data processing tasks are starving. Ideally we would
/// need to run all asynchronous operations using a single global scheduler.
static const int _NUMBER_OF_EVENT_QUEUE_PUMPINGS = 128;
final PerformanceLog _logger;
/// The object used to watch as analysis drivers are created and deleted.
final DriverWatcher driverWatcher;
final List<AnalysisDriverGeneric> _drivers = [];
final Monitor _hasWork = new Monitor();
final StatusSupport _statusSupport = new StatusSupport();
bool _started = false;
/// The optional worker that is invoked when its work priority is higher
/// than work priorities in drivers.
///
/// Don't use outside of Analyzer and Analysis Server.
SchedulerWorker outOfBandWorker;
AnalysisDriverScheduler(this._logger, {this.driverWatcher});
/// Return `true` if we are currently analyzing code.
bool get isAnalyzing => _hasFilesToAnalyze;
/// Return the stream that produces [AnalysisStatus] events.
Stream<AnalysisStatus> get status => _statusSupport.stream;
/// Return `true` if there is a driver with a file to analyze.
bool get _hasFilesToAnalyze {
for (AnalysisDriverGeneric driver in _drivers) {
if (driver.hasFilesToAnalyze) {
return true;
}
}
return false;
}
/// Add the given [driver] and schedule it to perform its work.
void add(AnalysisDriverGeneric driver) {
_drivers.add(driver);
_hasWork.notify();
if (driver is AnalysisDriver) {
driverWatcher?.addedDriver(driver, driver.contextRoot);
}
}
/// Notify that there is a change to the [driver], it it might need to
/// perform some work.
void notify(AnalysisDriverGeneric driver) {
_hasWork.notify();
_statusSupport.preTransitionToAnalyzing();
}
/// Remove the given [driver] from the scheduler, so that it will not be
/// asked to perform any new work.
void remove(AnalysisDriverGeneric driver) {
if (driver is AnalysisDriver) {
driverWatcher?.removedDriver(driver);
}
_drivers.remove(driver);
_hasWork.notify();
}
/// Start the scheduler, so that any [AnalysisDriver] created before or
/// after will be asked to perform work.
void start() {
if (_started) {
throw new StateError('The scheduler has already been started.');
}
_started = true;
_run();
}
/// Return a future that will be completed the next time the status is idle.
///
/// If the status is currently idle, the returned future will be signaled
/// immediately.
Future<void> waitForIdle() => _statusSupport.waitForIdle();
/// Run infinitely analysis cycle, selecting the drivers with the highest
/// priority first.
Future<void> _run() async {
// Give other microtasks the time to run before doing the analysis cycle.
await null;
Stopwatch timer = new Stopwatch()..start();
PerformanceLogSection analysisSection;
while (true) {
// Pump the event queue.
if (timer.elapsedMilliseconds > _MS_BEFORE_PUMPING_EVENT_QUEUE) {
await _pumpEventQueue(_NUMBER_OF_EVENT_QUEUE_PUMPINGS);
timer.reset();
}
await _hasWork.signal;
// Transition to analyzing if there are files to analyze.
if (_hasFilesToAnalyze) {
_statusSupport.transitionToAnalyzing();
analysisSection ??= _logger.enter('Analyzing');
}
// Find the driver with the highest priority.
AnalysisDriverGeneric bestDriver;
AnalysisDriverPriority bestPriority = AnalysisDriverPriority.nothing;
for (AnalysisDriverGeneric driver in _drivers) {
AnalysisDriverPriority priority = driver.workPriority;
if (priority.index > bestPriority.index) {
bestDriver = driver;
bestPriority = priority;
}
}
if (outOfBandWorker != null) {
var workerPriority = outOfBandWorker.workPriority;
if (workerPriority != AnalysisDriverPriority.nothing) {
if (workerPriority.index > bestPriority.index) {
await outOfBandWorker.performWork();
_hasWork.notify();
continue;
}
}
}
// Transition to idle if no files to analyze.
if (!_hasFilesToAnalyze) {
_statusSupport.transitionToIdle();
analysisSection?.exit();
analysisSection = null;
}
// Continue to sleep if no work to do.
if (bestPriority == AnalysisDriverPriority.nothing) {
continue;
}
// Ask the driver to perform a chunk of work.
await bestDriver.performWork();
// Schedule one more cycle.
_hasWork.notify();
}
}
/// Returns a [Future] that completes after performing [times] pumpings of
/// the event queue.
static Future _pumpEventQueue(int times) {
if (times == 0) {
return new Future.value();
}
return new Future.delayed(Duration.zero, () => _pumpEventQueue(times - 1));
}
}
@visibleForTesting
class AnalysisDriverTestView {
final AnalysisDriver driver;
int numOfAnalyzedLibraries = 0;
AnalysisDriverTestView(this.driver);
FileTracker get fileTracker => driver._fileTracker;
Map<String, ResolvedUnitResult> get priorityResults {
return driver._priorityResults;
}
SummaryDataStore getSummaryStore(String libraryPath) {
FileState library = driver.fsState.getFileForPath(libraryPath);
LibraryContext libraryContext = driver._createLibraryContext(library);
return libraryContext.store;
}
}
/// The result of analyzing of a single file.
///
/// These results are self-consistent, i.e. [content], [lineInfo], the
/// resolved [unit] correspond to each other. All referenced elements, even
/// external ones, are also self-consistent. But none of the results is
/// guaranteed to be consistent with the state of the files.
///
/// Every result is independent, and is not guaranteed to be consistent with
/// any previously returned result, even inside of the same library.
class AnalysisResult extends ResolvedUnitResultImpl {
static final _UNCHANGED = new AnalysisResult(
null, null, null, null, null, null, null, null, null, null, null, null);
/// The [SourceFactory] with which the file was analyzed.
final SourceFactory sourceFactory;
/// The signature of the result based on the content of the file, and the
/// transitive closure of files imported and exported by the library of
/// the requested file.
final String _signature;
/// The index of the unit.
final AnalysisDriverUnitIndex _index;
AnalysisResult(
AnalysisSession session,
this.sourceFactory,
String path,
Uri uri,
bool exists,
String content,
LineInfo lineInfo,
bool isPart,
this._signature,
CompilationUnit unit,
List<AnalysisError> errors,
this._index)
: super(session, path, uri, exists, content, lineInfo, isPart, unit,
errors);
@override
LibraryElement get libraryElement => unit.declaredElement.library;
@override
TypeProvider get typeProvider => unit.declaredElement.context.typeProvider;
@override
TypeSystem get typeSystem => unit.declaredElement.context.typeSystem;
}
class DriverPerformance {
static final PerformanceTag driver =
PerformanceStatistics.analyzer.createChild('driver');
static final PerformanceTag cache = driver.createChild('cache');
}
/// An object that watches for the creation and removal of analysis drivers.
///
/// Clients may not extend, implement or mix-in this class.
abstract class DriverWatcher {
/// The context manager has just added the given analysis [driver]. This method
/// must be called before the driver has been allowed to perform any analysis.
void addedDriver(AnalysisDriver driver, ContextRoot contextRoot);
/// The context manager has just removed the given analysis [driver].
void removedDriver(AnalysisDriver driver);
}
/// Exception that happened during analysis.
class ExceptionResult {
/// The path of the file being analyzed when the [exception] happened.
///
/// Absolute and normalized.
final String path;
/// The exception during analysis of the file with the [path].
final CaughtException exception;
/// If the exception happened during a file analysis, and the context in which
/// the exception happened was stored, this field is the key of the context
/// in the byte store. May be `null` if the context is unknown, the maximum
/// number of context to store was reached, etc.
final String contextKey;
ExceptionResult(this.path, this.exception, this.contextKey);
}
/// Worker in [AnalysisDriverScheduler].
abstract class SchedulerWorker {
/// Return the priority of work that this worker needs to perform.
AnalysisDriverPriority get workPriority;
/// Perform a single chunk of work.
Future<void> performWork();
}
/// Task that discovers all files that are available to the driver, and makes
/// them known.
class _DiscoverAvailableFilesTask {
static const int _MS_WORK_INTERVAL = 5;
final AnalysisDriver driver;
bool isCompleted = false;
Completer<void> completer = new Completer<void>();
Iterator<Folder> folderIterator;
List<String> files = [];
int fileIndex = 0;
_DiscoverAvailableFilesTask(this.driver);
/// Perform the next piece of work, and set [isCompleted] to `true` to
/// indicate that the task is done, or keeps it `false` to indicate that the
/// task should continue to be run.
void perform() {
if (folderIterator == null) {
files.addAll(driver.addedFiles);
// Discover SDK libraries.
var dartSdk = driver._sourceFactory.dartSdk;
if (dartSdk != null) {
for (var sdkLibrary in dartSdk.sdkLibraries) {
var file = dartSdk.mapDartUri(sdkLibrary.shortName).fullName;
files.add(file);
}
}
// Discover files in package/lib folders.
var packageMap = driver._sourceFactory.packageMap;
if (packageMap != null) {
folderIterator = packageMap.values.expand((f) => f).iterator;
} else {
folderIterator = <Folder>[].iterator;
}
}
// List each package/lib folder recursively.
Stopwatch timer = new Stopwatch()..start();
while (folderIterator.moveNext()) {
var folder = folderIterator.current;
_appendFilesRecursively(folder);
// Note: must check if we are exiting before calling moveNext()
// otherwise we will skip one iteration of the loop when we come back.
if (timer.elapsedMilliseconds > _MS_WORK_INTERVAL) {
return;
}
}
// Get know files one by one.
while (fileIndex < files.length) {
if (timer.elapsedMilliseconds > _MS_WORK_INTERVAL) {
return;
}
var file = files[fileIndex++];
driver._fsState.getFileForPath(file);
}
// The task is done, clean up.
folderIterator = null;
files = null;
// Complete and clean up.
isCompleted = true;
completer.complete();
completer = null;
}
void _appendFilesRecursively(Folder folder) {
try {
for (var child in folder.getChildren()) {
if (child is File) {
var path = child.path;
if (AnalysisEngine.isDartFileName(path)) {
files.add(path);
}
} else if (child is Folder) {
_appendFilesRecursively(child);
}
}
} catch (_) {}
}
}
/// Information about an exception and its context.
class _ExceptionState {
final exception;
final StackTrace stackTrace;
/// The key under which the context of the exception was stored, or `null`
/// if unknown, the maximum number of context to store was reached, etc.
final String contextKey;
_ExceptionState(this.exception, this.stackTrace, this.contextKey);
@override
String toString() => '$exception\n$stackTrace';
}
/// Task that computes the list of files that were added to the driver and
/// declare a class member with the given [name].
class _FilesDefiningClassMemberNameTask {
static const int _MS_WORK_INTERVAL = 5;
final AnalysisDriver driver;
final String name;
final Completer<List<String>> completer = new Completer<List<String>>();
final List<String> definingFiles = <String>[];
final Set<String> checkedFiles = new Set<String>();
final List<String> filesToCheck = <String>[];
_FilesDefiningClassMemberNameTask(this.driver, this.name);
/// Perform work for a fixed length of time, and complete the [completer] to
/// either return `true` to indicate that the task is done, or return `false`
/// to indicate that the task should continue to be run.
///
/// Each invocation of an asynchronous method has overhead, which looks as
/// `_SyncCompleter.complete` invocation, we see as much as 62% in some
/// scenarios. Instead we use a fixed length of time, so we can spend less time
/// overall and keep quick enough response time.
bool perform() {
Stopwatch timer = new Stopwatch()..start();
while (timer.elapsedMilliseconds < _MS_WORK_INTERVAL) {
// Prepare files to check.
if (filesToCheck.isEmpty) {
Set<String> newFiles = driver.addedFiles.difference(checkedFiles);
filesToCheck.addAll(newFiles);
}
// If no more files to check, complete and done.
if (filesToCheck.isEmpty) {
completer.complete(definingFiles);
return true;
}
// Check the next file.
String path = filesToCheck.removeLast();
FileState file = driver._fsState.getFileForPath(path);
if (file.definedClassMemberNames.contains(name)) {
definingFiles.add(path);
}
checkedFiles.add(path);
}
// We're not done yet.
return false;
}
}
/// Task that computes the list of files that were added to the driver and
/// have at least one reference to an identifier [name] defined outside of the
/// file.
class _FilesReferencingNameTask {
static const int _WORK_FILES = 100;
static const int _MS_WORK_INTERVAL = 5;
final AnalysisDriver driver;
final String name;
final Completer<List<String>> completer = new Completer<List<String>>();
int fileStamp = -1;
List<FileState> filesToCheck;
int filesToCheckIndex;
final List<String> referencingFiles = <String>[];
_FilesReferencingNameTask(this.driver, this.name);
/// Perform work for a fixed length of time, and complete the [completer] to
/// either return `true` to indicate that the task is done, or return `false`
/// to indicate that the task should continue to be run.
///
/// Each invocation of an asynchronous method has overhead, which looks as
/// `_SyncCompleter.complete` invocation, we see as much as 62% in some
/// scenarios. Instead we use a fixed length of time, so we can spend less time
/// overall and keep quick enough response time.
bool perform() {
if (driver._fsState.fileStamp != fileStamp) {
filesToCheck = null;
referencingFiles.clear();
}
// Prepare files to check.
if (filesToCheck == null) {
fileStamp = driver._fsState.fileStamp;
filesToCheck = driver._fsState.knownFiles;
filesToCheckIndex = 0;
}
Stopwatch timer = new Stopwatch()..start();
while (filesToCheckIndex < filesToCheck.length) {
if (filesToCheckIndex % _WORK_FILES == 0 &&
timer.elapsedMilliseconds > _MS_WORK_INTERVAL) {
return false;
}
FileState file = filesToCheck[filesToCheckIndex++];
if (file.referencedNames.contains(name)) {
referencingFiles.add(file.path);
}
}
// If no more files to check, complete and done.
completer.complete(referencingFiles);
return true;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/testing_data.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:analyzer/src/dart/resolver/flow_analysis_visitor.dart';
/// Data structure maintaining intermediate analysis results for testing
/// purposes. Under normal execution, no instance of this class should be
/// created.
class TestingData {
/// Map containing the results of flow analysis.
final Map<Uri, FlowAnalysisResult> uriToFlowAnalysisResult = {};
/// Called by the analysis driver after performing flow analysis, to record
/// flow analysis results.
void recordFlowAnalysisResult(Uri uri, FlowAnalysisResult result) {
uriToFlowAnalysisResult[uri] = result;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/context_root.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/dart/analysis/context_root.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:path/path.dart';
/**
* An implementation of a context root.
*/
class ContextRootImpl implements ContextRoot {
@override
final ResourceProvider resourceProvider;
@override
final Folder root;
@override
final List<Resource> included = <Resource>[];
@override
final List<Resource> excluded = <Resource>[];
@override
File optionsFile;
@override
File packagesFile;
/**
* Initialize a newly created context root.
*/
ContextRootImpl(this.resourceProvider, this.root);
@override
Iterable<String> get excludedPaths =>
excluded.map((Resource folder) => folder.path);
@override
int get hashCode => root.path.hashCode;
@override
Iterable<String> get includedPaths =>
included.map((Resource folder) => folder.path);
@override
bool operator ==(Object other) {
return other is ContextRoot && root.path == other.root.path;
}
@override
Iterable<String> analyzedFiles() sync* {
for (String path in includedPaths) {
if (!_isExcluded(path)) {
Resource resource = resourceProvider.getResource(path);
if (resource is File) {
yield path;
} else if (resource is Folder) {
yield* _includedFilesInFolder(resource);
} else {
Type type = resource.runtimeType;
throw new StateError('Unknown resource at path "$path" ($type)');
}
}
}
}
@override
bool isAnalyzed(String path) {
return _isIncluded(path) && !_isExcluded(path);
}
/**
* Return the absolute paths of all of the files that are included in the
* given [folder].
*/
Iterable<String> _includedFilesInFolder(Folder folder) sync* {
for (Resource resource in folder.getChildren()) {
String path = resource.path;
if (!_isExcluded(path)) {
if (resource is File) {
yield path;
} else if (resource is Folder) {
yield* _includedFilesInFolder(resource);
} else {
Type type = resource.runtimeType;
throw new StateError('Unknown resource at path "$path" ($type)');
}
}
}
}
/**
* Return `true` if the given [path] is either the same as or inside of one of
* the [excludedPaths].
*/
bool _isExcluded(String path) {
Context context = resourceProvider.pathContext;
String name = context.basename(path);
if (name.startsWith('.')) {
return true;
}
for (String excludedPath in excludedPaths) {
if (context.isAbsolute(excludedPath)) {
if (path == excludedPath || context.isWithin(excludedPath, path)) {
return true;
}
} else {
// The documentation claims that [excludedPaths] only contains absolute
// paths, so we shouldn't be able to reach this point.
for (String includedPath in includedPaths) {
if (context.isWithin(
context.join(includedPath, excludedPath), path)) {
return true;
}
}
}
}
return false;
}
/**
* Return `true` if the given [path] is either the same as or inside of one of
* the [includedPaths].
*/
bool _isIncluded(String path) {
Context context = resourceProvider.pathContext;
for (String includedPath in includedPaths) {
if (path == includedPath || context.isWithin(includedPath, path)) {
return true;
}
}
return false;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/context_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 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/context_builder.dart';
import 'package:analyzer/dart/analysis/context_root.dart';
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/context/builder.dart' as old
show ContextBuilder, ContextBuilderOptions;
import 'package:analyzer/src/context/context_root.dart' as old;
import 'package:analyzer/src/dart/analysis/byte_store.dart'
show ByteStore, MemoryByteStore;
import 'package:analyzer/src/dart/analysis/driver.dart'
show AnalysisDriver, AnalysisDriverScheduler;
import 'package:analyzer/src/dart/analysis/driver_based_analysis_context.dart';
import 'package:analyzer/src/dart/analysis/file_state.dart'
show FileContentOverlay;
import 'package:analyzer/src/dart/analysis/performance_logger.dart'
show PerformanceLog;
import 'package:analyzer/src/dart/sdk/sdk.dart';
import 'package:analyzer/src/generated/sdk.dart' show DartSdkManager;
import 'package:analyzer/src/generated/source.dart' show ContentCache;
import 'package:meta/meta.dart';
/**
* An implementation of a context builder.
*/
class ContextBuilderImpl implements ContextBuilder {
/**
* The resource provider used to access the file system.
*/
final ResourceProvider resourceProvider;
/**
* Initialize a newly created context builder. If a [resourceProvider] is
* given, then it will be used to access the file system, otherwise the
* default resource provider will be used.
*/
ContextBuilderImpl({ResourceProvider resourceProvider})
: resourceProvider =
resourceProvider ?? PhysicalResourceProvider.INSTANCE;
/**
* Return the path to the default location of the SDK, or `null` if the sdk
* cannot be found.
*/
String get _defaultSdkPath =>
FolderBasedDartSdk.defaultSdkDirectory(resourceProvider)?.path;
@override
AnalysisContext createContext(
{@deprecated ByteStore byteStore,
@required ContextRoot contextRoot,
DeclaredVariables declaredVariables,
bool enableIndex: false,
@deprecated FileContentOverlay fileContentOverlay,
List<String> librarySummaryPaths,
@deprecated PerformanceLog performanceLog,
@deprecated AnalysisDriverScheduler scheduler,
String sdkPath,
String sdkSummaryPath}) {
byteStore ??= new MemoryByteStore();
fileContentOverlay ??= new FileContentOverlay();
performanceLog ??= new PerformanceLog(new StringBuffer());
sdkPath ??= _defaultSdkPath;
if (sdkPath == null) {
throw new ArgumentError('Cannot find path to the SDK');
}
DartSdkManager sdkManager = new DartSdkManager(sdkPath, true);
if (scheduler == null) {
scheduler = new AnalysisDriverScheduler(performanceLog);
scheduler.start();
}
// TODO(brianwilkerson) Move the required implementation from the old
// ContextBuilder to this class and remove the old class.
old.ContextBuilderOptions options = new old.ContextBuilderOptions();
if (declaredVariables != null) {
options.declaredVariables = _toMap(declaredVariables);
}
if (sdkSummaryPath != null) {
options.dartSdkSummaryPath = sdkSummaryPath;
}
if (librarySummaryPaths != null) {
options.librarySummaryPaths = librarySummaryPaths;
}
options.defaultPackageFilePath = contextRoot.packagesFile?.path;
old.ContextBuilder builder = new old.ContextBuilder(
resourceProvider, sdkManager, new ContentCache(),
options: options);
builder.analysisDriverScheduler = scheduler;
builder.byteStore = byteStore;
builder.fileContentOverlay = fileContentOverlay;
builder.enableIndex = enableIndex;
builder.performanceLog = performanceLog;
old.ContextRoot oldContextRoot = new old.ContextRoot(
contextRoot.root.path, contextRoot.excludedPaths.toList(),
pathContext: resourceProvider.pathContext);
AnalysisDriver driver = builder.buildDriver(oldContextRoot);
// AnalysisDriver reports results into streams.
// We need to drain these streams to avoid memory leak.
driver.results.drain();
driver.exceptions.drain();
DriverBasedAnalysisContext context =
new DriverBasedAnalysisContext(resourceProvider, contextRoot, driver);
return context;
}
/**
* Convert the [declaredVariables] into a map for use with the old context
* builder.
*/
Map<String, String> _toMap(DeclaredVariables declaredVariables) {
Map<String, String> map = <String, String>{};
for (String name in declaredVariables.variableNames) {
map[name] = declaredVariables.get(name);
}
return map;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/experiments.g.dart | //
// THIS FILE IS GENERATED. DO NOT EDIT.
//
// Instead modify 'tools/experimental_features.yaml' and run
// 'dart pkg/analyzer/tool/experiments/generate.dart' to update.
part of 'experiments.dart';
/// A map containing information about all known experimental flags.
const _knownFeatures = <String, ExperimentalFeature>{
EnableString.constant_update_2018: ExperimentalFeatures.constant_update_2018,
EnableString.control_flow_collections:
ExperimentalFeatures.control_flow_collections,
EnableString.extension_methods: ExperimentalFeatures.extension_methods,
EnableString.non_nullable: ExperimentalFeatures.non_nullable,
EnableString.set_literals: ExperimentalFeatures.set_literals,
EnableString.spread_collections: ExperimentalFeatures.spread_collections,
EnableString.triple_shift: ExperimentalFeatures.triple_shift,
EnableString.variance: ExperimentalFeatures.variance,
// ignore: deprecated_member_use_from_same_package
EnableString.bogus_disabled: ExperimentalFeatures.bogus_disabled,
// ignore: deprecated_member_use_from_same_package
EnableString.bogus_enabled: ExperimentalFeatures.bogus_enabled,
};
List<bool> _buildExperimentalFlagsArray() => <bool>[
true, // constant-update-2018
true, // control-flow-collections
true, // extension-methods
IsEnabledByDefault.non_nullable,
true, // set-literals
true, // spread-collections
IsEnabledByDefault.triple_shift,
IsEnabledByDefault.variance,
false, // bogus-disabled
true, // bogus-enabled
];
/// Constant strings for enabling each of the currently known experimental
/// flags.
class EnableString {
/// String to enable the experiment "constant-update-2018"
static const String constant_update_2018 = 'constant-update-2018';
/// String to enable the experiment "control-flow-collections"
static const String control_flow_collections = 'control-flow-collections';
/// String to enable the experiment "extension-methods"
static const String extension_methods = 'extension-methods';
/// String to enable the experiment "non-nullable"
static const String non_nullable = 'non-nullable';
/// String to enable the experiment "set-literals"
static const String set_literals = 'set-literals';
/// String to enable the experiment "spread-collections"
static const String spread_collections = 'spread-collections';
/// String to enable the experiment "triple-shift"
static const String triple_shift = 'triple-shift';
/// String to enable the experiment "variance"
static const String variance = 'variance';
/// String to enable the experiment "bogus-disabled"
@deprecated
static const String bogus_disabled = 'bogus-disabled';
/// String to enable the experiment "bogus-enabled"
@deprecated
static const String bogus_enabled = 'bogus-enabled';
}
class ExperimentalFeatures {
static const constant_update_2018 = const ExperimentalFeature(
0,
EnableString.constant_update_2018,
IsEnabledByDefault.constant_update_2018,
IsExpired.constant_update_2018,
'Enhanced constant expressions',
firstSupportedVersion: '2.4.1');
static const control_flow_collections = const ExperimentalFeature(
1,
EnableString.control_flow_collections,
IsEnabledByDefault.control_flow_collections,
IsExpired.control_flow_collections,
'Control Flow Collections',
firstSupportedVersion: '2.2.2');
static const extension_methods = const ExperimentalFeature(
2,
EnableString.extension_methods,
IsEnabledByDefault.extension_methods,
IsExpired.extension_methods,
'Extension Methods',
firstSupportedVersion: '2.6.0');
static const non_nullable = const ExperimentalFeature(
3,
EnableString.non_nullable,
IsEnabledByDefault.non_nullable,
IsExpired.non_nullable,
'Non Nullable by default');
static const set_literals = const ExperimentalFeature(
4,
EnableString.set_literals,
IsEnabledByDefault.set_literals,
IsExpired.set_literals,
'Set Literals',
firstSupportedVersion: '2.2.0');
static const spread_collections = const ExperimentalFeature(
5,
EnableString.spread_collections,
IsEnabledByDefault.spread_collections,
IsExpired.spread_collections,
'Spread Collections',
firstSupportedVersion: '2.2.2');
static const triple_shift = const ExperimentalFeature(
6,
EnableString.triple_shift,
IsEnabledByDefault.triple_shift,
IsExpired.triple_shift,
'Triple-shift operator');
static const variance = const ExperimentalFeature(7, EnableString.variance,
IsEnabledByDefault.variance, IsExpired.variance, 'Sound variance.');
@deprecated
static const bogus_disabled = const ExperimentalFeature(
8,
// ignore: deprecated_member_use_from_same_package
EnableString.bogus_disabled,
IsEnabledByDefault.bogus_disabled,
IsExpired.bogus_disabled,
null);
@deprecated
static const bogus_enabled = const ExperimentalFeature(
9,
// ignore: deprecated_member_use_from_same_package
EnableString.bogus_enabled,
IsEnabledByDefault.bogus_enabled,
IsExpired.bogus_enabled,
null,
firstSupportedVersion: '1.0.0');
}
/// Constant bools indicating whether each experimental flag is currently
/// enabled by default.
class IsEnabledByDefault {
/// Default state of the experiment "constant-update-2018"
static const bool constant_update_2018 = true;
/// Default state of the experiment "control-flow-collections"
static const bool control_flow_collections = true;
/// Default state of the experiment "extension-methods"
static const bool extension_methods = true;
/// Default state of the experiment "non-nullable"
static const bool non_nullable = false;
/// Default state of the experiment "set-literals"
static const bool set_literals = true;
/// Default state of the experiment "spread-collections"
static const bool spread_collections = true;
/// Default state of the experiment "triple-shift"
static const bool triple_shift = false;
/// Default state of the experiment "variance"
static const bool variance = false;
/// Default state of the experiment "bogus-disabled"
@deprecated
static const bool bogus_disabled = false;
/// Default state of the experiment "bogus-enabled"
@deprecated
static const bool bogus_enabled = true;
}
/// Constant bools indicating whether each experimental flag is currently
/// expired (meaning its enable/disable status can no longer be altered from the
/// value in [IsEnabledByDefault]).
class IsExpired {
/// Expiration status of the experiment "constant-update-2018"
static const bool constant_update_2018 = true;
/// Expiration status of the experiment "control-flow-collections"
static const bool control_flow_collections = true;
/// Expiration status of the experiment "extension-methods"
static const bool extension_methods = false;
/// Expiration status of the experiment "non-nullable"
static const bool non_nullable = false;
/// Expiration status of the experiment "set-literals"
static const bool set_literals = true;
/// Expiration status of the experiment "spread-collections"
static const bool spread_collections = true;
/// Expiration status of the experiment "triple-shift"
static const bool triple_shift = false;
/// Expiration status of the experiment "variance"
static const bool variance = false;
/// Expiration status of the experiment "bogus-disabled"
static const bool bogus_disabled = true;
/// Expiration status of the experiment "bogus-enabled"
static const bool bogus_enabled = true;
}
mixin _CurrentState {
/// Current state for the flag "bogus-disabled"
@deprecated
bool get bogus_disabled => isEnabled(ExperimentalFeatures.bogus_disabled);
/// Current state for the flag "bogus-enabled"
@deprecated
bool get bogus_enabled => isEnabled(ExperimentalFeatures.bogus_enabled);
/// Current state for the flag "constant-update-2018"
bool get constant_update_2018 =>
isEnabled(ExperimentalFeatures.constant_update_2018);
/// Current state for the flag "control-flow-collections"
bool get control_flow_collections =>
isEnabled(ExperimentalFeatures.control_flow_collections);
/// Current state for the flag "extension-methods"
bool get extension_methods =>
isEnabled(ExperimentalFeatures.extension_methods);
/// Current state for the flag "non-nullable"
bool get non_nullable => isEnabled(ExperimentalFeatures.non_nullable);
/// Current state for the flag "set-literals"
bool get set_literals => isEnabled(ExperimentalFeatures.set_literals);
/// Current state for the flag "spread-collections"
bool get spread_collections =>
isEnabled(ExperimentalFeatures.spread_collections);
/// Current state for the flag "triple-shift"
bool get triple_shift => isEnabled(ExperimentalFeatures.triple_shift);
/// Current state for the flag "variance"
bool get variance => isEnabled(ExperimentalFeatures.variance);
bool isEnabled(covariant ExperimentalFeature feature);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/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.
import 'dart:typed_data';
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:analyzer/src/summary/api_signature.dart';
import 'package:analyzer/src/summary/link.dart' as graph
show DependencyWalker, Node;
/// Ensure that the [FileState.libraryCycle] for the [file] and anything it
/// depends on is computed.
void computeLibraryCycle(Uint32List linkedSalt, FileState file) {
var libraryWalker = new _LibraryWalker(linkedSalt);
libraryWalker.walk(libraryWalker.getNode(file));
}
/// Information about libraries that reference each other, so form a cycle.
class LibraryCycle {
/// The libraries that belong to this cycle.
final List<FileState> libraries = [];
/// The library cycles that this cycle references directly.
final Set<LibraryCycle> directDependencies = new Set<LibraryCycle>();
/// The cycles that use this cycle, used to [invalidate] transitively.
final List<LibraryCycle> _directUsers = [];
/// The transitive signature of this cycle.
///
/// It is based on the API signatures of all files of the [libraries], and
/// transitive signatures of the cycles that the [libraries] reference
/// directly. So, indirectly it is based on the transitive closure of all
/// files that [libraries] reference (but we don't compute these files).
String transitiveSignature;
/// The map from a library in [libraries] to its transitive signature.
///
/// It is almost the same as [transitiveSignature], but is also based on
/// the URI of this specific library. Currently we store each linked library
/// with its own key, so we need unique keys. However practically we never
/// can use just *one* library of a cycle, we always use the whole cycle.
///
/// TODO(scheglov) Switch to loading the whole cycle maybe?
final Map<FileState, String> transitiveSignatures = {};
LibraryCycle();
LibraryCycle.external() : transitiveSignature = '<external>';
/// Invalidate this cycle and any cycles that directly or indirectly use it.
///
/// Practically invalidation means that we clear the library cycle in all the
/// [libraries] that share this [LibraryCycle] instance.
void invalidate() {
for (var library in libraries) {
library.internal_setLibraryCycle(null, null);
}
for (var user in _directUsers) {
user.invalidate();
}
_directUsers.clear();
}
@override
String toString() {
return '[' + libraries.join(', ') + ']';
}
}
/// Node in [_LibraryWalker].
class _LibraryNode extends graph.Node<_LibraryNode> {
final _LibraryWalker walker;
final FileState file;
_LibraryNode(this.walker, this.file);
@override
bool get isEvaluated => file.internal_libraryCycle != null;
@override
List<_LibraryNode> computeDependencies() {
return file.directReferencedLibraries.map(walker.getNode).toList();
}
}
/// Helper that organizes dependencies of a library into topologically
/// sorted [LibraryCycle]s.
class _LibraryWalker extends graph.DependencyWalker<_LibraryNode> {
final Uint32List _linkedSalt;
final Map<FileState, _LibraryNode> nodesOfFiles = {};
_LibraryWalker(this._linkedSalt);
@override
void evaluate(_LibraryNode v) {
evaluateScc([v]);
}
@override
void evaluateScc(List<_LibraryNode> scc) {
var cycle = new LibraryCycle();
var signature = new ApiSignature();
signature.addUint32List(_linkedSalt);
// Sort libraries to produce stable signatures.
scc.sort((first, second) {
var firstPath = first.file.path;
var secondPath = second.file.path;
return firstPath.compareTo(secondPath);
});
// Append direct referenced cycles.
for (var node in scc) {
var file = node.file;
_appendDirectlyReferenced(cycle, signature, file.importedFiles);
_appendDirectlyReferenced(cycle, signature, file.exportedFiles);
}
// Fill the cycle with libraries.
for (var node in scc) {
cycle.libraries.add(node.file);
signature.addString(node.file.uriStr);
signature.addInt(node.file.libraryFiles.length);
for (var file in node.file.libraryFiles) {
signature.addBool(file.exists);
signature.addBytes(file.apiSignature);
}
}
// Compute the general library cycle signature.
cycle.transitiveSignature = signature.toHex();
// Compute library specific signatures.
for (var node in scc) {
var librarySignatureBuilder = new ApiSignature()
..addString(node.file.uriStr)
..addString(cycle.transitiveSignature);
var librarySignature = librarySignatureBuilder.toHex();
node.file.internal_setLibraryCycle(
cycle,
librarySignature,
);
}
}
_LibraryNode getNode(FileState file) {
return nodesOfFiles.putIfAbsent(file, () => new _LibraryNode(this, file));
}
void _appendDirectlyReferenced(
LibraryCycle cycle,
ApiSignature signature,
List<FileState> directlyReferenced,
) {
signature.addInt(directlyReferenced.length);
for (var referencedLibrary in directlyReferenced) {
var referencedCycle = referencedLibrary.internal_libraryCycle;
// We get null when the library is a part of the cycle being build.
if (referencedCycle == null) continue;
if (cycle.directDependencies.add(referencedCycle)) {
referencedCycle._directUsers.add(cycle);
signature.addString(referencedCycle.transitiveSignature);
}
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/status.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';
/**
* The status of analysis.
*/
class AnalysisStatus {
static const IDLE = const AnalysisStatus._(false);
static const ANALYZING = const AnalysisStatus._(true);
final bool _analyzing;
const AnalysisStatus._(this._analyzing);
/**
* Return `true` if the scheduler is analyzing.
*/
bool get isAnalyzing => _analyzing;
/**
* Return `true` if the scheduler is idle.
*/
bool get isIdle => !_analyzing;
@override
String toString() => _analyzing ? 'analyzing' : 'idle';
}
/**
* [Monitor] can be used to wait for a signal.
*
* Signals are not queued, the client will receive exactly one signal
* regardless of the number of [notify] invocations. The [signal] is reset
* after completion and will not complete until [notify] is called next time.
*/
class Monitor {
Completer<void> _completer = new Completer<void>();
/**
* Return a [Future] that completes when [notify] is called at least once.
*/
Future<void> get signal async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
await _completer.future;
_completer = new Completer<void>();
}
/**
* Complete the [signal] future if it is not completed yet. It is safe to
* call this method multiple times, but the [signal] will complete only once.
*/
void notify() {
if (!_completer.isCompleted) {
_completer.complete(null);
}
}
}
/**
* Helper for managing transitioning [AnalysisStatus].
*/
class StatusSupport {
/**
* The controller for the [stream].
*/
final _statusController = new StreamController<AnalysisStatus>();
/**
* The last status sent to the [stream].
*/
AnalysisStatus _currentStatus = AnalysisStatus.IDLE;
/**
* If non-null, a completer which should be completed on the next transition
* to idle.
*/
Completer<void> _idleCompleter;
/**
* Return the last status sent to the [stream].
*/
AnalysisStatus get currentStatus => _currentStatus;
/**
* Return the stream that produces [AnalysisStatus] events.
*/
Stream<AnalysisStatus> get stream => _statusController.stream;
/**
* Prepare for the scheduler to start analyzing, but do not notify the
* [stream] yet.
*
* A call to [preTransitionToAnalyzing] has the same effect on [waitForIdle]
* as a call to [transitionToAnalyzing], but it has no effect on the [stream].
*/
void preTransitionToAnalyzing() {
_idleCompleter ??= new Completer<void>();
}
/**
* Send a notification to the [stream] that the scheduler started analyzing.
*/
void transitionToAnalyzing() {
if (_currentStatus != AnalysisStatus.ANALYZING) {
preTransitionToAnalyzing();
_currentStatus = AnalysisStatus.ANALYZING;
_statusController.add(AnalysisStatus.ANALYZING);
}
}
/**
* Send a notification to the [stream] stream that the scheduler is idle.
*/
void transitionToIdle() {
if (_currentStatus != AnalysisStatus.IDLE) {
_currentStatus = AnalysisStatus.IDLE;
_statusController.add(AnalysisStatus.IDLE);
}
_idleCompleter?.complete();
_idleCompleter = null;
}
/**
* Return a future that will be completed the next time the status is idle.
*
* If the status is currently idle, the returned future will be signaled
* immediately.
*/
Future<void> waitForIdle() {
return _idleCompleter?.future ?? new Future<void>.value();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/crc32.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.
const List<int> _CRC32_TABLE = const [
0x00000000,
0x77073096,
0xEE0E612C,
0x990951BA,
0x076DC419,
0x706AF48F,
0xE963A535,
0x9E6495A3,
0x0EDB8832,
0x79DCB8A4,
0xE0D5E91E,
0x97D2D988,
0x09B64C2B,
0x7EB17CBD,
0xE7B82D07,
0x90BF1D91,
0x1DB71064,
0x6AB020F2,
0xF3B97148,
0x84BE41DE,
0x1ADAD47D,
0x6DDDE4EB,
0xF4D4B551,
0x83D385C7,
0x136C9856,
0x646BA8C0,
0xFD62F97A,
0x8A65C9EC,
0x14015C4F,
0x63066CD9,
0xFA0F3D63,
0x8D080DF5,
0x3B6E20C8,
0x4C69105E,
0xD56041E4,
0xA2677172,
0x3C03E4D1,
0x4B04D447,
0xD20D85FD,
0xA50AB56B,
0x35B5A8FA,
0x42B2986C,
0xDBBBC9D6,
0xACBCF940,
0x32D86CE3,
0x45DF5C75,
0xDCD60DCF,
0xABD13D59,
0x26D930AC,
0x51DE003A,
0xC8D75180,
0xBFD06116,
0x21B4F4B5,
0x56B3C423,
0xCFBA9599,
0xB8BDA50F,
0x2802B89E,
0x5F058808,
0xC60CD9B2,
0xB10BE924,
0x2F6F7C87,
0x58684C11,
0xC1611DAB,
0xB6662D3D,
0x76DC4190,
0x01DB7106,
0x98D220BC,
0xEFD5102A,
0x71B18589,
0x06B6B51F,
0x9FBFE4A5,
0xE8B8D433,
0x7807C9A2,
0x0F00F934,
0x9609A88E,
0xE10E9818,
0x7F6A0DBB,
0x086D3D2D,
0x91646C97,
0xE6635C01,
0x6B6B51F4,
0x1C6C6162,
0x856530D8,
0xF262004E,
0x6C0695ED,
0x1B01A57B,
0x8208F4C1,
0xF50FC457,
0x65B0D9C6,
0x12B7E950,
0x8BBEB8EA,
0xFCB9887C,
0x62DD1DDF,
0x15DA2D49,
0x8CD37CF3,
0xFBD44C65,
0x4DB26158,
0x3AB551CE,
0xA3BC0074,
0xD4BB30E2,
0x4ADFA541,
0x3DD895D7,
0xA4D1C46D,
0xD3D6F4FB,
0x4369E96A,
0x346ED9FC,
0xAD678846,
0xDA60B8D0,
0x44042D73,
0x33031DE5,
0xAA0A4C5F,
0xDD0D7CC9,
0x5005713C,
0x270241AA,
0xBE0B1010,
0xC90C2086,
0x5768B525,
0x206F85B3,
0xB966D409,
0xCE61E49F,
0x5EDEF90E,
0x29D9C998,
0xB0D09822,
0xC7D7A8B4,
0x59B33D17,
0x2EB40D81,
0xB7BD5C3B,
0xC0BA6CAD,
0xEDB88320,
0x9ABFB3B6,
0x03B6E20C,
0x74B1D29A,
0xEAD54739,
0x9DD277AF,
0x04DB2615,
0x73DC1683,
0xE3630B12,
0x94643B84,
0x0D6D6A3E,
0x7A6A5AA8,
0xE40ECF0B,
0x9309FF9D,
0x0A00AE27,
0x7D079EB1,
0xF00F9344,
0x8708A3D2,
0x1E01F268,
0x6906C2FE,
0xF762575D,
0x806567CB,
0x196C3671,
0x6E6B06E7,
0xFED41B76,
0x89D32BE0,
0x10DA7A5A,
0x67DD4ACC,
0xF9B9DF6F,
0x8EBEEFF9,
0x17B7BE43,
0x60B08ED5,
0xD6D6A3E8,
0xA1D1937E,
0x38D8C2C4,
0x4FDFF252,
0xD1BB67F1,
0xA6BC5767,
0x3FB506DD,
0x48B2364B,
0xD80D2BDA,
0xAF0A1B4C,
0x36034AF6,
0x41047A60,
0xDF60EFC3,
0xA867DF55,
0x316E8EEF,
0x4669BE79,
0xCB61B38C,
0xBC66831A,
0x256FD2A0,
0x5268E236,
0xCC0C7795,
0xBB0B4703,
0x220216B9,
0x5505262F,
0xC5BA3BBE,
0xB2BD0B28,
0x2BB45A92,
0x5CB36A04,
0xC2D7FFA7,
0xB5D0CF31,
0x2CD99E8B,
0x5BDEAE1D,
0x9B64C2B0,
0xEC63F226,
0x756AA39C,
0x026D930A,
0x9C0906A9,
0xEB0E363F,
0x72076785,
0x05005713,
0x95BF4A82,
0xE2B87A14,
0x7BB12BAE,
0x0CB61B38,
0x92D28E9B,
0xE5D5BE0D,
0x7CDCEFB7,
0x0BDBDF21,
0x86D3D2D4,
0xF1D4E242,
0x68DDB3F8,
0x1FDA836E,
0x81BE16CD,
0xF6B9265B,
0x6FB077E1,
0x18B74777,
0x88085AE6,
0xFF0F6A70,
0x66063BCA,
0x11010B5C,
0x8F659EFF,
0xF862AE69,
0x616BFFD3,
0x166CCF45,
0xA00AE278,
0xD70DD2EE,
0x4E048354,
0x3903B3C2,
0xA7672661,
0xD06016F7,
0x4969474D,
0x3E6E77DB,
0xAED16A4A,
0xD9D65ADC,
0x40DF0B66,
0x37D83BF0,
0xA9BCAE53,
0xDEBB9EC5,
0x47B2CF7F,
0x30B5FFE9,
0xBDBDF21C,
0xCABAC28A,
0x53B39330,
0x24B4A3A6,
0xBAD03605,
0xCDD70693,
0x54DE5729,
0x23D967BF,
0xB3667A2E,
0xC4614AB8,
0x5D681B02,
0x2A6F2B94,
0xB40BBE37,
0xC30C8EA1,
0x5A05DF1B,
0x2D02EF8D
];
/**
* Get the CRC-32 checksum of the given array. You can append bytes to an
* already computed crc by specifying the previous [crc] value.
*/
int getCrc32(List<int> array, [int crc = 0]) {
int len = array.length;
crc = crc ^ 0xffffffff;
int ip = 0;
while (len >= 8) {
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
len -= 8;
}
if (len > 0)
do {
crc = _CRC32_TABLE[(crc ^ array[ip++]) & 0xff] ^ (crc >> 8);
} while (--len > 0);
return crc ^ 0xffffffff;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/uri_converter.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/dart/analysis/uri_converter.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:path/src/context.dart';
/**
* An implementation of a URI converter based on an analysis driver.
*/
class DriverBasedUriConverter implements UriConverter {
/**
* The driver associated with the context in which the conversion will occur.
*/
final AnalysisDriver driver;
/**
* Initialize a newly created URI converter to use the given [driver] to =
* perform the conversions.
*/
DriverBasedUriConverter(this.driver);
@override
Uri pathToUri(String path, {String containingPath}) {
ResourceProvider provider = driver.resourceProvider;
if (containingPath != null) {
Context context = provider.pathContext;
String root = driver.contextRoot.root;
if (context.isWithin(root, path) &&
context.isWithin(root, containingPath)) {
String relativePath =
context.relative(path, from: context.dirname(containingPath));
if (context.isRelative(relativePath)) {
return new Uri.file(relativePath);
}
}
}
Source source = provider.getFile(path).createSource();
return driver.sourceFactory.restoreUri(source);
}
@override
String uriToPath(Uri uri) => driver.sourceFactory.forUri2(uri)?.fullName;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/index.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/summary/format.dart';
import 'package:analyzer/src/summary/idl.dart';
/**
* Return the [CompilationUnitElement] that should be used for [element].
* Throw [StateError] if the [element] is not linked into a unit.
*/
CompilationUnitElement getUnitElement(Element element) {
for (Element e = element; e != null; e = e.enclosingElement) {
if (e is CompilationUnitElement) {
return e;
}
if (e is LibraryElement) {
return e.definingCompilationUnit;
}
}
throw new StateError('Element not contained in compilation unit: $element');
}
/**
* Index the [unit] into a new [AnalysisDriverUnitIndexBuilder].
*/
AnalysisDriverUnitIndexBuilder indexUnit(CompilationUnit unit) {
return new _IndexAssembler().assemble(unit);
}
/**
* Information about an element that is actually put into index for some other
* related element. For example for a synthetic getter this is the corresponding
* non-synthetic field and [IndexSyntheticElementKind.getter] as the [kind].
*/
class IndexElementInfo {
final Element element;
final IndexSyntheticElementKind kind;
factory IndexElementInfo(Element element) {
IndexSyntheticElementKind kind = IndexSyntheticElementKind.notSynthetic;
ElementKind elementKind = element.kind;
if (elementKind == ElementKind.LIBRARY ||
elementKind == ElementKind.COMPILATION_UNIT) {
kind = IndexSyntheticElementKind.unit;
} else if (element.isSynthetic) {
if (elementKind == ElementKind.CONSTRUCTOR) {
kind = IndexSyntheticElementKind.constructor;
element = element.enclosingElement;
} else if (elementKind == ElementKind.FUNCTION &&
element.name == 'loadLibrary') {
kind = IndexSyntheticElementKind.loadLibrary;
element = element.library;
} else if (elementKind == ElementKind.FIELD) {
FieldElement field = element;
kind = IndexSyntheticElementKind.field;
element = field.getter ?? field.setter;
} else if (elementKind == ElementKind.GETTER ||
elementKind == ElementKind.SETTER) {
PropertyAccessorElement accessor = element;
Element enclosing = element.enclosingElement;
bool isEnumGetter = enclosing is ClassElement && enclosing.isEnum;
if (isEnumGetter && accessor.name == 'index') {
kind = IndexSyntheticElementKind.enumIndex;
element = enclosing;
} else if (isEnumGetter && accessor.name == 'values') {
kind = IndexSyntheticElementKind.enumValues;
element = enclosing;
} else {
kind = accessor.isGetter
? IndexSyntheticElementKind.getter
: IndexSyntheticElementKind.setter;
element = accessor.variable;
}
} else if (elementKind == ElementKind.METHOD) {
Element enclosing = element.enclosingElement;
bool isEnumMethod = enclosing is ClassElement && enclosing.isEnum;
if (isEnumMethod && element.name == 'toString') {
kind = IndexSyntheticElementKind.enumToString;
element = enclosing;
}
} else if (elementKind == ElementKind.TOP_LEVEL_VARIABLE) {
TopLevelVariableElement property = element;
kind = IndexSyntheticElementKind.topLevelVariable;
element = property.getter ?? property.setter;
} else {
throw new ArgumentError(
'Unsupported synthetic element ${element.runtimeType}');
}
}
return new IndexElementInfo._(element, kind);
}
IndexElementInfo._(this.element, this.kind);
}
/**
* Information about an element referenced in index.
*/
class _ElementInfo {
/**
* The identifier of the [CompilationUnitElement] containing this element.
*/
final int unitId;
/**
* The identifier of the top-level name, or `null` if the element is a
* reference to the unit.
*/
final _StringInfo nameIdUnitMember;
/**
* The identifier of the class member name, or `null` if the element is not a
* class member or a named parameter of a class member.
*/
final _StringInfo nameIdClassMember;
/**
* The identifier of the named parameter name, or `null` if the element is not
* a named parameter.
*/
final _StringInfo nameIdParameter;
/**
* The kind of the element.
*/
final IndexSyntheticElementKind kind;
/**
* The unique id of the element. It is set after indexing of the whole
* package is done and we are assembling the full package index.
*/
int id;
_ElementInfo(this.unitId, this.nameIdUnitMember, this.nameIdClassMember,
this.nameIdParameter, this.kind);
}
/**
* Information about a single relation in a single compilation unit.
*/
class _ElementRelationInfo {
final _ElementInfo elementInfo;
final IndexRelationKind kind;
final int offset;
final int length;
final bool isQualified;
_ElementRelationInfo(
this.elementInfo, this.kind, this.offset, this.length, this.isQualified);
}
/**
* Assembler of a single [CompilationUnit] index.
*
* The intended usage sequence:
*
* - Call [addElementRelation] for each element relation found in the unit.
* - Call [addNameRelation] for each name relation found in the unit.
* - Assign ids to all the [_ElementInfo] in [elementRelations].
* - Call [assemble] to produce the final unit index.
*/
class _IndexAssembler {
/**
* The string to use in place of the `null` string.
*/
static const NULL_STRING = '--nullString--';
/**
* Map associating referenced elements with their [_ElementInfo]s.
*/
final Map<Element, _ElementInfo> elementMap = {};
/**
* Map associating [CompilationUnitElement]s with their identifiers, which
* are indices into [unitLibraryUris] and [unitUnitUris].
*/
final Map<CompilationUnitElement, int> unitMap = {};
/**
* The fields [unitLibraryUris] and [unitUnitUris] are used together to
* describe each unique [CompilationUnitElement].
*
* This field contains the library URI of a unit.
*/
final List<_StringInfo> unitLibraryUris = [];
/**
* The fields [unitLibraryUris] and [unitUnitUris] are used together to
* describe each unique [CompilationUnitElement].
*
* This field contains the unit URI of a unit, which might be the same as
* the library URI for the defining unit, or a different one for a part.
*/
final List<_StringInfo> unitUnitUris = [];
/**
* Map associating strings with their [_StringInfo]s.
*/
final Map<String, _StringInfo> stringMap = {};
/**
* All element relations.
*/
final List<_ElementRelationInfo> elementRelations = [];
/**
* All unresolved name relations.
*/
final List<_NameRelationInfo> nameRelations = [];
/**
* All subtypes declared in the unit.
*/
final List<_SubtypeInfo> subtypes = [];
/**
* The [_StringInfo] to use for `null` strings.
*/
_StringInfo nullString;
_IndexAssembler() {
nullString = _getStringInfo(NULL_STRING);
}
void addElementRelation(Element element, IndexRelationKind kind, int offset,
int length, bool isQualified) {
_ElementInfo elementInfo = _getElementInfo(element);
elementRelations.add(new _ElementRelationInfo(
elementInfo, kind, offset, length, isQualified));
}
void addNameRelation(
String name, IndexRelationKind kind, int offset, bool isQualified) {
_StringInfo nameId = _getStringInfo(name);
nameRelations.add(new _NameRelationInfo(nameId, kind, offset, isQualified));
}
void addSubtype(String name, List<String> members, List<String> supertypes) {
for (var supertype in supertypes) {
subtypes.add(
new _SubtypeInfo(
_getStringInfo(supertype),
_getStringInfo(name),
members.map(_getStringInfo).toList(),
),
);
}
}
/**
* Index the [unit] and assemble a new [AnalysisDriverUnitIndexBuilder].
*/
AnalysisDriverUnitIndexBuilder assemble(CompilationUnit unit) {
unit.accept(new _IndexContributor(this));
// Sort strings and set IDs.
List<_StringInfo> stringInfoList = stringMap.values.toList();
stringInfoList.sort((a, b) {
return a.value.compareTo(b.value);
});
for (int i = 0; i < stringInfoList.length; i++) {
stringInfoList[i].id = i;
}
// Sort elements and set IDs.
List<_ElementInfo> elementInfoList = elementMap.values.toList();
elementInfoList.sort((a, b) {
int delta;
delta = a.nameIdUnitMember.id - b.nameIdUnitMember.id;
if (delta != 0) {
return delta;
}
delta = a.nameIdClassMember.id - b.nameIdClassMember.id;
if (delta != 0) {
return delta;
}
return a.nameIdParameter.id - b.nameIdParameter.id;
});
for (int i = 0; i < elementInfoList.length; i++) {
elementInfoList[i].id = i;
}
// Sort element and name relations.
elementRelations.sort((a, b) {
return a.elementInfo.id - b.elementInfo.id;
});
nameRelations.sort((a, b) {
return a.nameInfo.id - b.nameInfo.id;
});
// Sort subtypes by supertypes.
subtypes.sort((a, b) {
return a.supertype.id - b.supertype.id;
});
return new AnalysisDriverUnitIndexBuilder(
strings: stringInfoList.map((s) => s.value).toList(),
nullStringId: nullString.id,
unitLibraryUris: unitLibraryUris.map((s) => s.id).toList(),
unitUnitUris: unitUnitUris.map((s) => s.id).toList(),
elementKinds: elementInfoList.map((e) => e.kind).toList(),
elementUnits: elementInfoList.map((e) => e.unitId).toList(),
elementNameUnitMemberIds:
elementInfoList.map((e) => e.nameIdUnitMember.id).toList(),
elementNameClassMemberIds:
elementInfoList.map((e) => e.nameIdClassMember.id).toList(),
elementNameParameterIds:
elementInfoList.map((e) => e.nameIdParameter.id).toList(),
usedElements: elementRelations.map((r) => r.elementInfo.id).toList(),
usedElementKinds: elementRelations.map((r) => r.kind).toList(),
usedElementOffsets: elementRelations.map((r) => r.offset).toList(),
usedElementLengths: elementRelations.map((r) => r.length).toList(),
usedElementIsQualifiedFlags:
elementRelations.map((r) => r.isQualified).toList(),
usedNames: nameRelations.map((r) => r.nameInfo.id).toList(),
usedNameKinds: nameRelations.map((r) => r.kind).toList(),
usedNameOffsets: nameRelations.map((r) => r.offset).toList(),
usedNameIsQualifiedFlags:
nameRelations.map((r) => r.isQualified).toList(),
supertypes: subtypes.map((subtype) => subtype.supertype.id).toList(),
subtypes: subtypes.map((subtype) {
return new AnalysisDriverSubtypeBuilder(
name: subtype.name.id,
members: subtype.members.map((member) => member.id).toList(),
);
}).toList());
}
/**
* Return the unique [_ElementInfo] corresponding the [element]. The field
* [_ElementInfo.id] is filled by [assemble] during final sorting.
*/
_ElementInfo _getElementInfo(Element element) {
if (element is Member) {
element = (element as Member).baseElement;
}
return elementMap.putIfAbsent(element, () {
CompilationUnitElement unitElement = getUnitElement(element);
int unitId = _getUnitId(unitElement);
return _newElementInfo(unitId, element);
});
}
/**
* Return the unique [_StringInfo] corresponding the given [string]. The
* field [_StringInfo.id] is filled by [assemble] during final sorting.
*/
_StringInfo _getStringInfo(String string) {
return stringMap.putIfAbsent(string, () {
return new _StringInfo(string);
});
}
/**
* Add information about [unitElement] to [unitUnitUris] and
* [unitLibraryUris] if necessary, and return the location in those
* arrays representing [unitElement].
*/
int _getUnitId(CompilationUnitElement unitElement) {
return unitMap.putIfAbsent(unitElement, () {
assert(unitLibraryUris.length == unitUnitUris.length);
int id = unitUnitUris.length;
unitLibraryUris.add(_getUriInfo(unitElement.library.source.uri));
unitUnitUris.add(_getUriInfo(unitElement.source.uri));
return id;
});
}
/**
* Return the unique [_StringInfo] corresponding [uri]. The field
* [_StringInfo.id] is filled by [assemble] during final sorting.
*/
_StringInfo _getUriInfo(Uri uri) {
String str = uri.toString();
return _getStringInfo(str);
}
/**
* Return a new [_ElementInfo] for the given [element] in the given [unitId].
* This method is static, so it cannot add any information to the index.
*/
_ElementInfo _newElementInfo(int unitId, Element element) {
IndexElementInfo info = new IndexElementInfo(element);
element = info.element;
// Prepare name identifiers.
_StringInfo nameIdParameter = nullString;
_StringInfo nameIdClassMember = nullString;
_StringInfo nameIdUnitMember = nullString;
if (element is ParameterElement) {
nameIdParameter = _getStringInfo(element.name);
element = element.enclosingElement;
}
if (element?.enclosingElement is ClassElement ||
element?.enclosingElement is ExtensionElement) {
nameIdClassMember = _getStringInfo(element.name);
element = element.enclosingElement;
}
if (element?.enclosingElement is CompilationUnitElement) {
nameIdUnitMember = _getStringInfo(element.name);
}
return new _ElementInfo(unitId, nameIdUnitMember, nameIdClassMember,
nameIdParameter, info.kind);
}
}
/**
* Visits a resolved AST and adds relationships into the [assembler].
*/
class _IndexContributor extends GeneralizingAstVisitor {
final _IndexAssembler assembler;
_IndexContributor(this.assembler);
void recordIsAncestorOf(Element descendant) {
_recordIsAncestorOf(descendant, descendant, false, <ClassElement>[]);
}
/**
* Record that the name [node] has a relation of the given [kind].
*/
void recordNameRelation(
SimpleIdentifier node, IndexRelationKind kind, bool isQualified) {
if (node != null) {
assembler.addNameRelation(node.name, kind, node.offset, isQualified);
}
}
/**
* Record reference to the given operator [Element].
*/
void recordOperatorReference(Token operator, Element element) {
recordRelationToken(element, IndexRelationKind.IS_INVOKED_BY, operator);
}
/**
* Record that [element] has a relation of the given [kind] at the location
* of the given [node]. The flag [isQualified] is `true` if [node] has an
* explicit or implicit qualifier, so cannot be shadowed by a local
* declaration.
*/
void recordRelation(
Element element, IndexRelationKind kind, AstNode node, bool isQualified) {
if (element != null && node != null) {
recordRelationOffset(
element, kind, node.offset, node.length, isQualified);
}
}
/**
* Record that [element] has a relation of the given [kind] at the given
* [offset] and [length]. The flag [isQualified] is `true` if the relation
* has an explicit or implicit qualifier, so [element] cannot be shadowed by
* a local declaration.
*/
void recordRelationOffset(Element element, IndexRelationKind kind, int offset,
int length, bool isQualified) {
// Ignore elements that can't be referenced outside of the unit.
ElementKind elementKind = element?.kind;
if (elementKind == null ||
elementKind == ElementKind.DYNAMIC ||
elementKind == ElementKind.ERROR ||
elementKind == ElementKind.LABEL ||
elementKind == ElementKind.LOCAL_VARIABLE ||
elementKind == ElementKind.NEVER ||
elementKind == ElementKind.PREFIX ||
elementKind == ElementKind.TYPE_PARAMETER ||
elementKind == ElementKind.FUNCTION &&
element is FunctionElement &&
element.enclosingElement is ExecutableElement ||
elementKind == ElementKind.PARAMETER &&
element is ParameterElement &&
!element.isOptional ||
false) {
return;
}
// Ignore named parameters of synthetic functions, e.g. created for LUB.
// These functions are not bound to a source, we cannot index them.
if (elementKind == ElementKind.PARAMETER &&
element is ParameterElement &&
(element.enclosingElement == null ||
element.enclosingElement.isSynthetic)) {
return;
}
// Elements for generic function types are enclosed by the compilation
// units, but don't have names. So, we cannot index references to their
// named parameters. Ignore them.
if (elementKind == ElementKind.PARAMETER &&
element is ParameterElement &&
element.enclosingElement is GenericFunctionTypeElement) {
return;
}
// Add the relation.
assembler.addElementRelation(element, kind, offset, length, isQualified);
}
/**
* Record that [element] has a relation of the given [kind] at the location
* of the given [token].
*/
void recordRelationToken(
Element element, IndexRelationKind kind, Token token) {
if (element != null && token != null) {
recordRelationOffset(element, kind, token.offset, token.length, true);
}
}
/**
* Record a relation between a super [typeName] and its [Element].
*/
void recordSuperType(TypeName typeName, IndexRelationKind kind) {
Identifier name = typeName?.name;
if (name != null) {
Element element = name.staticElement;
bool isQualified;
SimpleIdentifier relNode;
if (name is PrefixedIdentifier) {
isQualified = true;
relNode = name.identifier;
} else {
isQualified = false;
relNode = name;
}
recordRelation(element, kind, relNode, isQualified);
recordRelation(
element, IndexRelationKind.IS_REFERENCED_BY, relNode, isQualified);
typeName.typeArguments?.accept(this);
}
}
void recordUriReference(Element element, StringLiteral uri) {
recordRelation(element, IndexRelationKind.IS_REFERENCED_BY, uri, true);
}
@override
visitAssignmentExpression(AssignmentExpression node) {
recordOperatorReference(node.operator, node.staticElement);
super.visitAssignmentExpression(node);
}
@override
visitBinaryExpression(BinaryExpression node) {
recordOperatorReference(node.operator, node.staticElement);
super.visitBinaryExpression(node);
}
@override
visitClassDeclaration(ClassDeclaration node) {
_addSubtypeForClassDeclaration(node);
if (node.extendsClause == null) {
ClassElement objectElement = node.declaredElement.supertype?.element;
recordRelationOffset(objectElement, IndexRelationKind.IS_EXTENDED_BY,
node.name.offset, 0, true);
}
recordIsAncestorOf(node.declaredElement);
super.visitClassDeclaration(node);
}
@override
visitClassTypeAlias(ClassTypeAlias node) {
_addSubtypeForClassTypeAlis(node);
recordIsAncestorOf(node.declaredElement);
super.visitClassTypeAlias(node);
}
@override
visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
SimpleIdentifier fieldName = node.fieldName;
if (fieldName != null) {
Element element = fieldName.staticElement;
recordRelation(element, IndexRelationKind.IS_WRITTEN_BY, fieldName, true);
}
node.expression?.accept(this);
}
@override
visitConstructorName(ConstructorName node) {
ConstructorElement element = node.staticElement;
element = _getActualConstructorElement(element);
// record relation
if (node.name != null) {
int offset = node.period.offset;
int length = node.name.end - offset;
recordRelationOffset(
element, IndexRelationKind.IS_REFERENCED_BY, offset, length, true);
} else {
int offset = node.type.end;
recordRelationOffset(
element, IndexRelationKind.IS_REFERENCED_BY, offset, 0, true);
}
node.type.accept(this);
}
@override
visitExportDirective(ExportDirective node) {
ExportElement element = node.element;
recordUriReference(element?.exportedLibrary, node.uri);
super.visitExportDirective(node);
}
@override
visitExpression(Expression node) {
ParameterElement parameterElement = node.staticParameterElement;
if (parameterElement != null && parameterElement.isOptionalPositional) {
recordRelationOffset(parameterElement, IndexRelationKind.IS_REFERENCED_BY,
node.offset, 0, true);
}
super.visitExpression(node);
}
@override
visitExtendsClause(ExtendsClause node) {
recordSuperType(node.superclass, IndexRelationKind.IS_EXTENDED_BY);
}
@override
visitImplementsClause(ImplementsClause node) {
for (TypeName typeName in node.interfaces) {
recordSuperType(typeName, IndexRelationKind.IS_IMPLEMENTED_BY);
}
}
@override
visitImportDirective(ImportDirective node) {
ImportElement element = node.element;
recordUriReference(element?.importedLibrary, node.uri);
super.visitImportDirective(node);
}
@override
visitIndexExpression(IndexExpression node) {
MethodElement element = node.staticElement;
if (element is MethodElement) {
Token operator = node.leftBracket;
recordRelationToken(element, IndexRelationKind.IS_INVOKED_BY, operator);
}
super.visitIndexExpression(node);
}
@override
visitLibraryIdentifier(LibraryIdentifier node) {}
@override
visitMethodInvocation(MethodInvocation node) {
SimpleIdentifier name = node.methodName;
Element element = name.staticElement;
// unresolved name invocation
bool isQualified = node.realTarget != null;
if (element == null) {
recordNameRelation(name, IndexRelationKind.IS_INVOKED_BY, isQualified);
}
// element invocation
IndexRelationKind kind = element is ClassElement
? IndexRelationKind.IS_REFERENCED_BY
: IndexRelationKind.IS_INVOKED_BY;
recordRelation(element, kind, name, isQualified);
node.target?.accept(this);
node.typeArguments?.accept(this);
node.argumentList?.accept(this);
}
@override
visitMixinDeclaration(MixinDeclaration node) {
_addSubtypeForMixinDeclaration(node);
recordIsAncestorOf(node.declaredElement);
super.visitMixinDeclaration(node);
}
@override
visitOnClause(OnClause node) {
for (TypeName typeName in node.superclassConstraints) {
recordSuperType(typeName, IndexRelationKind.IS_IMPLEMENTED_BY);
}
}
@override
visitPartDirective(PartDirective node) {
CompilationUnitElement element = node.element;
if (element?.source != null) {
recordUriReference(element, node.uri);
}
super.visitPartDirective(node);
}
@override
visitPostfixExpression(PostfixExpression node) {
recordOperatorReference(node.operator, node.staticElement);
super.visitPostfixExpression(node);
}
@override
visitPrefixExpression(PrefixExpression node) {
recordOperatorReference(node.operator, node.staticElement);
super.visitPrefixExpression(node);
}
@override
visitRedirectingConstructorInvocation(RedirectingConstructorInvocation node) {
ConstructorElement element = node.staticElement;
if (node.constructorName != null) {
int offset = node.period.offset;
int length = node.constructorName.end - offset;
recordRelationOffset(
element, IndexRelationKind.IS_REFERENCED_BY, offset, length, true);
} else {
int offset = node.thisKeyword.end;
recordRelationOffset(
element, IndexRelationKind.IS_REFERENCED_BY, offset, 0, true);
}
super.visitRedirectingConstructorInvocation(node);
}
@override
visitSimpleIdentifier(SimpleIdentifier node) {
// name in declaration
if (node.inDeclarationContext()) {
return;
}
Element element = node.staticElement;
// record unresolved name reference
bool isQualified = _isQualified(node);
if (element == null) {
bool inGetterContext = node.inGetterContext();
bool inSetterContext = node.inSetterContext();
IndexRelationKind kind;
if (inGetterContext && inSetterContext) {
kind = IndexRelationKind.IS_READ_WRITTEN_BY;
} else if (inGetterContext) {
kind = IndexRelationKind.IS_READ_BY;
} else {
kind = IndexRelationKind.IS_WRITTEN_BY;
}
recordNameRelation(node, kind, isQualified);
}
// this.field parameter
if (element is FieldFormalParameterElement) {
AstNode parent = node.parent;
IndexRelationKind kind =
parent is FieldFormalParameter && parent.identifier == node
? IndexRelationKind.IS_WRITTEN_BY
: IndexRelationKind.IS_REFERENCED_BY;
recordRelation(element.field, kind, node, true);
return;
}
// ignore a local reference to a parameter
if (element is ParameterElement && node.parent is! Label) {
return;
}
// record specific relations
recordRelation(
element, IndexRelationKind.IS_REFERENCED_BY, node, isQualified);
}
@override
visitSuperConstructorInvocation(SuperConstructorInvocation node) {
ConstructorElement element = node.staticElement;
if (node.constructorName != null) {
int offset = node.period.offset;
int length = node.constructorName.end - offset;
recordRelationOffset(
element, IndexRelationKind.IS_REFERENCED_BY, offset, length, true);
} else {
int offset = node.superKeyword.end;
recordRelationOffset(
element, IndexRelationKind.IS_REFERENCED_BY, offset, 0, true);
}
node.argumentList?.accept(this);
}
@override
visitTypeName(TypeName node) {
AstNode parent = node.parent;
if (parent is ClassTypeAlias && parent.superclass == node) {
recordSuperType(node, IndexRelationKind.IS_EXTENDED_BY);
} else {
super.visitTypeName(node);
}
}
@override
visitWithClause(WithClause node) {
for (TypeName typeName in node.mixinTypes) {
recordSuperType(typeName, IndexRelationKind.IS_MIXED_IN_BY);
}
}
/**
* Record the given class as a subclass of its direct superclasses.
*/
void _addSubtype(String name,
{TypeName superclass,
WithClause withClause,
OnClause onClause,
ImplementsClause implementsClause,
List<ClassMember> memberNodes}) {
List<String> supertypes = [];
List<String> members = [];
String getClassElementId(ClassElement element) {
return element.library.source.uri.toString() +
';' +
element.source.uri.toString() +
';' +
element.name;
}
void addSupertype(TypeName type) {
Element element = type?.name?.staticElement;
if (element is ClassElement) {
String id = getClassElementId(element);
supertypes.add(id);
}
}
addSupertype(superclass);
withClause?.mixinTypes?.forEach(addSupertype);
onClause?.superclassConstraints?.forEach(addSupertype);
implementsClause?.interfaces?.forEach(addSupertype);
void addMemberName(SimpleIdentifier identifier) {
if (identifier != null) {
String name = identifier.name;
if (name != null && name.isNotEmpty) {
members.add(name);
}
}
}
for (ClassMember member in memberNodes) {
if (member is MethodDeclaration && !member.isStatic) {
addMemberName(member.name);
} else if (member is FieldDeclaration && !member.isStatic) {
for (var field in member.fields.variables) {
addMemberName(field.name);
}
}
}
supertypes.sort();
members.sort();
assembler.addSubtype(name, members, supertypes);
}
/**
* Record the given class as a subclass of its direct superclasses.
*/
void _addSubtypeForClassDeclaration(ClassDeclaration node) {
_addSubtype(node.name.name,
superclass: node.extendsClause?.superclass,
withClause: node.withClause,
implementsClause: node.implementsClause,
memberNodes: node.members);
}
/**
* Record the given class as a subclass of its direct superclasses.
*/
void _addSubtypeForClassTypeAlis(ClassTypeAlias node) {
_addSubtype(node.name.name,
superclass: node.superclass,
withClause: node.withClause,
implementsClause: node.implementsClause,
memberNodes: const []);
}
/**
* Record the given mixin as a subclass of its direct superclasses.
*/
void _addSubtypeForMixinDeclaration(MixinDeclaration node) {
_addSubtype(node.name.name,
onClause: node.onClause,
implementsClause: node.implementsClause,
memberNodes: node.members);
}
/**
* If the given [constructor] is a synthetic constructor created for a
* [ClassTypeAlias], return the actual constructor of a [ClassDeclaration]
* which is invoked. Return `null` if a redirection cycle is detected.
*/
ConstructorElement _getActualConstructorElement(
ConstructorElement constructor) {
Set<ConstructorElement> seenConstructors = new Set<ConstructorElement>();
while (constructor != null &&
constructor.isSynthetic &&
constructor.redirectedConstructor != null) {
constructor = constructor.redirectedConstructor;
// fail if a cycle is detected
if (!seenConstructors.add(constructor)) {
return null;
}
}
return constructor;
}
/**
* Return `true` if [node] has an explicit or implicit qualifier, so that it
* cannot be shadowed by a local declaration.
*/
bool _isQualified(SimpleIdentifier node) {
if (node.isQualified) {
return true;
}
AstNode parent = node.parent;
return parent is Combinator || parent is Label;
}
void _recordIsAncestorOf(Element descendant, ClassElement ancestor,
bool includeThis, List<ClassElement> visitedElements) {
if (ancestor == null) {
return;
}
if (visitedElements.contains(ancestor)) {
return;
}
visitedElements.add(ancestor);
if (includeThis) {
int offset = descendant.nameOffset;
int length = descendant.nameLength;
assembler.addElementRelation(
ancestor, IndexRelationKind.IS_ANCESTOR_OF, offset, length, false);
}
{
InterfaceType superType = ancestor.supertype;
if (superType != null) {
_recordIsAncestorOf(
descendant, superType.element, true, visitedElements);
}
}
for (InterfaceType mixinType in ancestor.mixins) {
_recordIsAncestorOf(descendant, mixinType.element, true, visitedElements);
}
for (InterfaceType type in ancestor.superclassConstraints) {
_recordIsAncestorOf(descendant, type.element, true, visitedElements);
}
for (InterfaceType implementedType in ancestor.interfaces) {
_recordIsAncestorOf(
descendant, implementedType.element, true, visitedElements);
}
}
}
/**
* Information about a single name relation in single compilation unit.
*/
class _NameRelationInfo {
final _StringInfo nameInfo;
final IndexRelationKind kind;
final int offset;
final bool isQualified;
_NameRelationInfo(this.nameInfo, this.kind, this.offset, this.isQualified);
}
/**
* Information about a string referenced in the index.
*/
class _StringInfo {
/**
* The value of the string.
*/
final String value;
/**
* The unique id of the string. It is set after indexing of the whole
* package is done and we are assembling the full package index.
*/
int id;
_StringInfo(this.value);
}
/**
* Information about a subtype in the index.
*/
class _SubtypeInfo {
/**
* The identifier of a direct supertype.
*/
final _StringInfo supertype;
/**
* The name of the class.
*/
final _StringInfo name;
/**
* The names of defined instance members.
*/
final List<_StringInfo> members;
_SubtypeInfo(this.supertype, this.name, this.members);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/defined_names.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
/**
* Compute the [DefinedNames] for the given [unit].
*/
DefinedNames computeDefinedNames(CompilationUnit unit) {
DefinedNames names = new DefinedNames();
void appendName(Set<String> names, SimpleIdentifier node) {
String name = node?.name;
if (name != null && name.isNotEmpty) {
names.add(name);
}
}
void appendClassMemberName(ClassMember member) {
if (member is MethodDeclaration) {
appendName(names.classMemberNames, member.name);
} else if (member is FieldDeclaration) {
for (VariableDeclaration field in member.fields.variables) {
appendName(names.classMemberNames, field.name);
}
}
}
void appendTopLevelName(CompilationUnitMember member) {
if (member is NamedCompilationUnitMember) {
appendName(names.topLevelNames, member.name);
if (member is ClassDeclaration) {
member.members.forEach(appendClassMemberName);
}
if (member is MixinDeclaration) {
member.members.forEach(appendClassMemberName);
}
} else if (member is TopLevelVariableDeclaration) {
for (VariableDeclaration variable in member.variables.variables) {
appendName(names.topLevelNames, variable.name);
}
}
}
unit.declarations.forEach(appendTopLevelName);
return names;
}
/**
* Defined top-level and class member names.
*/
class DefinedNames {
final Set<String> topLevelNames = new Set<String>();
final Set<String> classMemberNames = new Set<String>();
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/context_locator.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:collection';
import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/context_locator.dart';
import 'package:analyzer/dart/analysis/context_root.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart'
show PhysicalResourceProvider;
import 'package:analyzer/src/context/builder.dart'
show ContextBuilder, ContextBuilderOptions;
import 'package:analyzer/src/context/context_root.dart' as old;
import 'package:analyzer/src/dart/analysis/byte_store.dart'
show MemoryByteStore;
import 'package:analyzer/src/dart/analysis/context_root.dart';
import 'package:analyzer/src/dart/analysis/driver.dart'
show AnalysisDriver, AnalysisDriverScheduler;
import 'package:analyzer/src/dart/analysis/driver_based_analysis_context.dart';
import 'package:analyzer/src/dart/analysis/file_state.dart'
show FileContentOverlay;
import 'package:analyzer/src/dart/analysis/performance_logger.dart'
show PerformanceLog;
import 'package:analyzer/src/dart/sdk/sdk.dart' show FolderBasedDartSdk;
import 'package:analyzer/src/generated/sdk.dart' show DartSdkManager;
import 'package:analyzer/src/task/options.dart';
import 'package:analyzer/src/util/yaml.dart';
import 'package:glob/glob.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart';
import 'package:yaml/yaml.dart';
/**
* An implementation of a context locator.
*/
class ContextLocatorImpl implements ContextLocator {
/**
* The name of the analysis options file.
*/
static const String ANALYSIS_OPTIONS_NAME = 'analysis_options.yaml';
/**
* The old name of the analysis options file.
*/
static const String OLD_ANALYSIS_OPTIONS_NAME = '.analysis_options';
/**
* The name of the packages file.
*/
static const String PACKAGES_FILE_NAME = '.packages';
/**
* The resource provider used to access the file system.
*/
final ResourceProvider resourceProvider;
/**
* Initialize a newly created context locator. If a [resourceProvider] is
* supplied, it will be used to access the file system. Otherwise the default
* resource provider will be used.
*/
ContextLocatorImpl({ResourceProvider resourceProvider})
: this.resourceProvider =
resourceProvider ?? PhysicalResourceProvider.INSTANCE;
/**
* Return the path to the default location of the SDK.
*/
String get _defaultSdkPath =>
FolderBasedDartSdk.defaultSdkDirectory(resourceProvider).path;
@deprecated
@override
List<AnalysisContext> locateContexts(
{@required List<String> includedPaths,
List<String> excludedPaths: const <String>[],
String optionsFile,
String packagesFile,
String sdkPath}) {
List<ContextRoot> roots = locateRoots(
includedPaths: includedPaths,
excludedPaths: excludedPaths,
optionsFile: optionsFile,
packagesFile: packagesFile);
if (roots.isEmpty) {
return const <AnalysisContext>[];
}
PerformanceLog performanceLog = new PerformanceLog(new StringBuffer());
AnalysisDriverScheduler scheduler =
new AnalysisDriverScheduler(performanceLog);
DartSdkManager sdkManager =
new DartSdkManager(sdkPath ?? _defaultSdkPath, true);
scheduler.start();
ContextBuilderOptions options = new ContextBuilderOptions();
ContextBuilder builder = new ContextBuilder(
resourceProvider, sdkManager, null,
options: options);
if (packagesFile != null) {
options.defaultPackageFilePath = packagesFile;
}
builder.analysisDriverScheduler = scheduler;
builder.byteStore = new MemoryByteStore();
builder.fileContentOverlay = new FileContentOverlay();
builder.performanceLog = performanceLog;
List<AnalysisContext> contextList = <AnalysisContext>[];
for (ContextRoot root in roots) {
old.ContextRoot contextRoot = new old.ContextRoot(
root.root.path, root.excludedPaths.toList(),
pathContext: resourceProvider.pathContext);
AnalysisDriver driver = builder.buildDriver(contextRoot);
DriverBasedAnalysisContext context =
new DriverBasedAnalysisContext(resourceProvider, root, driver);
contextList.add(context);
}
return contextList;
}
@override
List<ContextRoot> locateRoots(
{@required List<String> includedPaths,
List<String> excludedPaths,
String optionsFile,
String packagesFile}) {
//
// Compute the list of folders and files that are to be included.
//
List<Folder> includedFolders = <Folder>[];
List<File> includedFiles = <File>[];
_resourcesFromPaths(
includedPaths ?? const <String>[], includedFolders, includedFiles);
//
// Compute the list of folders and files that are to be excluded.
//
List<Folder> excludedFolders = <Folder>[];
List<File> excludedFiles = <File>[];
_resourcesFromPaths(
excludedPaths ?? const <String>[], excludedFolders, excludedFiles);
//
// Use the excluded folders and files to filter the included folders and
// files.
//
includedFolders = includedFolders
.where((Folder includedFolder) =>
!_containedInAny(excludedFolders, includedFolder) &&
!_containedInAny(includedFolders, includedFolder))
.toList();
includedFiles = includedFiles
.where((File includedFile) =>
!_containedInAny(excludedFolders, includedFile) &&
!excludedFiles.contains(includedFile) &&
!_containedInAny(includedFolders, includedFile))
.toList();
//
// We now have a list of all of the files and folders that need to be
// analyzed. For each, walk the directory structure and figure out where to
// create context roots.
//
File defaultOptionsFile;
if (optionsFile != null) {
defaultOptionsFile = resourceProvider.getFile(optionsFile);
if (!defaultOptionsFile.exists) {
defaultOptionsFile = null;
}
}
File defaultPackagesFile;
if (packagesFile != null) {
defaultPackagesFile = resourceProvider.getFile(packagesFile);
if (!defaultPackagesFile.exists) {
defaultPackagesFile = null;
}
}
List<ContextRoot> roots = <ContextRoot>[];
for (Folder folder in includedFolders) {
ContextRootImpl root = new ContextRootImpl(resourceProvider, folder);
root.packagesFile = defaultPackagesFile ?? _findPackagesFile(folder);
root.optionsFile = defaultOptionsFile ?? _findOptionsFile(folder);
root.included.add(folder);
roots.add(root);
_createContextRootsIn(roots, folder, excludedFolders, root,
_getExcludedFiles(root), defaultOptionsFile, defaultPackagesFile);
}
Map<Folder, ContextRoot> rootMap = <Folder, ContextRoot>{};
for (File file in includedFiles) {
Folder parent = file.parent;
ContextRoot root = rootMap.putIfAbsent(parent, () {
ContextRootImpl root = new ContextRootImpl(resourceProvider, parent);
root.packagesFile = defaultPackagesFile ?? _findPackagesFile(parent);
root.optionsFile = defaultOptionsFile ?? _findOptionsFile(parent);
roots.add(root);
return root;
});
root.included.add(file);
}
return roots;
}
/**
* Return `true` if the given [resource] is contained in one or more of the
* given [folders].
*/
bool _containedInAny(Iterable<Folder> folders, Resource resource) =>
folders.any((Folder folder) => folder.contains(resource.path));
/**
* If the given [folder] should be the root of a new analysis context, then
* create a new context root for it and add it to the list of context [roots].
* The [containingRoot] is the context root from an enclosing directory and is
* used to inherit configuration information that isn't overridden.
*
* If either the [optionsFile] or [packagesFile] is non-`null` then the given
* file will be used even if there is a local version of the file.
*
* For each directory within the given [folder] that is neither in the list of
* [excludedFolders] nor excluded by the [excludedFilePatterns], recursively
* search for nested context roots.
*/
void _createContextRoots(
List<ContextRoot> roots,
Folder folder,
List<Folder> excludedFolders,
ContextRoot containingRoot,
List<Glob> excludedFilePatterns,
File optionsFile,
File packagesFile) {
//
// If the options and packages files are allowed to be locally specified,
// then look to see whether they are.
//
File localOptionsFile;
if (optionsFile == null) {
localOptionsFile = _getOptionsFile(folder);
}
File localPackagesFile;
if (packagesFile == null) {
localPackagesFile = _getPackagesFile(folder);
}
//
// Create a context root for the given [folder] if at least one of the
// options and packages file is locally specified.
//
if (localPackagesFile != null || localOptionsFile != null) {
if (optionsFile != null) {
localOptionsFile = optionsFile;
}
if (packagesFile != null) {
localPackagesFile = packagesFile;
}
ContextRootImpl root = new ContextRootImpl(resourceProvider, folder);
root.packagesFile = localPackagesFile ?? containingRoot.packagesFile;
root.optionsFile = localOptionsFile ?? containingRoot.optionsFile;
root.included.add(folder);
containingRoot.excluded.add(folder);
roots.add(root);
containingRoot = root;
excludedFilePatterns = _getExcludedFiles(root);
}
_createContextRootsIn(roots, folder, excludedFolders, containingRoot,
excludedFilePatterns, optionsFile, packagesFile);
}
/**
* For each directory within the given [folder] that is neither in the list of
* [excludedFolders] nor excluded by the [excludedFilePatterns], recursively
* search for nested context roots and add them to the list of [roots].
*
* If either the [optionsFile] or [packagesFile] is non-`null` then the given
* file will be used even if there is a local version of the file.
*/
void _createContextRootsIn(
List<ContextRoot> roots,
Folder folder,
List<Folder> excludedFolders,
ContextRoot containingRoot,
List<Glob> excludedFilePatterns,
File optionsFile,
File packagesFile) {
bool isExcluded(Folder folder) {
if (excludedFolders.contains(folder) ||
folder.shortName.startsWith('.')) {
return true;
}
for (Glob pattern in excludedFilePatterns) {
if (pattern.matches(folder.path)) {
return true;
}
}
return false;
}
//
// Check each of the subdirectories to see whether a context root needs to
// be added for it.
//
try {
for (Resource child in folder.getChildren()) {
if (child is Folder) {
if (isExcluded(child)) {
containingRoot.excluded.add(child);
} else {
_createContextRoots(roots, child, excludedFolders, containingRoot,
excludedFilePatterns, optionsFile, packagesFile);
}
}
}
} on FileSystemException {
// The directory either doesn't exist or cannot be read. Either way, there
// are no subdirectories that need to be added.
}
}
/**
* Return the analysis options file to be used to analyze files in the given
* [folder], or `null` if there is no analysis options file in the given
* folder or any parent folder.
*/
File _findOptionsFile(Folder folder) {
while (folder != null) {
File packagesFile = _getOptionsFile(folder);
if (packagesFile != null) {
return packagesFile;
}
folder = folder.parent;
}
return null;
}
/**
* Return the packages file to be used to analyze files in the given [folder],
* or `null` if there is no packages file in the given folder or any parent
* folder.
*/
File _findPackagesFile(Folder folder) {
while (folder != null) {
File packagesFile = _getPackagesFile(folder);
if (packagesFile != null) {
return packagesFile;
}
folder = folder.parent;
}
return null;
}
/// Return a list containing the glob patterns used to exclude files from the
/// given context [root]. The patterns are extracted from the analysis options
/// file associated with the context root. The list will be empty if there are
/// no exclusion patterns in the options file, or if there is no options file
/// associated with the context root.
List<Glob> _getExcludedFiles(ContextRootImpl root) {
List<Glob> patterns = [];
File optionsFile = root.optionsFile;
if (optionsFile != null) {
try {
String content = optionsFile.readAsStringSync();
YamlNode doc = loadYamlNode(content);
if (doc is YamlMap) {
YamlNode analyzerOptions = getValue(doc, AnalyzerOptions.analyzer);
if (analyzerOptions is YamlMap) {
YamlNode excludeOptions =
getValue(analyzerOptions, AnalyzerOptions.exclude);
if (excludeOptions is YamlList) {
List<String> excludeList = toStringList(excludeOptions);
if (excludeList != null) {
for (String excludedPath in excludeList) {
Context context = resourceProvider.pathContext;
if (context.isRelative(excludedPath)) {
excludedPath =
context.join(optionsFile.parent.path, excludedPath);
}
patterns.add(new Glob(excludedPath, context: context));
}
}
}
}
}
} catch (exception) {
// If we can't read and parse the analysis options file, then there
// aren't any excluded files that need to be read.
}
}
return patterns;
}
/**
* If the given [directory] contains a file with the given [name], then return
* the file. Otherwise, return `null`.
*/
File _getFile(Folder directory, String name) {
Resource resource = directory.getChild(name);
if (resource is File && resource.exists) {
return resource;
}
return null;
}
/**
* Return the analysis options file in the given [folder], or `null` if the
* folder does not contain an analysis options file.
*/
File _getOptionsFile(Folder folder) =>
_getFile(folder, ANALYSIS_OPTIONS_NAME) ??
_getFile(folder, OLD_ANALYSIS_OPTIONS_NAME);
/**
* Return the packages file in the given [folder], or `null` if the folder
* does not contain a packages file.
*/
File _getPackagesFile(Folder folder) => _getFile(folder, PACKAGES_FILE_NAME);
/**
* Add to the given lists of [folders] and [files] all of the resources in the
* given list of [paths] that exist and are not contained within one of the
* folders.
*/
void _resourcesFromPaths(
List<String> paths, List<Folder> folders, List<File> files) {
for (String path in _uniqueSortedPaths(paths)) {
Resource resource = resourceProvider.getResource(path);
if (resource.exists && !_containedInAny(folders, resource)) {
if (resource is Folder) {
folders.add(resource);
} else if (resource is File) {
files.add(resource);
} else {
// Internal error: unhandled kind of resource.
}
}
}
}
/**
* Return a list of paths that contains all of the unique elements from the
* given list of [paths], sorted such that shorter paths are first.
*/
List<String> _uniqueSortedPaths(List<String> paths) {
Set<String> uniquePaths = new HashSet<String>.from(paths);
List<String> sortedPaths = uniquePaths.toList();
sortedPaths.sort((a, b) => a.length - b.length);
return sortedPaths;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/file_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:convert';
import 'dart:typed_data';
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/standard_ast_factory.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/byte_store.dart';
import 'package:analyzer/src/dart/analysis/defined_names.dart';
import 'package:analyzer/src/dart/analysis/library_graph.dart';
import 'package:analyzer/src/dart/analysis/performance_logger.dart';
import 'package:analyzer/src/dart/analysis/referenced_names.dart';
import 'package:analyzer/src/dart/analysis/unlinked_api_signature.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
import 'package:analyzer/src/source/source_resource.dart';
import 'package:analyzer/src/summary/api_signature.dart';
import 'package:analyzer/src/summary/format.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary/name_filter.dart';
import 'package:analyzer/src/summary/package_bundle_reader.dart';
import 'package:analyzer/src/summary2/informative_data.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:front_end/src/fasta/scanner/token.dart';
import 'package:meta/meta.dart';
var counterFileStateRefresh = 0;
var counterUnlinkedLinkedBytes = 0;
var timerFileStateRefresh = Stopwatch();
/**
* [FileContentOverlay] is used to temporary override content of files.
*/
class FileContentOverlay {
final _map = <String, String>{};
/**
* Return the paths currently being overridden.
*/
Iterable<String> get paths => _map.keys;
/**
* Return the content of the file with the given [path], or `null` the
* overlay does not override the content of the file.
*
* The [path] must be absolute and normalized.
*/
String operator [](String path) => _map[path];
/**
* Return the new [content] of the file with the given [path].
*
* The [path] must be absolute and normalized.
*/
void operator []=(String path, String content) {
if (content == null) {
_map.remove(path);
} else {
_map[path] = content;
}
}
}
/**
* Information about a file being analyzed, explicitly or implicitly.
*
* It provides a consistent view on its properties.
*
* The properties are not guaranteed to represent the most recent state
* of the file system. To update the file to the most recent state, [refresh]
* should be called.
*/
class FileState {
final FileSystemState _fsState;
/**
* The absolute path of the file.
*/
final String path;
/**
* The absolute URI of the file.
*/
final Uri uri;
/**
* The [Source] of the file with the [uri].
*/
final Source source;
/**
* Return `true` if this file is a stub created for a file in the provided
* external summary store. The values of most properties are not the same
* as they would be if the file were actually read from the file system.
* The value of the property [uri] is correct.
*/
final bool isInExternalSummaries;
bool _exists;
String _content;
String _contentHash;
LineInfo _lineInfo;
Set<String> _definedClassMemberNames;
Set<String> _definedTopLevelNames;
Set<String> _referencedNames;
String _unlinkedKey;
AnalysisDriverUnlinkedUnit _driverUnlinkedUnit;
UnlinkedUnit _unlinked;
List<int> _apiSignature;
UnlinkedUnit2 _unlinked2;
List<FileState> _importedFiles;
List<FileState> _exportedFiles;
List<FileState> _partedFiles;
List<FileState> _libraryFiles;
List<NameFilter> _exportFilters;
Set<FileState> _directReferencedFiles;
Set<FileState> _directReferencedLibraries;
LibraryCycle _libraryCycle;
String _transitiveSignature;
String _transitiveSignatureLinked;
/**
* The flag that shows whether the file has an error or warning that
* might be fixed by a change to another file.
*/
bool hasErrorOrWarning = false;
FileState._(this._fsState, this.path, this.uri, this.source)
: isInExternalSummaries = false;
FileState._external(this._fsState, this.uri)
: isInExternalSummaries = true,
path = null,
source = null,
_exists = true {
_apiSignature = new Uint8List(16);
_libraryCycle = new LibraryCycle.external();
}
/**
* The unlinked API signature of the file.
*/
List<int> get apiSignature => _apiSignature;
/**
* The content of the file.
*/
String get content => _content;
/**
* The MD5 hash of the [content].
*/
String get contentHash => _contentHash;
/**
* The class member names defined by the file.
*/
Set<String> get definedClassMemberNames {
return _definedClassMemberNames ??=
_driverUnlinkedUnit.definedClassMemberNames.toSet();
}
/**
* The top-level names defined by the file.
*/
Set<String> get definedTopLevelNames {
return _definedTopLevelNames ??=
_driverUnlinkedUnit.definedTopLevelNames.toSet();
}
/**
* Return the set of all directly referenced files - imported, exported or
* parted.
*/
Set<FileState> get directReferencedFiles => _directReferencedFiles;
/**
* Return the set of all directly referenced libraries - imported or exported.
*/
Set<FileState> get directReferencedLibraries => _directReferencedLibraries;
/**
* Return `true` if the file exists.
*/
bool get exists => _exists;
/**
* The list of files this file exports.
*/
List<FileState> get exportedFiles => _exportedFiles;
@override
int get hashCode => uri.hashCode;
/**
* The list of files this file imports.
*/
List<FileState> get importedFiles => _importedFiles;
LibraryCycle get internal_libraryCycle => _libraryCycle;
/**
* Return `true` if the file is a stub created for a library in the provided
* external summary store.
*/
bool get isExternalLibrary {
return _fsState.externalSummaries != null &&
_fsState.externalSummaries.hasLinkedLibrary(uriStr);
}
/**
* Return `true` if the file does not have a `library` directive, and has a
* `part of` directive, so is probably a part.
*/
bool get isPart {
if (_fsState.externalSummaries != null &&
_fsState.externalSummaries.hasUnlinkedUnit(uriStr)) {
return _fsState.externalSummaries.isPartUnit(uriStr);
}
if (_unlinked2 != null) {
return !_unlinked2.hasLibraryDirective && _unlinked2.hasPartOfDirective;
}
return _unlinked.libraryNameOffset == 0 && _unlinked.isPartOf;
}
/**
* Return `true` if the file is the "unresolved" file, which does not have
* neither a valid URI, nor a path.
*/
bool get isUnresolved => uri == null;
/**
* If the file [isPart], return a currently know library the file is a part
* of. Return `null` if a library is not known, for example because we have
* not processed a library file yet.
*/
FileState get library {
List<FileState> libraries = _fsState._partToLibraries[this];
if (libraries == null || libraries.isEmpty) {
return null;
} else {
return libraries.first;
}
}
/// Return the [LibraryCycle] this file belongs to, even if it consists of
/// just this file. If the library cycle is not known yet, compute it.
LibraryCycle get libraryCycle {
if (isPart) {
var library = this.library;
if (library != null) {
return library.libraryCycle;
}
}
if (_libraryCycle == null) {
computeLibraryCycle(_fsState._linkedSalt, this);
}
return _libraryCycle;
}
/**
* The list of files files that this library consists of, i.e. this library
* file itself and its [partedFiles].
*/
List<FileState> get libraryFiles => _libraryFiles;
/**
* Return information about line in the file.
*/
LineInfo get lineInfo => _lineInfo;
/**
* The list of files this library file references as parts.
*/
List<FileState> get partedFiles => _partedFiles;
/**
* The external names referenced by the file.
*/
Set<String> get referencedNames {
return _referencedNames ??= _driverUnlinkedUnit.referencedNames.toSet();
}
@visibleForTesting
FileStateTestView get test => new FileStateTestView(this);
/**
* Return the set of transitive files - the file itself and all of the
* directly or indirectly referenced files.
*/
Set<FileState> get transitiveFiles {
var transitiveFiles = new Set<FileState>();
void appendReferenced(FileState file) {
if (transitiveFiles.add(file)) {
file._directReferencedFiles?.forEach(appendReferenced);
}
}
appendReferenced(this);
return transitiveFiles;
}
/**
* Return the signature of the file, based on API signatures of the
* transitive closure of imported / exported files.
*/
String get transitiveSignature {
this.libraryCycle; // sets _transitiveSignature
return _transitiveSignature;
}
/**
* The value `transitiveSignature.linked` is used often, so we cache it.
*/
String get transitiveSignatureLinked {
return _transitiveSignatureLinked ??= '$transitiveSignature.linked';
}
/**
* The [UnlinkedUnit] of the file.
*/
UnlinkedUnit get unlinked => _unlinked;
/**
* The [UnlinkedUnit2] of the file.
*/
UnlinkedUnit2 get unlinked2 => _unlinked2;
/**
* Return the [uri] string.
*/
String get uriStr => uri.toString();
@override
bool operator ==(Object other) {
return other is FileState && other.uri == uri;
}
void internal_setLibraryCycle(LibraryCycle cycle, String signature) {
if (cycle == null) {
_libraryCycle = null;
_transitiveSignature = null;
_transitiveSignatureLinked = null;
} else {
_libraryCycle = cycle;
_transitiveSignature = signature;
}
}
/**
* Return a new parsed unresolved [CompilationUnit].
*
* If an exception happens during parsing, an empty unit is returned.
*/
CompilationUnit parse([AnalysisErrorListener errorListener]) {
errorListener ??= AnalysisErrorListener.NULL_LISTENER;
try {
return PerformanceStatistics.parse.makeCurrentWhile(() {
return _parse(errorListener);
});
} catch (_) {
AnalysisOptionsImpl analysisOptions = _fsState._analysisOptions;
return _createEmptyCompilationUnit(analysisOptions.contextFeatures);
}
}
/**
* Read the file content and ensure that all of the file properties are
* consistent with the read content, including API signature.
*
* If [allowCached] is `true`, don't read the content of the file if it
* is already cached (in another [FileSystemState], because otherwise we
* would not create this new instance of [FileState] and refresh it).
*
* Return `true` if the API signature changed since the last refresh.
*/
bool refresh({bool allowCached: false}) {
counterFileStateRefresh++;
var timerWasRunning = timerFileStateRefresh.isRunning;
if (!timerWasRunning) {
timerFileStateRefresh.start();
}
_invalidateCurrentUnresolvedData();
{
var rawFileState = _fsState._fileContentCache.get(path, allowCached);
_content = rawFileState.content;
_exists = rawFileState.exists;
_contentHash = rawFileState.contentHash;
}
// Prepare the unlinked bundle key.
List<int> contentSignature;
{
var signature = new ApiSignature();
signature.addUint32List(_fsState._unlinkedSalt);
signature.addString(_contentHash);
signature.addBool(_exists);
contentSignature = signature.toByteList();
_unlinkedKey = '${hex.encode(contentSignature)}.unlinked2';
}
// Prepare bytes of the unlinked bundle - existing or new.
List<int> bytes;
{
bytes = _fsState._byteStore.get(_unlinkedKey);
if (bytes == null || bytes.isEmpty) {
CompilationUnit unit = parse();
_fsState._logger.run('Create unlinked for $path', () {
var unlinkedUnit = serializeAstUnlinked2(unit);
var definedNames = computeDefinedNames(unit);
var referencedNames = computeReferencedNames(unit).toList();
var subtypedNames = computeSubtypedNames(unit).toList();
bytes = new AnalysisDriverUnlinkedUnitBuilder(
unit2: unlinkedUnit,
definedTopLevelNames: definedNames.topLevelNames.toList(),
definedClassMemberNames: definedNames.classMemberNames.toList(),
referencedNames: referencedNames,
subtypedNames: subtypedNames,
).toBuffer();
_fsState._byteStore.put(_unlinkedKey, bytes);
});
}
}
// Read the unlinked bundle.
_driverUnlinkedUnit = new AnalysisDriverUnlinkedUnit.fromBuffer(bytes);
_unlinked2 = _driverUnlinkedUnit.unit2;
_lineInfo = new LineInfo(_unlinked2.lineStarts);
// Prepare API signature.
var newApiSignature = new Uint8List.fromList(_unlinked2.apiSignature);
bool apiSignatureChanged = _apiSignature != null &&
!_equalByteLists(_apiSignature, newApiSignature);
_apiSignature = newApiSignature;
// The API signature changed.
// Flush affected library cycles.
// Flush exported top-level declarations of all files.
if (apiSignatureChanged) {
_libraryCycle?.invalidate();
// If this is a part, invalidate the libraries.
var libraries = _fsState._partToLibraries[this];
if (libraries != null) {
for (var library in libraries) {
library.libraryCycle?.invalidate();
}
}
}
// This file is potentially not a library for its previous parts anymore.
if (_partedFiles != null) {
for (FileState part in _partedFiles) {
_fsState._partToLibraries[part]?.remove(this);
}
}
// Build the graph.
_importedFiles = <FileState>[];
_exportedFiles = <FileState>[];
_partedFiles = <FileState>[];
_exportFilters = <NameFilter>[];
for (var uri in _unlinked2.imports) {
var file = _fileForRelativeUri(uri);
_importedFiles.add(file);
}
for (var uri in _unlinked2.exports) {
var file = _fileForRelativeUri(uri);
_exportedFiles.add(file);
// TODO(scheglov) implement
_exportFilters.add(NameFilter.identity);
}
for (var uri in _unlinked2.parts) {
var file = _fileForRelativeUri(uri);
_partedFiles.add(file);
_fsState._partToLibraries
.putIfAbsent(file, () => <FileState>[])
.add(this);
}
_libraryFiles = [this]..addAll(_partedFiles);
// Compute referenced files.
_directReferencedFiles = new Set<FileState>()
..addAll(_importedFiles)
..addAll(_exportedFiles)
..addAll(_partedFiles);
_directReferencedLibraries = Set<FileState>()
..addAll(_importedFiles)
..addAll(_exportedFiles);
// Update mapping from subtyped names to files.
for (var name in _driverUnlinkedUnit.subtypedNames) {
var files = _fsState._subtypedNameToFiles[name];
if (files == null) {
files = new Set<FileState>();
_fsState._subtypedNameToFiles[name] = files;
}
files.add(this);
}
if (!timerWasRunning) {
timerFileStateRefresh.stop();
}
// Return whether the API signature changed.
return apiSignatureChanged;
}
@override
String toString() => path ?? '<unresolved>';
CompilationUnit _createEmptyCompilationUnit(FeatureSet featureSet) {
var token = new Token.eof(0);
return astFactory.compilationUnit(
beginToken: token, endToken: token, featureSet: featureSet)
..lineInfo = new LineInfo(const <int>[0]);
}
/**
* Return the [FileState] for the given [relativeUri], maybe "unresolved"
* file if the URI cannot be parsed, cannot correspond any file, etc.
*/
FileState _fileForRelativeUri(String relativeUri) {
if (relativeUri.isEmpty) {
return _fsState.unresolvedFile;
}
Uri absoluteUri;
try {
absoluteUri = resolveRelativeUri(uri, Uri.parse(relativeUri));
} on FormatException {
return _fsState.unresolvedFile;
}
return _fsState.getFileForUri(absoluteUri);
}
/**
* Invalidate any data that depends on the current unlinked data of the file,
* because [refresh] is going to recompute the unlinked data.
*/
void _invalidateCurrentUnresolvedData() {
// Invalidate unlinked information.
_definedTopLevelNames = null;
_definedClassMemberNames = null;
_referencedNames = null;
if (_driverUnlinkedUnit != null) {
for (var name in _driverUnlinkedUnit.subtypedNames) {
var files = _fsState._subtypedNameToFiles[name];
files?.remove(this);
}
}
}
CompilationUnit _parse(AnalysisErrorListener errorListener) {
AnalysisOptionsImpl analysisOptions = _fsState._analysisOptions;
FeatureSet featureSet = analysisOptions.contextFeatures;
if (source == null) {
return _createEmptyCompilationUnit(featureSet);
}
CharSequenceReader reader = new CharSequenceReader(content);
Scanner scanner = new Scanner(source, reader, errorListener)
..configureFeatures(featureSet);
Token token = PerformanceStatistics.scan.makeCurrentWhile(() {
return scanner.tokenize(reportScannerErrors: false);
});
LineInfo lineInfo = new LineInfo(scanner.lineStarts);
bool useFasta = analysisOptions.useFastaParser;
// Pass the feature set from the scanner to the parser
// because the scanner may have detected a language version comment
// and downgraded the feature set it holds.
Parser parser = new Parser(source, errorListener,
featureSet: scanner.featureSet, useFasta: useFasta);
parser.enableOptionalNewAndConst = true;
CompilationUnit unit = parser.parseCompilationUnit(token);
unit.lineInfo = lineInfo;
// StringToken uses a static instance of StringCanonicalizer, so we need
// to clear it explicitly once we are done using it for this file.
StringToken.canonicalizer.clear();
return unit;
}
static UnlinkedUnit2Builder serializeAstUnlinked2(CompilationUnit unit) {
var exports = <String>[];
var imports = <String>[];
var parts = <String>[];
var hasDartCoreImport = false;
var hasLibraryDirective = false;
var hasPartOfDirective = false;
for (var directive in unit.directives) {
if (directive is ExportDirective) {
var uriStr = directive.uri.stringValue;
exports.add(uriStr ?? '');
} else if (directive is ImportDirective) {
var uriStr = directive.uri.stringValue;
imports.add(uriStr ?? '');
if (uriStr == 'dart:core') {
hasDartCoreImport = true;
}
} else if (directive is LibraryDirective) {
hasLibraryDirective = true;
} else if (directive is PartDirective) {
var uriStr = directive.uri.stringValue;
parts.add(uriStr ?? '');
} else if (directive is PartOfDirective) {
hasPartOfDirective = true;
}
}
if (!hasDartCoreImport) {
imports.add('dart:core');
}
var informativeData = createInformativeData(unit);
return UnlinkedUnit2Builder(
apiSignature: computeUnlinkedApiSignature(unit),
exports: exports,
imports: imports,
parts: parts,
hasLibraryDirective: hasLibraryDirective,
hasPartOfDirective: hasPartOfDirective,
lineStarts: unit.lineInfo.lineStarts,
informativeData: informativeData,
);
}
/**
* Return `true` if the given byte lists are equal.
*/
static bool _equalByteLists(List<int> a, List<int> b) {
if (a == null) {
return b == null;
} else if (b == null) {
return false;
}
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
}
@visibleForTesting
class FileStateTestView {
final FileState file;
FileStateTestView(this.file);
String get unlinkedKey => file._unlinkedKey;
}
/**
* Information about known file system state.
*/
class FileSystemState {
final PerformanceLog _logger;
final ResourceProvider _resourceProvider;
final String contextName;
final ByteStore _byteStore;
final FileContentOverlay _contentOverlay;
final SourceFactory _sourceFactory;
final AnalysisOptions _analysisOptions;
final Uint32List _unlinkedSalt;
final Uint32List _linkedSalt;
/**
* The optional store with externally provided unlinked and corresponding
* linked summaries. These summaries are always added to the store for any
* file analysis.
*
* While walking the file graph, when we reach a file that exists in the
* external store, we add a stub [FileState], but don't attempt to read its
* content, or its unlinked unit, or imported libraries, etc.
*/
final SummaryDataStore externalSummaries;
/**
* Mapping from a URI to the corresponding [FileState].
*/
final Map<Uri, FileState> _uriToFile = {};
/**
* All known file paths.
*/
final Set<String> knownFilePaths = new Set<String>();
/**
* All known files.
*/
final List<FileState> knownFiles = [];
/**
* Mapping from a path to the flag whether there is a URI for the path.
*/
final Map<String, bool> _hasUriForPath = {};
/**
* Mapping from a path to the corresponding [FileState]s, canonical or not.
*/
final Map<String, List<FileState>> _pathToFiles = {};
/**
* Mapping from a path to the corresponding canonical [FileState].
*/
final Map<String, FileState> _pathToCanonicalFile = {};
/**
* Mapping from a part to the libraries it is a part of.
*/
final Map<FileState, List<FileState>> _partToLibraries = {};
/**
* The map of subtyped names to files where these names are subtyped.
*/
final Map<String, Set<FileState>> _subtypedNameToFiles = {};
/**
* The value of this field is incremented when the set of files is updated.
*/
int fileStamp = 0;
/**
* The [FileState] instance that correspond to an unresolved URI.
*/
FileState _unresolvedFile;
/**
* The cache of content of files, possibly shared with other file system
* states with the same resource provider and the content overlay.
*/
_FileContentCache _fileContentCache;
FileSystemStateTestView _testView;
FileSystemState(
this._logger,
this._byteStore,
this._contentOverlay,
this._resourceProvider,
this.contextName,
this._sourceFactory,
this._analysisOptions,
this._unlinkedSalt,
this._linkedSalt, {
this.externalSummaries,
}) {
_fileContentCache = _FileContentCache.getInstance(
_resourceProvider,
_contentOverlay,
);
_testView = new FileSystemStateTestView(this);
}
@visibleForTesting
FileSystemStateTestView get test => _testView;
/**
* Return the [FileState] instance that correspond to an unresolved URI.
*/
FileState get unresolvedFile {
if (_unresolvedFile == null) {
_unresolvedFile = new FileState._(this, null, null, null);
_unresolvedFile.refresh();
}
return _unresolvedFile;
}
/**
* Return the canonical [FileState] for the given absolute [path]. The
* returned file has the last known state since if was last refreshed.
*
* Here "canonical" means that if the [path] is in a package `lib` then the
* returned file will have the `package:` style URI.
*/
FileState getFileForPath(String path) {
FileState file = _pathToCanonicalFile[path];
if (file == null) {
File resource = _resourceProvider.getFile(path);
Source fileSource = resource.createSource();
Uri uri = _sourceFactory.restoreUri(fileSource);
// Try to get the existing instance.
file = _uriToFile[uri];
// If we have a file, call it the canonical one and return it.
if (file != null) {
_pathToCanonicalFile[path] = file;
return file;
}
// Create a new file.
FileSource uriSource = new FileSource(resource, uri);
file = new FileState._(this, path, uri, uriSource);
_uriToFile[uri] = file;
_addFileWithPath(path, file);
_pathToCanonicalFile[path] = file;
file.refresh(allowCached: true);
}
return file;
}
/**
* Return the [FileState] for the given absolute [uri]. May return the
* "unresolved" file if the [uri] is invalid, e.g. a `package:` URI without
* a package name. The returned file has the last known state since if was
* last refreshed.
*/
FileState getFileForUri(Uri uri) {
FileState file = _uriToFile[uri];
if (file == null) {
// If the external store has this URI, create a stub file for it.
// We are given all required unlinked and linked summaries for it.
if (externalSummaries != null) {
String uriStr = uri.toString();
if (externalSummaries.hasLinkedLibrary(uriStr)) {
file = new FileState._external(this, uri);
_uriToFile[uri] = file;
return file;
}
}
Source uriSource = _sourceFactory.resolveUri(null, uri.toString());
// If the URI cannot be resolved, for example because the factory
// does not understand the scheme, return the unresolved file instance.
if (uriSource == null) {
_uriToFile[uri] = unresolvedFile;
return unresolvedFile;
}
String path = uriSource.fullName;
File resource = _resourceProvider.getFile(path);
FileSource source = new FileSource(resource, uri);
file = new FileState._(this, path, uri, source);
_uriToFile[uri] = file;
_addFileWithPath(path, file);
file.refresh(allowCached: true);
}
return file;
}
/**
* Return the list of all [FileState]s corresponding to the given [path]. The
* list has at least one item, and the first item is the canonical file.
*/
List<FileState> getFilesForPath(String path) {
FileState canonicalFile = getFileForPath(path);
List<FileState> allFiles = _pathToFiles[path].toList();
if (allFiles.length == 1) {
return allFiles;
}
return allFiles
..remove(canonicalFile)
..insert(0, canonicalFile);
}
/**
* Return files where the given [name] is subtyped, i.e. used in `extends`,
* `with` or `implements` clauses.
*/
Set<FileState> getFilesSubtypingName(String name) {
return _subtypedNameToFiles[name];
}
/**
* Return `true` if there is a URI that can be resolved to the [path].
*
* When a file exists, but for the URI that corresponds to the file is
* resolved to another file, e.g. a generated one in Bazel, Gn, etc, we
* cannot analyze the original file.
*/
bool hasUri(String path) {
bool flag = _hasUriForPath[path];
if (flag == null) {
File resource = _resourceProvider.getFile(path);
Source fileSource = resource.createSource();
Uri uri = _sourceFactory.restoreUri(fileSource);
Source uriSource = _sourceFactory.forUri2(uri);
flag = uriSource?.fullName == path;
_hasUriForPath[path] = flag;
}
return flag;
}
/**
* The file with the given [path] might have changed, so ensure that it is
* read the next time it is refreshed.
*/
void markFileForReading(String path) {
_fileContentCache.remove(path);
}
/**
* Remove the file with the given [path].
*/
void removeFile(String path) {
markFileForReading(path);
_clearFiles();
}
/**
* Reset URI resolution, and forget all files. So, the next time any file is
* requested, it will be read, and its whole (potentially different) graph
* will be built.
*/
void resetUriResolution() {
_sourceFactory.clearCache();
_fileContentCache.clear();
_clearFiles();
}
void _addFileWithPath(String path, FileState file) {
var files = _pathToFiles[path];
if (files == null) {
knownFilePaths.add(path);
knownFiles.add(file);
files = <FileState>[];
_pathToFiles[path] = files;
fileStamp++;
}
files.add(file);
}
/// Clear all [FileState] data - all maps from path or URI, etc.
void _clearFiles() {
_uriToFile.clear();
knownFilePaths.clear();
knownFiles.clear();
_pathToFiles.clear();
_pathToCanonicalFile.clear();
_partToLibraries.clear();
_subtypedNameToFiles.clear();
}
}
@visibleForTesting
class FileSystemStateTestView {
final FileSystemState state;
FileSystemStateTestView(this.state);
Set<FileState> get filesWithoutLibraryCycle {
return state._uriToFile.values
.where((f) => f._libraryCycle == null)
.toSet();
}
}
/**
* Information about the content of a file.
*/
class _FileContent {
final String path;
final bool exists;
final String content;
final String contentHash;
_FileContent(this.path, this.exists, this.content, this.contentHash);
}
/**
* The cache of information about content of files.
*/
class _FileContentCache {
/**
* Weak map of cache instances.
*
* Outer key is a [FileContentOverlay].
* Inner key is a [ResourceProvider].
*/
static final _instances = new Expando<Expando<_FileContentCache>>();
/**
* Weak map of cache instances.
*
* Key is a [ResourceProvider].
*/
static final _instances2 = new Expando<_FileContentCache>();
final ResourceProvider _resourceProvider;
final FileContentOverlay _contentOverlay;
final Map<String, _FileContent> _pathToFile = {};
_FileContentCache(this._resourceProvider, this._contentOverlay);
void clear() {
_pathToFile.clear();
}
/**
* Return the content of the file with the given [path].
*
* If [allowCached] is `true`, and the file is in the cache, return the
* cached data. Otherwise read the file, compute and cache the data.
*/
_FileContent get(String path, bool allowCached) {
var file = allowCached ? _pathToFile[path] : null;
if (file == null) {
String content;
bool exists;
try {
if (_contentOverlay != null) {
content = _contentOverlay[path];
}
content ??= _resourceProvider.getFile(path).readAsStringSync();
exists = true;
} catch (_) {
content = '';
exists = false;
}
List<int> contentBytes = utf8.encode(content);
List<int> contentHashBytes = md5.convert(contentBytes).bytes;
String contentHash = hex.encode(contentHashBytes);
file = new _FileContent(path, exists, content, contentHash);
_pathToFile[path] = file;
}
return file;
}
/**
* Remove the file with the given [path] from the cache.
*/
void remove(String path) {
_pathToFile.remove(path);
}
static _FileContentCache getInstance(
ResourceProvider resourceProvider, FileContentOverlay contentOverlay) {
Expando<_FileContentCache> providerToInstance;
if (contentOverlay != null) {
providerToInstance = _instances[contentOverlay];
if (providerToInstance == null) {
providerToInstance = new Expando<_FileContentCache>();
_instances[contentOverlay] = providerToInstance;
}
} else {
providerToInstance = _instances2;
}
var instance = providerToInstance[resourceProvider];
if (instance == null) {
instance = new _FileContentCache(resourceProvider, contentOverlay);
providerToInstance[resourceProvider] = instance;
}
return instance;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/fletcher16.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.
int fletcher16(List<int> data) {
int c0;
int c1;
int index = data.length;
for (c0 = c1 = 0; index >= 5802; index -= 5802) {
for (int i = 0; i < 5802; ++i) {
c0 = c0 + data[index - i - 1];
c1 = c1 + c0;
}
c0 = c0 % 255;
c1 = c1 % 255;
}
for (int i = 0; i < index; ++i) {
c0 = c0 + data[i];
c1 = c1 + c0;
}
c0 = c0 % 255;
c1 = c1 % 255;
return (c1 << 8 | c0);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/search.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/analysis/results.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/visitor.dart';
import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:analyzer/src/dart/analysis/index.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:collection/collection.dart';
Element _getEnclosingElement(CompilationUnitElement unitElement, int offset) {
var finder = new _ContainingElementFinder(offset);
unitElement.accept(finder);
Element element = finder.containingElement;
assert(element != null,
'No containing element in ${unitElement.source.fullName} at $offset');
return element;
}
/**
* Search support for an [AnalysisDriver].
*/
class Search {
final AnalysisDriver _driver;
Search(this._driver);
/**
* Returns class or mixin members with the given [name].
*/
Future<List<Element>> classMembers(String name) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
List<Element> elements = <Element>[];
void addElement(Element element) {
if (!element.isSynthetic && element.displayName == name) {
elements.add(element);
}
}
void addElements(ClassElement element) {
element.accessors.forEach(addElement);
element.fields.forEach(addElement);
element.methods.forEach(addElement);
}
List<String> files = await _driver.getFilesDefiningClassMemberName(name);
for (String file in files) {
UnitElementResult unitResult = await _driver.getUnitElement(file);
if (unitResult != null) {
unitResult.element.types.forEach(addElements);
unitResult.element.mixins.forEach(addElements);
}
}
return elements;
}
/**
* Returns references to the [element].
*/
Future<List<SearchResult>> references(
Element element, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
if (element == null) {
return const <SearchResult>[];
}
ElementKind kind = element.kind;
if (kind == ElementKind.CLASS ||
kind == ElementKind.CONSTRUCTOR ||
kind == ElementKind.EXTENSION ||
kind == ElementKind.FUNCTION_TYPE_ALIAS ||
kind == ElementKind.SETTER) {
return _searchReferences(element, searchedFiles);
} else if (kind == ElementKind.COMPILATION_UNIT) {
return _searchReferences_CompilationUnit(element);
} else if (kind == ElementKind.GETTER) {
return _searchReferences_Getter(element, searchedFiles);
} else if (kind == ElementKind.FIELD ||
kind == ElementKind.TOP_LEVEL_VARIABLE) {
return _searchReferences_Field(element, searchedFiles);
} else if (kind == ElementKind.FUNCTION || kind == ElementKind.METHOD) {
if (element.enclosingElement is ExecutableElement) {
return _searchReferences_Local(
element, (n) => n is Block, searchedFiles);
}
return _searchReferences_Function(element, searchedFiles);
} else if (kind == ElementKind.IMPORT) {
return _searchReferences_Import(element, searchedFiles);
} else if (kind == ElementKind.LABEL ||
kind == ElementKind.LOCAL_VARIABLE) {
return _searchReferences_Local(element, (n) => n is Block, searchedFiles);
} else if (kind == ElementKind.LIBRARY) {
return _searchReferences_Library(element, searchedFiles);
} else if (kind == ElementKind.PARAMETER) {
return _searchReferences_Parameter(element, searchedFiles);
} else if (kind == ElementKind.PREFIX) {
return _searchReferences_Prefix(element, searchedFiles);
} else if (kind == ElementKind.TYPE_PARAMETER) {
return _searchReferences_Local(
element, (n) => n.parent is CompilationUnit, searchedFiles);
}
return const <SearchResult>[];
}
/**
* Returns subtypes of the given [type].
*
* The [searchedFiles] are consulted to see if a file is "owned" by this
* [Search] object, so should be only searched by it to avoid duplicate
* results; and updated to take ownership if the file is not owned yet.
*/
Future<List<SearchResult>> subTypes(
ClassElement type, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
if (type == null) {
return const <SearchResult>[];
}
List<SearchResult> results = <SearchResult>[];
await _addResults(results, type, searchedFiles, const {
IndexRelationKind.IS_EXTENDED_BY: SearchResultKind.REFERENCE,
IndexRelationKind.IS_MIXED_IN_BY: SearchResultKind.REFERENCE,
IndexRelationKind.IS_IMPLEMENTED_BY: SearchResultKind.REFERENCE
});
return results;
}
/**
* Return direct [SubtypeResult]s for either the [type] or [subtype].
*/
Future<List<SubtypeResult>> subtypes(SearchedFiles searchedFiles,
{ClassElement type, SubtypeResult subtype}) async {
String name;
String id;
if (type != null) {
name = type.name;
id = '${type.librarySource.uri};${type.source.uri};$name';
} else {
name = subtype.name;
id = subtype.id;
}
await _driver.discoverAvailableFiles();
final List<SubtypeResult> results = [];
// Note, this is a defensive copy.
var files = _driver.fsState.getFilesSubtypingName(name)?.toList();
if (files != null) {
for (FileState file in files) {
if (searchedFiles.add(file.path, this)) {
AnalysisDriverUnitIndex index = await _driver.getIndex(file.path);
if (index != null) {
var request = new _IndexRequest(index);
request.addSubtypes(id, results, file);
}
}
}
}
return results;
}
/**
* Returns top-level elements with names matching the given [regExp].
*/
Future<List<Element>> topLevelElements(RegExp regExp) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
List<Element> elements = <Element>[];
void addElement(Element element) {
if (!element.isSynthetic && regExp.hasMatch(element.displayName)) {
elements.add(element);
}
}
List<FileState> knownFiles = _driver.fsState.knownFiles.toList();
for (FileState file in knownFiles) {
UnitElementResult unitResult = await _driver.getUnitElement(file.path);
if (unitResult != null) {
CompilationUnitElement unitElement = unitResult.element;
unitElement.accessors.forEach(addElement);
unitElement.enums.forEach(addElement);
unitElement.extensions.forEach(addElement);
unitElement.functions.forEach(addElement);
unitElement.functionTypeAliases.forEach(addElement);
unitElement.mixins.forEach(addElement);
unitElement.topLevelVariables.forEach(addElement);
unitElement.types.forEach(addElement);
}
}
return elements;
}
/**
* Returns unresolved references to the given [name].
*/
Future<List<SearchResult>> unresolvedMemberReferences(
String name, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
if (name == null) {
return const <SearchResult>[];
}
// Prepare the list of files that reference the name.
List<String> files = await _driver.getFilesReferencingName(name);
// Check the index of every file that references the element name.
List<SearchResult> results = [];
for (String file in files) {
if (searchedFiles.add(file, this)) {
AnalysisDriverUnitIndex index = await _driver.getIndex(file);
if (index != null) {
_IndexRequest request = new _IndexRequest(index);
var fileResults = await request.getUnresolvedMemberReferences(
name,
const {
IndexRelationKind.IS_READ_BY: SearchResultKind.READ,
IndexRelationKind.IS_WRITTEN_BY: SearchResultKind.WRITE,
IndexRelationKind.IS_READ_WRITTEN_BY: SearchResultKind.READ_WRITE,
IndexRelationKind.IS_INVOKED_BY: SearchResultKind.INVOCATION
},
() => _getUnitElement(file),
);
results.addAll(fileResults);
}
}
}
return results;
}
Future<void> _addResults(
List<SearchResult> results,
Element element,
SearchedFiles searchedFiles,
Map<IndexRelationKind, SearchResultKind> relationToResultKind) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
// Prepare the element name.
String name = element.displayName;
if (element is ConstructorElement) {
name = element.enclosingElement.displayName;
}
// Prepare the list of files that reference the element name.
List<String> files = <String>[];
String path = element.source.fullName;
if (name.startsWith('_')) {
String libraryPath = element.library.source.fullName;
if (searchedFiles.add(libraryPath, this)) {
FileState library = _driver.fsState.getFileForPath(libraryPath);
for (FileState file in library.libraryFiles) {
if (file.path == path || file.referencedNames.contains(name)) {
files.add(file.path);
}
}
}
} else {
files = await _driver.getFilesReferencingName(name);
if (!files.contains(path)) {
files.add(path);
}
}
// Check the index of every file that references the element name.
for (String file in files) {
if (searchedFiles.add(file, this)) {
await _addResultsInFile(results, element, relationToResultKind, file);
}
}
}
/**
* Add results for [element] usage in the given [file].
*/
Future<void> _addResultsInFile(
List<SearchResult> results,
Element element,
Map<IndexRelationKind, SearchResultKind> relationToResultKind,
String file) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
AnalysisDriverUnitIndex index = await _driver.getIndex(file);
if (index != null) {
_IndexRequest request = new _IndexRequest(index);
int elementId = request.findElementId(element);
if (elementId != -1) {
List<SearchResult> fileResults = await request.getRelations(
elementId, relationToResultKind, () => _getUnitElement(file));
results.addAll(fileResults);
}
}
}
Future<CompilationUnitElement> _getUnitElement(String file) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
UnitElementResult result = await _driver.getUnitElement(file);
return result?.element;
}
Future<List<SearchResult>> _searchReferences(
Element element, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
List<SearchResult> results = <SearchResult>[];
await _addResults(results, element, searchedFiles,
const {IndexRelationKind.IS_REFERENCED_BY: SearchResultKind.REFERENCE});
return results;
}
Future<List<SearchResult>> _searchReferences_CompilationUnit(
CompilationUnitElement element) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
String path = element.source.fullName;
// If the path is not known, then the file is not referenced.
if (!_driver.fsState.knownFilePaths.contains(path)) {
return const <SearchResult>[];
}
// Check every file that references the given path.
List<SearchResult> results = <SearchResult>[];
List<FileState> knownFiles = _driver.fsState.knownFiles.toList();
for (FileState file in knownFiles) {
for (FileState referencedFile in file.directReferencedFiles) {
if (referencedFile.path == path) {
await _addResultsInFile(
results,
element,
const {
IndexRelationKind.IS_REFERENCED_BY: SearchResultKind.REFERENCE
},
file.path);
}
}
}
return results;
}
Future<List<SearchResult>> _searchReferences_Field(
PropertyInducingElement field, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
List<SearchResult> results = <SearchResult>[];
PropertyAccessorElement getter = field.getter;
PropertyAccessorElement setter = field.setter;
if (!field.isSynthetic) {
await _addResults(results, field, searchedFiles, const {
IndexRelationKind.IS_WRITTEN_BY: SearchResultKind.WRITE,
IndexRelationKind.IS_REFERENCED_BY: SearchResultKind.REFERENCE
});
}
if (getter != null) {
await _addResults(results, getter, searchedFiles, const {
IndexRelationKind.IS_REFERENCED_BY: SearchResultKind.READ,
IndexRelationKind.IS_INVOKED_BY: SearchResultKind.INVOCATION
});
}
if (setter != null) {
await _addResults(results, setter, searchedFiles,
const {IndexRelationKind.IS_REFERENCED_BY: SearchResultKind.WRITE});
}
return results;
}
Future<List<SearchResult>> _searchReferences_Function(
Element element, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
if (element is Member) {
element = (element as Member).baseElement;
}
List<SearchResult> results = <SearchResult>[];
await _addResults(results, element, searchedFiles, const {
IndexRelationKind.IS_REFERENCED_BY: SearchResultKind.REFERENCE,
IndexRelationKind.IS_INVOKED_BY: SearchResultKind.INVOCATION
});
return results;
}
Future<List<SearchResult>> _searchReferences_Getter(
PropertyAccessorElement getter, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
List<SearchResult> results = <SearchResult>[];
await _addResults(results, getter, searchedFiles, const {
IndexRelationKind.IS_REFERENCED_BY: SearchResultKind.REFERENCE,
IndexRelationKind.IS_INVOKED_BY: SearchResultKind.INVOCATION
});
return results;
}
Future<List<SearchResult>> _searchReferences_Import(
ImportElement element, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
String path = element.source.fullName;
if (!searchedFiles.add(path, this)) {
return const <SearchResult>[];
}
List<SearchResult> results = <SearchResult>[];
LibraryElement libraryElement = element.library;
for (CompilationUnitElement unitElement in libraryElement.units) {
String unitPath = unitElement.source.fullName;
ResolvedUnitResult unitResult = await _driver.getResult(unitPath);
_ImportElementReferencesVisitor visitor =
new _ImportElementReferencesVisitor(element, unitElement);
unitResult.unit.accept(visitor);
results.addAll(visitor.results);
}
return results;
}
Future<List<SearchResult>> _searchReferences_Library(
LibraryElement element, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
String path = element.source.fullName;
if (!searchedFiles.add(path, this)) {
return const <SearchResult>[];
}
List<SearchResult> results = <SearchResult>[];
for (CompilationUnitElement unitElement in element.units) {
String unitPath = unitElement.source.fullName;
ResolvedUnitResult unitResult = await _driver.getResult(unitPath);
CompilationUnit unit = unitResult.unit;
for (Directive directive in unit.directives) {
if (directive is PartOfDirective && directive.element == element) {
results.add(new SearchResult._(
unit.declaredElement,
SearchResultKind.REFERENCE,
directive.libraryName.offset,
directive.libraryName.length,
true,
false));
}
}
}
return results;
}
Future<List<SearchResult>> _searchReferences_Local(Element element,
bool isRootNode(AstNode n), SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
String path = element.source.fullName;
if (!searchedFiles.add(path, this)) {
return const <SearchResult>[];
}
// Prepare the unit.
ResolvedUnitResult unitResult = await _driver.getResult(path);
CompilationUnit unit = unitResult.unit;
if (unit == null) {
return const <SearchResult>[];
}
// Prepare the node.
AstNode node = new NodeLocator(element.nameOffset).searchWithin(unit);
if (node == null) {
return const <SearchResult>[];
}
// Prepare the enclosing node.
AstNode enclosingNode = node.thisOrAncestorMatching(isRootNode);
if (enclosingNode == null) {
return const <SearchResult>[];
}
// Find the matches.
_LocalReferencesVisitor visitor =
new _LocalReferencesVisitor(element, unit.declaredElement);
enclosingNode.accept(visitor);
return visitor.results;
}
Future<List<SearchResult>> _searchReferences_Parameter(
ParameterElement parameter, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
List<SearchResult> results = <SearchResult>[];
results.addAll(await _searchReferences_Local(
parameter,
(AstNode node) {
AstNode parent = node.parent;
return parent is ClassDeclaration || parent is CompilationUnit;
},
searchedFiles,
));
if (parameter.isOptional) {
results.addAll(await _searchReferences(parameter, searchedFiles));
}
return results;
}
Future<List<SearchResult>> _searchReferences_Prefix(
PrefixElement element, SearchedFiles searchedFiles) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
String path = element.source.fullName;
if (!searchedFiles.add(path, this)) {
return const <SearchResult>[];
}
List<SearchResult> results = <SearchResult>[];
LibraryElement libraryElement = element.library;
for (CompilationUnitElement unitElement in libraryElement.units) {
String unitPath = unitElement.source.fullName;
ResolvedUnitResult unitResult = await _driver.getResult(unitPath);
_LocalReferencesVisitor visitor =
new _LocalReferencesVisitor(element, unitElement);
unitResult.unit.accept(visitor);
results.addAll(visitor.results);
}
return results;
}
}
/**
* Container that keeps track of file owners.
*/
class SearchedFiles {
final Map<String, Search> pathOwners = {};
final Map<Uri, Search> uriOwners = {};
bool add(String path, Search search) {
var file = search._driver.fsState.getFileForPath(path);
var pathOwner = pathOwners[path];
var uriOwner = uriOwners[file.uri];
if (pathOwner == null && uriOwner == null) {
pathOwners[path] = search;
uriOwners[file.uri] = search;
return true;
}
return identical(pathOwner, search) && identical(uriOwner, search);
}
void ownAdded(Search search) {
for (var path in search._driver.addedFiles) {
add(path, search);
}
}
}
/**
* A single search result.
*/
class SearchResult {
/**
* The deep most element that contains this result.
*/
final Element enclosingElement;
/**
* The kind of the [element] usage.
*/
final SearchResultKind kind;
/**
* The offset relative to the beginning of the containing file.
*/
final int offset;
/**
* The length of the usage in the containing file context.
*/
final int length;
/**
* Is `true` if a field or a method is using with a qualifier.
*/
final bool isResolved;
/**
* Is `true` if the result is a resolved reference to [element].
*/
final bool isQualified;
SearchResult._(this.enclosingElement, this.kind, this.offset, this.length,
this.isResolved, this.isQualified)
: assert(enclosingElement != null);
@override
String toString() {
StringBuffer buffer = new StringBuffer();
buffer.write("SearchResult(kind=");
buffer.write(kind);
buffer.write(", enclosingElement=");
buffer.write(enclosingElement);
buffer.write(", offset=");
buffer.write(offset);
buffer.write(", length=");
buffer.write(length);
buffer.write(", isResolved=");
buffer.write(isResolved);
buffer.write(", isQualified=");
buffer.write(isQualified);
buffer.write(")");
return buffer.toString();
}
}
/**
* The kind of reference in a [SearchResult].
*/
enum SearchResultKind { READ, READ_WRITE, WRITE, INVOCATION, REFERENCE }
/**
* A single subtype of a type.
*/
class SubtypeResult {
/**
* The URI of the library.
*/
final String libraryUri;
/**
* The identifier of the subtype.
*/
final String id;
/**
* The name of the subtype.
*/
final String name;
/**
* The names of instance members declared in the class.
*/
final List<String> members;
SubtypeResult(this.libraryUri, this.id, this.name, this.members);
@override
String toString() => id;
}
/**
* A visitor that finds the deep-most [Element] that contains the [offset].
*/
class _ContainingElementFinder extends GeneralizingElementVisitor {
final int offset;
Element containingElement;
_ContainingElementFinder(this.offset);
visitElement(Element element) {
if (element is ElementImpl) {
if (element.codeOffset != null &&
element.codeOffset <= offset &&
offset <= element.codeOffset + element.codeLength) {
containingElement = element;
super.visitElement(element);
}
}
}
}
/**
* Visitor that adds [SearchResult]s for references to the [importElement].
*/
class _ImportElementReferencesVisitor extends RecursiveAstVisitor {
final List<SearchResult> results = <SearchResult>[];
final ImportElement importElement;
final CompilationUnitElement enclosingUnitElement;
Set<Element> importedElements;
_ImportElementReferencesVisitor(
ImportElement element, this.enclosingUnitElement)
: importElement = element {
importedElements = element.namespace.definedNames.values.toSet();
}
@override
visitExportDirective(ExportDirective node) {}
@override
visitImportDirective(ImportDirective node) {}
@override
visitSimpleIdentifier(SimpleIdentifier node) {
if (node.inDeclarationContext()) {
return;
}
if (importElement.prefix != null) {
if (node.staticElement == importElement.prefix) {
AstNode parent = node.parent;
if (parent is PrefixedIdentifier && parent.prefix == node) {
if (importedElements.contains(parent.staticElement)) {
_addResultForPrefix(node, parent.identifier);
}
}
if (parent is MethodInvocation && parent.target == node) {
if (importedElements.contains(parent.methodName.staticElement)) {
_addResultForPrefix(node, parent.methodName);
}
}
}
} else {
if (importedElements.contains(node.staticElement)) {
_addResult(node.offset, 0);
}
}
}
void _addResult(int offset, int length) {
Element enclosingElement =
_getEnclosingElement(enclosingUnitElement, offset);
results.add(new SearchResult._(enclosingElement, SearchResultKind.REFERENCE,
offset, length, true, false));
}
void _addResultForPrefix(SimpleIdentifier prefixNode, AstNode nextNode) {
int prefixOffset = prefixNode.offset;
_addResult(prefixOffset, nextNode.offset - prefixOffset);
}
}
class _IndexRequest {
final AnalysisDriverUnitIndex index;
_IndexRequest(this.index);
void addSubtypes(
String superIdString, List<SubtypeResult> results, FileState file) {
var superId = getStringId(superIdString);
if (superId == -1) {
return;
}
var superIndex = _findFirstOccurrence(index.supertypes, superId);
if (superIndex == -1) {
return;
}
var library = file.library ?? file;
for (; index.supertypes[superIndex] == superId; superIndex++) {
var subtype = index.subtypes[superIndex];
var name = index.strings[subtype.name];
var subId = '${library.uriStr};${file.uriStr};$name';
results.add(new SubtypeResult(
library.uriStr,
subId,
name,
subtype.members.map((m) => index.strings[m]).toList(),
));
}
}
/**
* Return the [element]'s identifier in the [index] or `-1` if the
* [element] is not referenced in the [index].
*/
int findElementId(Element element) {
IndexElementInfo info = new IndexElementInfo(element);
element = info.element;
// Find the id of the element's unit.
int unitId = getUnitId(element);
if (unitId == -1) {
return -1;
}
// Prepare information about the element.
int unitMemberId = getElementUnitMemberId(element);
if (unitMemberId == -1) {
return -1;
}
int classMemberId = getElementClassMemberId(element);
if (classMemberId == -1) {
return -1;
}
int parameterId = getElementParameterId(element);
if (parameterId == -1) {
return -1;
}
// Try to find the element id using classMemberId, parameterId, and kind.
int elementId =
_findFirstOccurrence(index.elementNameUnitMemberIds, unitMemberId);
if (elementId == -1) {
return -1;
}
for (;
elementId < index.elementNameUnitMemberIds.length &&
index.elementNameUnitMemberIds[elementId] == unitMemberId;
elementId++) {
if (index.elementUnits[elementId] == unitId &&
index.elementNameClassMemberIds[elementId] == classMemberId &&
index.elementNameParameterIds[elementId] == parameterId &&
index.elementKinds[elementId] == info.kind) {
return elementId;
}
}
return -1;
}
/**
* Return the [element]'s class member name identifier, `null` is not a class
* member, or `-1` if the [element] is not referenced in the [index].
*/
int getElementClassMemberId(Element element) {
for (; element != null; element = element.enclosingElement) {
if (element.enclosingElement is ClassElement ||
element.enclosingElement is ExtensionElement) {
return getStringId(element.name);
}
}
return index.nullStringId;
}
/**
* Return the [element]'s class member name identifier, `null` is not a class
* member, or `-1` if the [element] is not referenced in the [index].
*/
int getElementParameterId(Element element) {
for (; element != null; element = element.enclosingElement) {
if (element is ParameterElement) {
return getStringId(element.name);
}
}
return index.nullStringId;
}
/**
* Return the [element]'s top-level name identifier, `0` is the unit, or
* `-1` if the [element] is not referenced in the [index].
*/
int getElementUnitMemberId(Element element) {
for (; element != null; element = element.enclosingElement) {
if (element.enclosingElement is CompilationUnitElement) {
return getStringId(element.name);
}
}
return index.nullStringId;
}
/**
* Return a list of results where an element with the given [elementId] has
* a relation with the kind from [relationToResultKind].
*
* The function [getEnclosingUnitElement] is used to lazily compute the
* enclosing [CompilationUnitElement] if there is a relation of an
* interesting kind.
*/
Future<List<SearchResult>> getRelations(
int elementId,
Map<IndexRelationKind, SearchResultKind> relationToResultKind,
Future<CompilationUnitElement> getEnclosingUnitElement()) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
// Find the first usage of the element.
int i = _findFirstOccurrence(index.usedElements, elementId);
if (i == -1) {
return const <SearchResult>[];
}
// Create locations for every usage of the element.
List<SearchResult> results = <SearchResult>[];
CompilationUnitElement enclosingUnitElement;
for (;
i < index.usedElements.length && index.usedElements[i] == elementId;
i++) {
IndexRelationKind relationKind = index.usedElementKinds[i];
SearchResultKind resultKind = relationToResultKind[relationKind];
if (resultKind != null) {
int offset = index.usedElementOffsets[i];
enclosingUnitElement ??= await getEnclosingUnitElement();
if (enclosingUnitElement != null) {
Element enclosingElement =
_getEnclosingElement(enclosingUnitElement, offset);
results.add(new SearchResult._(
enclosingElement,
resultKind,
offset,
index.usedElementLengths[i],
true,
index.usedElementIsQualifiedFlags[i]));
}
}
}
return results;
}
/**
* Return the identifier of [str] in the [index] or `-1` if [str] is not
* used in the [index].
*/
int getStringId(String str) {
return binarySearch(index.strings, str);
}
/**
* Return the identifier of the [CompilationUnitElement] containing the
* [element] in the [index] or `-1` if not found.
*/
int getUnitId(Element element) {
CompilationUnitElement unitElement = getUnitElement(element);
int libraryUriId = getUriId(unitElement.library.source.uri);
if (libraryUriId == -1) {
return -1;
}
int unitUriId = getUriId(unitElement.source.uri);
if (unitUriId == -1) {
return -1;
}
for (int i = 0; i < index.unitLibraryUris.length; i++) {
if (index.unitLibraryUris[i] == libraryUriId &&
index.unitUnitUris[i] == unitUriId) {
return i;
}
}
return -1;
}
/**
* Return a list of results where a class members with the given [name] is
* referenced with a qualifier, but is not resolved.
*/
Future<List<SearchResult>> getUnresolvedMemberReferences(
String name,
Map<IndexRelationKind, SearchResultKind> relationToResultKind,
Future<CompilationUnitElement> getEnclosingUnitElement()) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
// Find the name identifier.
int nameId = getStringId(name);
if (nameId == -1) {
return const <SearchResult>[];
}
// Find the first usage of the name.
int i = _findFirstOccurrence(index.usedNames, nameId);
if (i == -1) {
return const <SearchResult>[];
}
// Create results for every usage of the name.
List<SearchResult> results = <SearchResult>[];
CompilationUnitElement enclosingUnitElement;
for (; i < index.usedNames.length && index.usedNames[i] == nameId; i++) {
IndexRelationKind relationKind = index.usedNameKinds[i];
SearchResultKind resultKind = relationToResultKind[relationKind];
if (resultKind != null) {
int offset = index.usedNameOffsets[i];
enclosingUnitElement ??= await getEnclosingUnitElement();
if (enclosingUnitElement != null) {
Element enclosingElement =
_getEnclosingElement(enclosingUnitElement, offset);
results.add(new SearchResult._(enclosingElement, resultKind, offset,
name.length, false, index.usedNameIsQualifiedFlags[i]));
}
}
}
return results;
}
/**
* Return the identifier of the [uri] in the [index] or `-1` if the [uri] is
* not used in the [index].
*/
int getUriId(Uri uri) {
String str = uri.toString();
return getStringId(str);
}
/**
* Return the index of the first occurrence of the [value] in the [sortedList],
* or `-1` if the [value] is not in the list.
*/
int _findFirstOccurrence(List<int> sortedList, int value) {
// Find an occurrence.
int i = binarySearch(sortedList, value);
if (i == -1) {
return -1;
}
// Find the first occurrence.
while (i > 0 && sortedList[i - 1] == value) {
i--;
}
return i;
}
}
/**
* Visitor that adds [SearchResult]s for local elements of a block, method,
* class or a library - labels, local functions, local variables and parameters,
* type parameters, import prefixes.
*/
class _LocalReferencesVisitor extends RecursiveAstVisitor {
final List<SearchResult> results = <SearchResult>[];
final Element element;
final CompilationUnitElement enclosingUnitElement;
_LocalReferencesVisitor(this.element, this.enclosingUnitElement);
@override
visitSimpleIdentifier(SimpleIdentifier node) {
if (node.inDeclarationContext()) {
return;
}
if (node.staticElement == element) {
AstNode parent = node.parent;
SearchResultKind kind = SearchResultKind.REFERENCE;
if (element is FunctionElement) {
if (parent is MethodInvocation && parent.methodName == node) {
kind = SearchResultKind.INVOCATION;
}
} else if (element is VariableElement) {
bool isGet = node.inGetterContext();
bool isSet = node.inSetterContext();
if (isGet && isSet) {
kind = SearchResultKind.READ_WRITE;
} else if (isGet) {
if (parent is MethodInvocation && parent.methodName == node) {
kind = SearchResultKind.INVOCATION;
} else {
kind = SearchResultKind.READ;
}
} else if (isSet) {
kind = SearchResultKind.WRITE;
}
}
_addResult(node, kind);
}
}
void _addResult(AstNode node, SearchResultKind kind) {
bool isQualified = node.parent is Label;
Element enclosingElement =
_getEnclosingElement(enclosingUnitElement, node.offset);
results.add(new SearchResult._(
enclosingElement, kind, node.offset, node.length, true, isQualified));
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/experiments_impl.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/dart/analysis/features.dart';
import 'package:analyzer/src/dart/analysis/experiments.dart';
import 'package:meta/meta.dart';
import 'package:pub_semver/pub_semver.dart';
/// The same as [ExperimentStatus.knownFeatures], except when a call to
/// [overrideKnownFeatures] is in progress.
Map<String, ExperimentalFeature> _knownFeatures =
ExperimentStatus.knownFeatures;
/// Decodes the strings given in [flags] into a list of booleans representing
/// experiments that should be enabled.
///
/// Always succeeds, even if the input flags are invalid. Expired and
/// unrecognized flags are ignored, conflicting flags are resolved in favor of
/// the flag appearing last.
List<bool> decodeFlags(List<String> flags) {
var decodedFlags = List<bool>.filled(_knownFeatures.length, false);
for (var feature in _knownFeatures.values) {
decodedFlags[feature.index] = feature.isEnabledByDefault;
}
for (var entry in _flagStringsToMap(flags).entries) {
decodedFlags[entry.key] = entry.value;
}
return decodedFlags;
}
/// Computes a set of features for use in a unit test. Computes the set of
/// features enabled in [sdkVersion], plus any specified [additionalFeatures].
///
/// If [sdkVersion] is not supplied (or is `null`), then the current set of
/// enabled features is used as the starting point.
List<bool> enableFlagsForTesting(
{String sdkVersion, List<Feature> additionalFeatures: const []}) {
var flags = decodeFlags([]);
if (sdkVersion != null) {
flags = restrictEnableFlagsToVersion(flags, Version.parse(sdkVersion));
}
for (ExperimentalFeature feature in additionalFeatures) {
flags[feature.index] = true;
}
return flags;
}
/// Pretty-prints the given set of enable flags as a set of feature names.
String experimentStatusToString(List<bool> enableFlags) {
var featuresInSet = <String>[];
for (var feature in _knownFeatures.values) {
if (enableFlags[feature.index]) {
featuresInSet.add(feature.enableString);
}
}
return 'FeatureSet{${featuresInSet.join(', ')}}';
}
/// Converts the flags in [status] to a list of strings suitable for
/// passing to [_decodeFlags].
List<String> experimentStatusToStringList(ExperimentStatus status) {
var result = <String>[];
for (var feature in _knownFeatures.values) {
if (feature.isExpired) continue;
var isEnabled = status.isEnabled(feature);
if (isEnabled != feature.isEnabledByDefault) {
result.add(feature.stringForValue(isEnabled));
}
}
return result;
}
/// Execute the callback, pretending that the given [knownFeatures] take the
/// place of [ExperimentStatus.knownFeatures].
///
/// It isn't safe to call this method with an asynchronous callback, because it
/// only changes the set of known features during the time that [callback] is
/// (synchronously) executing.
@visibleForTesting
T overrideKnownFeatures<T>(
Map<String, ExperimentalFeature> knownFeatures, T callback()) {
var oldKnownFeatures = _knownFeatures;
try {
_knownFeatures = knownFeatures;
return callback();
} finally {
_knownFeatures = oldKnownFeatures;
}
}
/// Computes a new set of enable flags based on [flags], but with any features
/// that were not present in [version] set to `false`.
List<bool> restrictEnableFlagsToVersion(List<bool> flags, Version version) {
flags = List.from(flags);
for (var feature in _knownFeatures.values) {
if (!feature.isEnabledByDefault ||
feature.firstSupportedVersion > version) {
flags[feature.index] = false;
}
}
return flags;
}
/// Validates whether there are any disagreements between the strings given in
/// [flags1] and the strings given in [flags2].
///
/// The returned iterable yields any problems that were found. Only reports
/// problems related to combining the flags; problems that would be found by
/// applying [validateFlags] to [flags1] or [flags2] individually are not
/// reported.
///
/// If no problems are found, it is safe to concatenate the flag lists. If
/// problems are found, the only negative side effect is that some flags in
/// one list may be overridden by some flags in the other list.
///
/// TODO(paulberry): if this method ever needs to be exposed via the analyzer
/// public API, consider making a version that reports validation results using
/// the AnalysisError type.
Iterable<ConflictingFlagLists> validateFlagCombination(
List<String> flags1, List<String> flags2) sync* {
var flag1Map = _flagStringsToMap(flags1);
var flag2Map = _flagStringsToMap(flags2);
for (var entry in flag2Map.entries) {
if (flag1Map[entry.key] != null && flag1Map[entry.key] != entry.value) {
yield new ConflictingFlagLists(
_featureIndexToFeature(entry.key), !entry.value);
}
}
}
/// Validates whether the strings given in [flags] constitute a valid set of
/// experimental feature enable/disable flags.
///
/// The returned iterable yields any problems that were found.
///
/// TODO(paulberry): if this method ever needs to be exposed via the analyzer
/// public API, consider making a version that reports validation results using
/// the AnalysisError type.
Iterable<ValidationResult> validateFlags(List<String> flags) sync* {
var previousFlagIndex = <int, int>{};
var previousFlagValue = <int, bool>{};
for (int flagIndex = 0; flagIndex < flags.length; flagIndex++) {
var flag = flags[flagIndex];
ExperimentalFeature feature;
bool requestedValue;
if (flag.startsWith('no-')) {
feature = _knownFeatures[flag.substring(3)];
requestedValue = false;
} else {
feature = _knownFeatures[flag];
requestedValue = true;
}
if (feature == null) {
yield UnrecognizedFlag(flagIndex, flag);
} else if (feature.isExpired) {
yield requestedValue == feature.isEnabledByDefault
? UnnecessaryUseOfExpiredFlag(flagIndex, feature)
: IllegalUseOfExpiredFlag(flagIndex, feature);
} else if (previousFlagIndex.containsKey(feature.index) &&
previousFlagValue[feature.index] != requestedValue) {
yield ConflictingFlags(
flagIndex, previousFlagIndex[feature.index], feature, requestedValue);
} else {
previousFlagIndex[feature.index] = flagIndex;
previousFlagValue[feature.index] = requestedValue;
}
}
}
ExperimentalFeature _featureIndexToFeature(int index) {
for (var feature in _knownFeatures.values) {
if (feature.index == index) return feature;
}
throw new ArgumentError('Unrecognized feature index');
}
Map<int, bool> _flagStringsToMap(List<String> flags) {
var result = <int, bool>{};
for (int flagIndex = 0; flagIndex < flags.length; flagIndex++) {
var flag = flags[flagIndex];
ExperimentalFeature feature;
bool requestedValue;
if (flag.startsWith('no-')) {
feature = _knownFeatures[flag.substring(3)];
requestedValue = false;
} else {
feature = _knownFeatures[flag];
requestedValue = true;
}
if (feature != null && !feature.isExpired) {
result[feature.index] = requestedValue;
}
}
return result;
}
/// Indication of a conflict between two lists of flags.
class ConflictingFlagLists {
/// Info about which feature the user requested conflicting values for
final ExperimentalFeature feature;
/// True if the first list of flags requested to enable the experimental
/// feature.
final bool firstValue;
ConflictingFlagLists(this.feature, this.firstValue);
}
/// Validation result indicating that the user requested conflicting values for
/// an experimental flag (e.g. both "foo" and "no-foo").
class ConflictingFlags extends ValidationResult {
/// Info about which feature the user requested conflicting values for
final ExperimentalFeature feature;
/// The index of the first of the two conflicting strings.
///
/// [stringIndex] is the index of the second of the two conflicting strings.
final int previousStringIndex;
/// True if the string at [stringIndex] requested to enable the experimental
/// feature.
///
/// The string at [previousStringIndex] requested the opposite.
final bool requestedValue;
ConflictingFlags(int stringIndex, this.previousStringIndex, this.feature,
this.requestedValue)
: super._(stringIndex);
@override
String get flag => feature.stringForValue(requestedValue);
@override
bool get isError => true;
@override
String get message {
var previousFlag = feature.stringForValue(!requestedValue);
return 'Flag "$flag" conflicts with previous flag "$previousFlag"';
}
}
/// Information about a single experimental flag that the user might use to
/// request that a feature be enabled (or disabled).
class ExperimentalFeature implements Feature {
/// Index of the flag in the private data structure maintained by
/// [ExperimentStatus].
///
/// This index should not be relied upon to be stable over time. For instance
/// it should not be used to serialize the state of experiments to long term
/// storage if there is any expectation of compatibility between analyzer
/// versions.
final int index;
/// The string to enable the feature.
final String enableString;
/// Whether the feature is currently enabled by default.
final bool isEnabledByDefault;
/// Whether the flag is currently expired (meaning the enable/disable status
/// can no longer be altered from the value in [isEnabledByDefault]).
final bool isExpired;
/// Documentation for the feature, if known. `null` for expired flags.
final String documentation;
final String _firstSupportedVersion;
const ExperimentalFeature(this.index, this.enableString,
this.isEnabledByDefault, this.isExpired, this.documentation,
{String firstSupportedVersion})
: _firstSupportedVersion = firstSupportedVersion,
assert(index != null),
assert(isEnabledByDefault
? firstSupportedVersion != null
: firstSupportedVersion == null),
assert(enableString != null);
/// The string to disable the feature.
String get disableString => 'no-$enableString';
@override
String get experimentalFlag => isExpired ? null : enableString;
@override
Version get firstSupportedVersion {
if (_firstSupportedVersion == null) {
return null;
} else {
return Version.parse(_firstSupportedVersion);
}
}
@override
FeatureStatus get status {
if (isExpired) {
if (isEnabledByDefault) {
return FeatureStatus.current;
} else {
return FeatureStatus.abandoned;
}
} else {
if (isEnabledByDefault) {
return FeatureStatus.provisional;
} else {
return FeatureStatus.future;
}
}
}
/// Retrieves the string to enable or disable the feature, depending on
/// [value].
String stringForValue(bool value) => value ? enableString : disableString;
@override
String toString() => enableString;
}
/// Validation result indicating that the user requested enabling or disabling
/// of a feature associated with an expired flag, and the requested behavior
/// conflicts with the behavior that is now hardcoded into the toolchain.
class IllegalUseOfExpiredFlag extends ValidationResult {
/// Information about the feature associated with the error.
final ExperimentalFeature feature;
IllegalUseOfExpiredFlag(int flagIndex, this.feature) : super._(flagIndex);
@override
String get flag => feature.stringForValue(!feature.isEnabledByDefault);
@override
bool get isError => true;
@override
String get message {
var state = feature.isEnabledByDefault ? 'enabled' : 'disabled';
return 'Flag "$flag" was supplied, but the feature is already '
'unconditionally $state.';
}
}
/// Validation result indicating that the user requested enabling or disabling
/// of a feature associated with an expired flag, and the requested behavior
/// is consistent with the behavior that is now hardcoded into the toolchain.
/// (This is merely a warning, not an error).
class UnnecessaryUseOfExpiredFlag extends ValidationResult {
/// Information about the feature associated with the warning.
final ExperimentalFeature feature;
UnnecessaryUseOfExpiredFlag(int flagIndex, this.feature) : super._(flagIndex);
@override
String get flag => feature.stringForValue(feature.isEnabledByDefault);
@override
bool get isError => false;
@override
String get message => 'Flag "$flag" is no longer required.';
}
/// Validation result indicating that the user requested enabling or disabling
/// an unrecognized feature.
class UnrecognizedFlag extends ValidationResult {
@override
final String flag;
UnrecognizedFlag(int flagIndex, this.flag) : super._(flagIndex);
@override
bool get isError => true;
@override
String get message => 'Flag "$flag" not recognized.';
}
/// Representation of a single error or warning reported by
/// [ExperimentStatus.fromStrings].
abstract class ValidationResult {
/// Indicates which of the supplied strings is associated with the error or
/// warning.
final int stringIndex;
ValidationResult._(this.stringIndex);
/// The supplied string associated with the error or warning.
String get flag;
/// Indicates whether the validation result is an error or a warning.
bool get isError;
/// Message describing the problem.
String get message;
@override
String toString() => message;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/experiments.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/dart/analysis/features.dart';
import 'package:analyzer/src/dart/analysis/experiments_impl.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:meta/meta.dart';
import 'package:pub_semver/src/version.dart';
export 'package:analyzer/src/dart/analysis/experiments_impl.dart'
show
ConflictingFlags,
ExperimentalFeature,
IllegalUseOfExpiredFlag,
UnnecessaryUseOfExpiredFlag,
UnrecognizedFlag,
validateFlags,
ValidationResult;
part 'experiments.g.dart';
/// Gets access to the private list of boolean flags in an [Experiments] object.
/// For testing use only.
@visibleForTesting
List<bool> getExperimentalFlags_forTesting(ExperimentStatus status) =>
status._enableFlags;
/// A representation of the set of experiments that are active and whether they
/// are enabled.
class ExperimentStatus with _CurrentState implements FeatureSet {
/// A map containing information about all known experimental flags.
static const knownFeatures = _knownFeatures;
final List<bool> _enableFlags;
/// Initializes a newly created set of experiments based on optional
/// arguments.
ExperimentStatus() : _enableFlags = _buildExperimentalFlagsArray();
/// Computes a set of features for use in a unit test. Computes the set of
/// features enabled in [sdkVersion], plus any specified [additionalFeatures].
///
/// If [sdkVersion] is not supplied (or is `null`), then the current set of
/// enabled features is used as the starting point.
@visibleForTesting
ExperimentStatus.forTesting(
{String sdkVersion, List<Feature> additionalFeatures: const []})
: this._(enableFlagsForTesting(
sdkVersion: sdkVersion, additionalFeatures: additionalFeatures));
/// Decodes the strings given in [flags] into a representation of the set of
/// experiments that should be enabled.
///
/// Always succeeds, even if the input flags are invalid. Expired and
/// unrecognized flags are ignored, conflicting flags are resolved in favor of
/// the flag appearing last.
ExperimentStatus.fromStrings(List<String> flags) : this._(decodeFlags(flags));
ExperimentStatus._(this._enableFlags);
@override
int get hashCode {
int hash = 0;
for (var flag in _enableFlags) {
hash = JenkinsSmiHash.combine(hash, flag.hashCode);
}
return JenkinsSmiHash.finish(hash);
}
@override
operator ==(Object other) {
if (other is ExperimentStatus) {
if (_enableFlags.length != other._enableFlags.length) return false;
for (int i = 0; i < _enableFlags.length; i++) {
if (_enableFlags[i] != other._enableFlags[i]) return false;
}
return true;
}
return false;
}
/// Queries whether the given [feature] is enabled or disabled.
@override
bool isEnabled(covariant ExperimentalFeature feature) =>
_enableFlags[feature.index];
@override
FeatureSet restrictToVersion(Version version) =>
ExperimentStatus._(restrictEnableFlagsToVersion(_enableFlags, version));
@override
String toString() => experimentStatusToString(_enableFlags);
/// Returns a list of strings suitable for passing to
/// [ExperimentStatus.fromStrings].
List<String> toStringList() => experimentStatusToStringList(this);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/results.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/dart/analysis/results.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/source/line_info.dart';
import 'package:analyzer/src/generated/resolver.dart';
abstract class AnalysisResultImpl implements AnalysisResult {
@override
final AnalysisSession session;
@override
final String path;
@override
final Uri uri;
AnalysisResultImpl(this.session, this.path, this.uri);
}
class ElementDeclarationResultImpl implements ElementDeclarationResult {
@override
final Element element;
@override
final AstNode node;
@override
final ParsedUnitResult parsedUnit;
@override
final ResolvedUnitResult resolvedUnit;
ElementDeclarationResultImpl(
this.element, this.node, this.parsedUnit, this.resolvedUnit);
}
class ErrorsResultImpl extends FileResultImpl implements ErrorsResult {
@override
final List<AnalysisError> errors;
ErrorsResultImpl(AnalysisSession session, String path, Uri uri,
LineInfo lineInfo, bool isPart, this.errors)
: super(session, path, uri, lineInfo, isPart);
}
class FileResultImpl extends AnalysisResultImpl implements FileResult {
@override
final LineInfo lineInfo;
@override
final bool isPart;
FileResultImpl(
AnalysisSession session, String path, Uri uri, this.lineInfo, this.isPart)
: super(session, path, uri);
@override
ResultState get state => ResultState.VALID;
}
class ParsedLibraryResultImpl extends AnalysisResultImpl
implements ParsedLibraryResult {
@override
final List<ParsedUnitResult> units;
ParsedLibraryResultImpl(
AnalysisSession session, String path, Uri uri, this.units)
: super(session, path, uri);
ParsedLibraryResultImpl.external(AnalysisSession session, Uri uri)
: this(session, null, uri, null);
@override
ResultState get state {
if (path == null) {
return ResultState.NOT_A_FILE;
}
return ResultState.VALID;
}
@override
ElementDeclarationResult getElementDeclaration(Element element) {
if (state != ResultState.VALID) {
throw StateError('The result is not valid: $state');
}
var elementPath = element.source.fullName;
var unitResult = units.firstWhere(
(r) => r.path == elementPath,
orElse: () {
throw ArgumentError('Element (${element.runtimeType}) $element is not '
'defined in this library.');
},
);
if (element.isSynthetic || element.nameOffset == -1) {
return null;
}
var locator = _DeclarationByElementLocator(element);
unitResult.unit.accept(locator);
var declaration = locator.result;
return ElementDeclarationResultImpl(element, declaration, unitResult, null);
}
}
class ParsedUnitResultImpl extends FileResultImpl implements ParsedUnitResult {
@override
final String content;
@override
final CompilationUnit unit;
@override
final List<AnalysisError> errors;
ParsedUnitResultImpl(AnalysisSession session, String path, Uri uri,
this.content, LineInfo lineInfo, bool isPart, this.unit, this.errors)
: super(session, path, uri, lineInfo, isPart);
@override
ResultState get state => ResultState.VALID;
}
class ParseStringResultImpl implements ParseStringResult {
@override
final String content;
@override
final List<AnalysisError> errors;
@override
final CompilationUnit unit;
ParseStringResultImpl(this.content, this.unit, this.errors);
@override
LineInfo get lineInfo => unit.lineInfo;
}
class ResolvedLibraryResultImpl extends AnalysisResultImpl
implements ResolvedLibraryResult {
@override
final LibraryElement element;
@override
final TypeProvider typeProvider;
@override
final List<ResolvedUnitResult> units;
ResolvedLibraryResultImpl(AnalysisSession session, String path, Uri uri,
this.element, this.typeProvider, this.units)
: super(session, path, uri);
ResolvedLibraryResultImpl.external(AnalysisSession session, Uri uri)
: this(session, null, uri, null, null, null);
@override
ResultState get state {
if (path == null) {
return ResultState.NOT_A_FILE;
}
return ResultState.VALID;
}
@override
ElementDeclarationResult getElementDeclaration(Element element) {
if (state != ResultState.VALID) {
throw StateError('The result is not valid: $state');
}
var elementPath = element.source.fullName;
var unitResult = units.firstWhere(
(r) => r.path == elementPath,
orElse: () {
throw ArgumentError('Element (${element.runtimeType}) $element is not '
'defined in this library.');
},
);
if (element.isSynthetic || element.nameOffset == -1) {
return null;
}
var locator = _DeclarationByElementLocator(element);
unitResult.unit.accept(locator);
var declaration = locator.result;
return ElementDeclarationResultImpl(element, declaration, null, unitResult);
}
}
class ResolvedUnitResultImpl extends FileResultImpl
implements ResolvedUnitResult {
/// Return `true` if the file exists.
final bool exists;
@override
final String content;
@override
final CompilationUnit unit;
@override
final List<AnalysisError> errors;
ResolvedUnitResultImpl(
AnalysisSession session,
String path,
Uri uri,
this.exists,
this.content,
LineInfo lineInfo,
bool isPart,
this.unit,
this.errors)
: super(session, path, uri, lineInfo, isPart);
@override
LibraryElement get libraryElement => unit.declaredElement.library;
@override
ResultState get state => exists ? ResultState.VALID : ResultState.NOT_A_FILE;
@override
TypeProvider get typeProvider => unit.declaredElement.context.typeProvider;
@override
TypeSystem get typeSystem => unit.declaredElement.context.typeSystem;
}
class UnitElementResultImpl extends AnalysisResultImpl
implements UnitElementResult {
@override
final String signature;
@override
final CompilationUnitElement element;
UnitElementResultImpl(AnalysisSession session, String path, Uri uri,
this.signature, this.element)
: super(session, path, uri);
@override
ResultState get state => ResultState.VALID;
}
class _DeclarationByElementLocator extends GeneralizingAstVisitor<void> {
final Element element;
AstNode result;
_DeclarationByElementLocator(this.element);
@override
void visitNode(AstNode node) {
if (result != null) return;
if (element is ClassElement) {
if (node is ClassOrMixinDeclaration) {
if (_hasOffset(node.name)) {
result = node;
}
} else if (node is ClassTypeAlias) {
if (_hasOffset(node.name)) {
result = node;
}
} else if (node is EnumDeclaration) {
if (_hasOffset(node.name)) {
result = node;
}
}
} else if (element is ConstructorElement) {
if (node is ConstructorDeclaration) {
if (node.name != null) {
if (_hasOffset(node.name)) {
result = node;
}
} else {
if (_hasOffset(node.returnType)) {
result = node;
}
}
}
} else if (element is ExtensionElement) {
if (node is ExtensionDeclaration) {
if (_hasOffset(node.name)) {
result = node;
}
}
} else if (element is FieldElement) {
if (node is EnumConstantDeclaration) {
if (_hasOffset(node.name)) {
result = node;
}
} else if (node is VariableDeclaration) {
if (_hasOffset(node.name)) {
result = node;
}
}
} else if (element is FunctionElement) {
if (node is FunctionDeclaration && _hasOffset(node.name)) {
result = node;
}
} else if (element is LocalVariableElement) {
if (node is VariableDeclaration && _hasOffset(node.name)) {
result = node;
}
} else if (element is MethodElement) {
if (node is MethodDeclaration && _hasOffset(node.name)) {
result = node;
}
} else if (element is ParameterElement) {
if (node is FormalParameter && _hasOffset(node.identifier)) {
result = node;
}
} else if (element is PropertyAccessorElement) {
if (node is FunctionDeclaration) {
if (_hasOffset(node.name)) {
result = node;
}
} else if (node is MethodDeclaration) {
if (_hasOffset(node.name)) {
result = node;
}
}
} else if (element is TopLevelVariableElement) {
if (node is VariableDeclaration && _hasOffset(node.name)) {
result = node;
}
}
super.visitNode(node);
}
bool _hasOffset(AstNode node) {
return node?.offset == element.nameOffset;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/cache.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
/**
* LRU cache of objects.
*/
class Cache<K, V> {
final int _maxSizeBytes;
final int Function(V) _meter;
final _map = new LinkedHashMap<K, V>();
int _currentSizeBytes = 0;
Cache(this._maxSizeBytes, this._meter);
V get(K key, V getNotCached()) {
V value = _map.remove(key);
if (value == null) {
value = getNotCached();
if (value != null) {
_map[key] = value;
_currentSizeBytes += _meter(value);
_evict();
}
} else {
_map[key] = value;
}
return value;
}
void put(K key, V value) {
V oldValue = _map[key];
if (oldValue != null) {
_currentSizeBytes -= _meter(oldValue);
}
_map[key] = value;
_currentSizeBytes += _meter(value);
_evict();
}
void _evict() {
while (_currentSizeBytes > _maxSizeBytes) {
if (_map.isEmpty) {
// Should be impossible, since _currentSizeBytes should always match
// _map. But recover anyway.
assert(false);
_currentSizeBytes = 0;
break;
}
K key = _map.keys.first;
V value = _map.remove(key);
_currentSizeBytes -= _meter(value);
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/mutex.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';
/// Mutual exclusion.
///
/// Usage:
///
/// var m = new Mutex();
///
/// await m.acquire();
/// try {
/// // critical section
/// }
/// finally {
/// m.release();
/// }
class Mutex {
Completer<void> _lock;
/// Acquire a lock.
///
/// Returns a [Future] that will be completed when the lock has been acquired.
Future<void> acquire() async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
while (_lock != null) {
await _lock.future;
}
_lock = new Completer<void>();
}
/// Run the given [criticalSection] with acquired mutex.
Future<T> guard<T>(Future<T> criticalSection()) async {
// TODO(brianwilkerson) Determine whether this await is necessary.
await null;
await acquire();
try {
return await criticalSection();
} finally {
release();
}
}
/// Release a lock.
///
/// Release a lock that has been acquired.
void release() {
if (_lock == null) {
throw new StateError('No lock to release.');
}
_lock.complete();
_lock = null;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/performance_logger.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';
/// This class is used to gather and print performance information.
class PerformanceLog {
final StringSink sink;
int _level = 0;
PerformanceLog(this.sink);
/// Enter a new execution section, which starts at one point of code, runs
/// some time, and then ends at the other point of code.
///
/// The client must call [PerformanceLogSection.exit] for every [enter].
PerformanceLogSection enter(String msg) {
writeln('+++ $msg.');
_level++;
return new PerformanceLogSection(this, msg);
}
/// Return the result of the function [f] invocation and log the elapsed time.
///
/// Each invocation of [run] creates a new enclosed section in the log,
/// which begins with printing [msg], then any log output produced during
/// [f] invocation, and ends with printing [msg] with the elapsed time.
T run<T>(String msg, T f()) {
Stopwatch timer = new Stopwatch()..start();
try {
writeln('+++ $msg.');
_level++;
return f();
} finally {
_level--;
int ms = timer.elapsedMilliseconds;
writeln('--- $msg in $ms ms.');
}
}
/// Return the result of the function [f] invocation and log the elapsed time.
///
/// Each invocation of [run] creates a new enclosed section in the log,
/// which begins with printing [msg], then any log output produced during
/// [f] invocation, and ends with printing [msg] with the elapsed time.
Future<T> runAsync<T>(String msg, Future<T> f()) async {
Stopwatch timer = new Stopwatch()..start();
try {
writeln('+++ $msg.');
_level++;
return await f();
} finally {
_level--;
int ms = timer.elapsedMilliseconds;
writeln('--- $msg in $ms ms.');
}
}
/// Write a new line into the log.
void writeln(String msg) {
if (sink != null) {
String indent = '\t' * _level;
sink.writeln('$indent$msg');
}
}
}
/**
* The performance measurement section for operations that start and end
* at different place in code, so cannot be run using [PerformanceLog.run].
*
* The client must call [exit] for every [PerformanceLog.enter].
*/
class PerformanceLogSection {
final PerformanceLog _logger;
final String _msg;
final Stopwatch _timer = new Stopwatch()..start();
PerformanceLogSection(this._logger, this._msg);
/**
* Stop the timer, log the time.
*/
void exit() {
_timer.stop();
_logger._level--;
int ms = _timer.elapsedMilliseconds;
_logger.writeln('--- $_msg in $ms ms.');
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/library_analyzer.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:analyzer/src/dart/analysis/testing_data.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/constant/compute.dart';
import 'package:analyzer/src/dart/constant/constant_verifier.dart';
import 'package:analyzer/src/dart/constant/evaluation.dart';
import 'package:analyzer/src/dart/constant/utilities.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/inheritance_manager3.dart';
import 'package:analyzer/src/dart/element/type_provider.dart';
import 'package:analyzer/src/dart/resolver/ast_rewrite.dart';
import 'package:analyzer/src/dart/resolver/flow_analysis_visitor.dart';
import 'package:analyzer/src/dart/resolver/legacy_type_asserter.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/error/imports_verifier.dart';
import 'package:analyzer/src/error/inheritance_override.dart';
import 'package:analyzer/src/generated/declaration_resolver.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/error_verifier.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/hint/sdk_constraint_verifier.dart';
import 'package:analyzer/src/ignore_comments/ignore_info.dart';
import 'package:analyzer/src/lint/linter.dart';
import 'package:analyzer/src/lint/linter_visitor.dart';
import 'package:analyzer/src/services/lint.dart';
import 'package:analyzer/src/summary2/linked_element_factory.dart';
import 'package:analyzer/src/task/strong/checker.dart';
import 'package:pub_semver/pub_semver.dart';
var timerLibraryAnalyzer = Stopwatch();
var timerLibraryAnalyzerConst = Stopwatch();
var timerLibraryAnalyzerFreshUnit = Stopwatch();
var timerLibraryAnalyzerResolve = Stopwatch();
var timerLibraryAnalyzerSplicer = Stopwatch();
var timerLibraryAnalyzerVerify = Stopwatch();
/**
* Analyzer of a single library.
*/
class LibraryAnalyzer {
/// A marker object used to prevent the initialization of
/// [_versionConstraintFromPubspec] when the previous initialization attempt
/// failed.
static final VersionRange noSpecifiedRange = new VersionRange();
final AnalysisOptionsImpl _analysisOptions;
final DeclaredVariables _declaredVariables;
final SourceFactory _sourceFactory;
final FileState _library;
final ResourceProvider _resourceProvider;
final InheritanceManager3 _inheritance;
final bool Function(Uri) _isLibraryUri;
final AnalysisContext _context;
final LinkedElementFactory _elementFactory;
TypeProviderImpl _typeProvider;
final TypeSystem _typeSystem;
LibraryElement _libraryElement;
LibraryScope _libraryScope;
final Map<FileState, LineInfo> _fileToLineInfo = {};
final Map<FileState, IgnoreInfo> _fileToIgnoreInfo = {};
final Map<FileState, RecordingErrorListener> _errorListeners = {};
final Map<FileState, ErrorReporter> _errorReporters = {};
final TestingData _testingData;
final List<UsedImportedElements> _usedImportedElementsList = [];
final List<UsedLocalElements> _usedLocalElementsList = [];
/**
* Constants in the current library.
*
* TODO(scheglov) Remove after https://github.com/dart-lang/sdk/issues/31925
*/
final Set<ConstantEvaluationTarget> _libraryConstants = new Set();
final Set<ConstantEvaluationTarget> _constants = new Set();
LibraryAnalyzer(
this._analysisOptions,
this._declaredVariables,
this._sourceFactory,
this._isLibraryUri,
this._context,
this._elementFactory,
this._inheritance,
this._library,
this._resourceProvider,
{TestingData testingData})
: _typeSystem = _context.typeSystem,
_testingData = testingData;
/**
* Compute analysis results for all units of the library.
*/
Map<FileState, UnitAnalysisResult> analyze() {
return PerformanceStatistics.analysis.makeCurrentWhile(() {
return analyzeSync();
});
}
/**
* Compute analysis results for all units of the library.
*/
Map<FileState, UnitAnalysisResult> analyzeSync() {
timerLibraryAnalyzer.start();
Map<FileState, CompilationUnit> units = {};
// Parse all files.
timerLibraryAnalyzerFreshUnit.start();
for (FileState file in _library.libraryFiles) {
units[file] = _parse(file);
}
timerLibraryAnalyzerFreshUnit.stop();
// Resolve URIs in directives to corresponding sources.
FeatureSet featureSet = units[_library].featureSet;
_typeProvider = _context.typeProvider;
if (featureSet.isEnabled(Feature.non_nullable)) {
_typeProvider = _typeProvider.withNullability(NullabilitySuffix.none);
} else {
_typeProvider = _typeProvider.withNullability(NullabilitySuffix.star);
}
units.forEach((file, unit) {
_validateFeatureSet(unit, featureSet);
_resolveUriBasedDirectives(file, unit);
});
_libraryElement = _elementFactory.libraryOfUri(_library.uriStr);
_libraryScope = new LibraryScope(_libraryElement);
timerLibraryAnalyzerResolve.start();
_resolveDirectives(units);
units.forEach((file, unit) {
_resolveFile(file, unit);
});
timerLibraryAnalyzerResolve.stop();
timerLibraryAnalyzerConst.start();
units.values.forEach(_findConstants);
_clearConstantEvaluationResults();
_computeConstants();
timerLibraryAnalyzerConst.stop();
timerLibraryAnalyzerVerify.start();
PerformanceStatistics.errors.makeCurrentWhile(() {
units.forEach((file, unit) {
_computeVerifyErrors(file, unit);
});
});
if (_analysisOptions.hint) {
PerformanceStatistics.hints.makeCurrentWhile(() {
units.forEach((file, unit) {
{
var visitor = new GatherUsedLocalElementsVisitor(_libraryElement);
unit.accept(visitor);
_usedLocalElementsList.add(visitor.usedElements);
}
{
var visitor =
new GatherUsedImportedElementsVisitor(_libraryElement);
unit.accept(visitor);
_usedImportedElementsList.add(visitor.usedElements);
}
});
units.forEach((file, unit) {
_computeHints(file, unit);
});
});
}
if (_analysisOptions.lint) {
PerformanceStatistics.lints.makeCurrentWhile(() {
var allUnits = _library.libraryFiles
.map((file) => LinterContextUnit(file.content, units[file]))
.toList();
for (int i = 0; i < allUnits.length; i++) {
_computeLints(_library.libraryFiles[i], allUnits[i], allUnits);
}
});
}
assert(units.values.every(LegacyTypeAsserter.assertLegacyTypes));
timerLibraryAnalyzerVerify.stop();
// Return full results.
Map<FileState, UnitAnalysisResult> results = {};
units.forEach((file, unit) {
List<AnalysisError> errors = _getErrorListener(file).errors;
errors = _filterIgnoredErrors(file, errors);
results[file] = new UnitAnalysisResult(file, unit, errors);
});
timerLibraryAnalyzer.stop();
return results;
}
/**
* Clear evaluation results for all constants before computing them again.
* The reason is described in https://github.com/dart-lang/sdk/issues/35940
*
* Otherwise, we reuse results, including errors are recorded only when
* we evaluate constants resynthesized from summaries.
*
* TODO(scheglov) Remove after https://github.com/dart-lang/sdk/issues/31925
*/
void _clearConstantEvaluationResults() {
for (var constant in _libraryConstants) {
if (constant is ConstFieldElementImpl_ofEnum) continue;
if (constant is ConstVariableElement) {
constant.evaluationResult = null;
}
}
}
void _computeConstantErrors(
ErrorReporter errorReporter, CompilationUnit unit) {
ConstantVerifier constantVerifier = new ConstantVerifier(
errorReporter, _libraryElement, _typeProvider, _declaredVariables,
featureSet: unit.featureSet, forAnalysisDriver: true);
unit.accept(constantVerifier);
}
/**
* Compute [_constants] in all units.
*/
void _computeConstants() {
computeConstants(_typeProvider, _context.typeSystem, _declaredVariables,
_constants.toList(), _analysisOptions.experimentStatus);
}
void _computeHints(FileState file, CompilationUnit unit) {
if (file.source == null) {
return;
}
AnalysisErrorListener errorListener = _getErrorListener(file);
ErrorReporter errorReporter = _getErrorReporter(file);
unit.accept(new DeadCodeVerifier(errorReporter, unit.featureSet,
typeSystem: _context.typeSystem));
// Dart2js analysis.
if (_analysisOptions.dart2jsHint) {
unit.accept(new Dart2JSVerifier(errorReporter));
}
unit.accept(new BestPracticesVerifier(
errorReporter, _typeProvider, _libraryElement, unit, file.content,
typeSystem: _context.typeSystem,
inheritanceManager: _inheritance,
resourceProvider: _resourceProvider,
analysisOptions: _context.analysisOptions));
unit.accept(new OverrideVerifier(
_inheritance,
_libraryElement,
errorReporter,
));
new ToDoFinder(errorReporter).findIn(unit);
// Verify imports.
{
ImportsVerifier verifier = new ImportsVerifier();
verifier.addImports(unit);
_usedImportedElementsList.forEach(verifier.removeUsedElements);
verifier.generateDuplicateImportHints(errorReporter);
verifier.generateDuplicateShownHiddenNameHints(errorReporter);
verifier.generateUnusedImportHints(errorReporter);
verifier.generateUnusedShownNameHints(errorReporter);
}
// Unused local elements.
{
UsedLocalElements usedElements =
new UsedLocalElements.merge(_usedLocalElementsList);
UnusedLocalElementsVerifier visitor =
new UnusedLocalElementsVerifier(errorListener, usedElements);
unit.accept(visitor);
}
//
// Find code that uses features from an SDK version that does not satisfy
// the SDK constraints specified in analysis options.
//
var sdkVersionConstraint = _analysisOptions.sdkVersionConstraint;
if (sdkVersionConstraint != null) {
SdkConstraintVerifier verifier = new SdkConstraintVerifier(
errorReporter, _libraryElement, _typeProvider, sdkVersionConstraint);
unit.accept(verifier);
}
}
void _computeLints(FileState file, LinterContextUnit currentUnit,
List<LinterContextUnit> allUnits) {
var unit = currentUnit.unit;
if (file.source == null) {
return;
}
ErrorReporter errorReporter = _getErrorReporter(file);
var nodeRegistry = new NodeLintRegistry(_analysisOptions.enableTiming);
var visitors = <AstVisitor>[];
var context = LinterContextImpl(allUnits, currentUnit, _declaredVariables,
_typeProvider, _typeSystem, _inheritance, _analysisOptions);
for (Linter linter in _analysisOptions.lintRules) {
linter.reporter = errorReporter;
if (linter is NodeLintRule) {
(linter as NodeLintRule).registerNodeProcessors(nodeRegistry, context);
} else {
AstVisitor visitor = linter.getVisitor();
if (visitor != null) {
if (_analysisOptions.enableTiming) {
var timer = lintRegistry.getTimer(linter);
visitor = new TimedAstVisitor(visitor, timer);
}
visitors.add(visitor);
}
}
}
// Run lints that handle specific node types.
unit.accept(new LinterVisitor(
nodeRegistry, ExceptionHandlingDelegatingAstVisitor.logException));
// Run visitor based lints.
if (visitors.isNotEmpty) {
AstVisitor visitor = new ExceptionHandlingDelegatingAstVisitor(
visitors, ExceptionHandlingDelegatingAstVisitor.logException);
unit.accept(visitor);
}
}
void _computeVerifyErrors(FileState file, CompilationUnit unit) {
if (file.source == null) {
return;
}
RecordingErrorListener errorListener = _getErrorListener(file);
CodeChecker checker = new CodeChecker(
_typeProvider,
_context.typeSystem,
_inheritance,
errorListener,
_analysisOptions,
);
checker.visitCompilationUnit(unit);
ErrorReporter errorReporter = _getErrorReporter(file);
//
// Validate the directives.
//
_validateUriBasedDirectives(file, unit);
//
// Use the ConstantVerifier to compute errors.
//
_computeConstantErrors(errorReporter, unit);
//
// Compute inheritance and override errors.
//
var inheritanceOverrideVerifier = new InheritanceOverrideVerifier(
_context.typeSystem, _inheritance, errorReporter);
inheritanceOverrideVerifier.verifyUnit(unit);
//
// Use the ErrorVerifier to compute errors.
//
ErrorVerifier errorVerifier = new ErrorVerifier(
errorReporter, _libraryElement, _typeProvider, _inheritance, false);
unit.accept(errorVerifier);
}
/**
* Return a subset of the given [errors] that are not marked as ignored in
* the [file].
*/
List<AnalysisError> _filterIgnoredErrors(
FileState file, List<AnalysisError> errors) {
if (errors.isEmpty) {
return errors;
}
IgnoreInfo ignoreInfo = _fileToIgnoreInfo[file];
if (!ignoreInfo.hasIgnores) {
return errors;
}
LineInfo lineInfo = _fileToLineInfo[file];
bool isIgnored(AnalysisError error) {
int errorLine = lineInfo.getLocation(error.offset).lineNumber;
String errorCode = error.errorCode.name.toLowerCase();
return ignoreInfo.ignoredAt(errorCode, errorLine);
}
return errors.where((AnalysisError e) => !isIgnored(e)).toList();
}
/// Find constants to compute.
void _findConstants(CompilationUnit unit) {
ConstantFinder constantFinder = new ConstantFinder();
unit.accept(constantFinder);
_libraryConstants.addAll(constantFinder.constantsToCompute);
_constants.addAll(constantFinder.constantsToCompute);
var dependenciesFinder = new ConstantExpressionsDependenciesFinder();
unit.accept(dependenciesFinder);
_constants.addAll(dependenciesFinder.dependencies);
}
RecordingErrorListener _getErrorListener(FileState file) =>
_errorListeners.putIfAbsent(file, () => new RecordingErrorListener());
ErrorReporter _getErrorReporter(FileState file) {
return _errorReporters.putIfAbsent(file, () {
RecordingErrorListener listener = _getErrorListener(file);
return new ErrorReporter(listener, file.source);
});
}
/**
* Return the name of the library that the given part is declared to be a
* part of, or `null` if the part does not contain a part-of directive.
*/
_NameOrSource _getPartLibraryNameOrUri(Source partSource,
CompilationUnit partUnit, List<Directive> directivesToResolve) {
for (Directive directive in partUnit.directives) {
if (directive is PartOfDirective) {
directivesToResolve.add(directive);
LibraryIdentifier libraryName = directive.libraryName;
if (libraryName != null) {
return new _NameOrSource(libraryName.name, null);
}
String uri = directive.uri?.stringValue;
if (uri != null) {
Source librarySource = _sourceFactory.resolveUri(partSource, uri);
if (librarySource != null) {
return new _NameOrSource(null, librarySource);
}
}
}
}
return null;
}
bool _isExistingSource(Source source) {
for (var file in _library.directReferencedFiles) {
if (file.uri == source.uri) {
return file.exists;
}
}
return false;
}
/**
* Return `true` if the given [source] is a library.
*/
bool _isLibrarySource(Source source) {
return _isLibraryUri(source.uri);
}
/**
* Return a new parsed unresolved [CompilationUnit].
*/
CompilationUnit _parse(FileState file) {
AnalysisErrorListener errorListener = _getErrorListener(file);
String content = file.content;
CompilationUnit unit = file.parse(errorListener);
LineInfo lineInfo = unit.lineInfo;
_fileToLineInfo[file] = lineInfo;
_fileToIgnoreInfo[file] = IgnoreInfo.calculateIgnores(content, lineInfo);
return unit;
}
void _resolveDirectives(Map<FileState, CompilationUnit> units) {
CompilationUnit definingCompilationUnit = units[_library];
definingCompilationUnit.element = _libraryElement.definingCompilationUnit;
bool matchNodeElement(Directive node, Element element) {
return node.keyword.offset == element.nameOffset;
}
ErrorReporter libraryErrorReporter = _getErrorReporter(_library);
LibraryIdentifier libraryNameNode;
var seenPartSources = new Set<Source>();
var directivesToResolve = <Directive>[];
int partIndex = 0;
for (Directive directive in definingCompilationUnit.directives) {
if (directive is LibraryDirective) {
libraryNameNode = directive.name;
directivesToResolve.add(directive);
} else if (directive is ImportDirective) {
for (ImportElement importElement in _libraryElement.imports) {
if (matchNodeElement(directive, importElement)) {
directive.element = importElement;
directive.prefix?.staticElement = importElement.prefix;
Source source = importElement.importedLibrary?.source;
if (source != null && !_isLibrarySource(source)) {
libraryErrorReporter.reportErrorForNode(
CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY,
directive.uri,
[directive.uri]);
}
}
}
} else if (directive is ExportDirective) {
for (ExportElement exportElement in _libraryElement.exports) {
if (matchNodeElement(directive, exportElement)) {
directive.element = exportElement;
Source source = exportElement.exportedLibrary?.source;
if (source != null && !_isLibrarySource(source)) {
libraryErrorReporter.reportErrorForNode(
CompileTimeErrorCode.EXPORT_OF_NON_LIBRARY,
directive.uri,
[directive.uri]);
}
}
}
} else if (directive is PartDirective) {
StringLiteral partUri = directive.uri;
FileState partFile = _library.partedFiles[partIndex];
CompilationUnit partUnit = units[partFile];
CompilationUnitElement partElement = _libraryElement.parts[partIndex];
partUnit.element = partElement;
directive.element = partElement;
partIndex++;
Source partSource = directive.uriSource;
if (partSource == null) {
continue;
}
//
// Validate that the part source is unique in the library.
//
if (!seenPartSources.add(partSource)) {
libraryErrorReporter.reportErrorForNode(
CompileTimeErrorCode.DUPLICATE_PART, partUri, [partSource.uri]);
}
//
// Validate that the part contains a part-of directive with the same
// name or uri as the library.
//
if (_isExistingSource(partSource)) {
_NameOrSource nameOrSource = _getPartLibraryNameOrUri(
partSource, partUnit, directivesToResolve);
if (nameOrSource == null) {
libraryErrorReporter.reportErrorForNode(
CompileTimeErrorCode.PART_OF_NON_PART,
partUri,
[partUri.toSource()]);
} else {
String name = nameOrSource.name;
if (name != null) {
if (libraryNameNode == null) {
libraryErrorReporter.reportErrorForNode(
ResolverErrorCode.PART_OF_UNNAMED_LIBRARY, partUri, [name]);
} else if (libraryNameNode.name != name) {
libraryErrorReporter.reportErrorForNode(
StaticWarningCode.PART_OF_DIFFERENT_LIBRARY,
partUri,
[libraryNameNode.name, name]);
}
} else {
Source source = nameOrSource.source;
if (source != _library.source) {
libraryErrorReporter.reportErrorForNode(
StaticWarningCode.PART_OF_DIFFERENT_LIBRARY,
partUri,
[_library.uriStr, source.uri]);
}
}
}
}
}
}
// TODO(brianwilkerson) Report the error
// ResolverErrorCode.MISSING_LIBRARY_DIRECTIVE_WITH_PART
//
// Resolve the relevant directives to the library element.
//
for (Directive directive in directivesToResolve) {
directive.element = _libraryElement;
}
// TODO(scheglov) remove DirectiveResolver class
}
void _resolveFile(FileState file, CompilationUnit unit) {
Source source = file.source;
if (source == null) {
return;
}
RecordingErrorListener errorListener = _getErrorListener(file);
CompilationUnitElement unitElement = unit.declaredElement;
// TODO(scheglov) Hack: set types for top-level variables
// Otherwise TypeResolverVisitor will set declared types, and because we
// don't run InferStaticVariableTypeTask, we will stuck with these declared
// types. And we don't need to run this task - resynthesized elements have
// inferred types.
for (var e in unitElement.topLevelVariables) {
if (!e.isSynthetic) {
e.type;
}
}
timerLibraryAnalyzerSplicer.start();
new DeclarationResolver().resolve(unit, unitElement);
timerLibraryAnalyzerSplicer.stop();
unit.accept(new AstRewriteVisitor(_context.typeSystem, _libraryElement,
source, _typeProvider, errorListener,
nameScope: _libraryScope));
new TypeParameterBoundsResolver(_context.typeSystem, _libraryElement,
source, errorListener, unit.featureSet)
.resolveTypeBounds(unit);
unit.accept(new TypeResolverVisitor(
_libraryElement, source, _typeProvider, errorListener,
featureSet: unit.featureSet));
unit.accept(new VariableResolverVisitor(
_libraryElement, source, _typeProvider, errorListener,
nameScope: _libraryScope));
unit.accept(new PartialResolverVisitor(
_inheritance,
_libraryElement,
source,
_typeProvider,
AnalysisErrorListener.NULL_LISTENER,
unit.featureSet));
// Nothing for RESOLVED_UNIT8?
// Nothing for RESOLVED_UNIT9?
// Nothing for RESOLVED_UNIT10?
FlowAnalysisHelper flowAnalysisHelper;
if (unit.featureSet.isEnabled(Feature.non_nullable)) {
flowAnalysisHelper =
FlowAnalysisHelper(_context.typeSystem, unit, _testingData != null);
_testingData?.recordFlowAnalysisResult(
file.uri, flowAnalysisHelper.result);
}
unit.accept(new ResolverVisitor(
_inheritance, _libraryElement, source, _typeProvider, errorListener,
featureSet: unit.featureSet, flowAnalysisHelper: flowAnalysisHelper));
}
/**
* Return the result of resolve the given [uriContent], reporting errors
* against the [uriLiteral].
*/
Source _resolveUri(FileState file, bool isImport, StringLiteral uriLiteral,
String uriContent) {
UriValidationCode code =
UriBasedDirectiveImpl.validateUri(isImport, uriLiteral, uriContent);
if (code == null) {
try {
Uri.parse(uriContent);
} on FormatException {
return null;
}
return _sourceFactory.resolveUri(file.source, uriContent);
} else if (code == UriValidationCode.URI_WITH_DART_EXT_SCHEME) {
return null;
} else if (code == UriValidationCode.URI_WITH_INTERPOLATION) {
_getErrorReporter(file).reportErrorForNode(
CompileTimeErrorCode.URI_WITH_INTERPOLATION, uriLiteral);
return null;
} else if (code == UriValidationCode.INVALID_URI) {
_getErrorReporter(file).reportErrorForNode(
CompileTimeErrorCode.INVALID_URI, uriLiteral, [uriContent]);
return null;
}
return null;
}
void _resolveUriBasedDirectives(FileState file, CompilationUnit unit) {
for (Directive directive in unit.directives) {
if (directive is UriBasedDirective) {
StringLiteral uriLiteral = directive.uri;
String uriContent = uriLiteral.stringValue?.trim();
directive.uriContent = uriContent;
Source defaultSource = _resolveUri(
file, directive is ImportDirective, uriLiteral, uriContent);
directive.uriSource = defaultSource;
}
}
}
/// Validate that the feature set associated with the compilation [unit] is
/// the same as the [expectedSet] of features supported by the library.
void _validateFeatureSet(CompilationUnit unit, FeatureSet expectedSet) {
FeatureSet actualSet = unit.featureSet;
if (actualSet != expectedSet) {
// TODO(brianwilkerson) Generate a diagnostic.
}
}
/**
* Check the given [directive] to see if the referenced source exists and
* report an error if it does not.
*/
void _validateUriBasedDirective(
FileState file, UriBasedDirectiveImpl directive) {
Source source = directive.uriSource;
if (source != null) {
if (_isExistingSource(source)) {
return;
}
} else {
// Don't report errors already reported by ParseDartTask.resolveDirective
// TODO(scheglov) we don't use this task here
if (directive.validate() != null) {
return;
}
}
StringLiteral uriLiteral = directive.uri;
CompileTimeErrorCode errorCode = CompileTimeErrorCode.URI_DOES_NOT_EXIST;
if (_isGenerated(source)) {
errorCode = CompileTimeErrorCode.URI_HAS_NOT_BEEN_GENERATED;
}
_getErrorReporter(file)
.reportErrorForNode(errorCode, uriLiteral, [directive.uriContent]);
}
/**
* Check each directive in the given [unit] to see if the referenced source
* exists and report an error if it does not.
*/
void _validateUriBasedDirectives(FileState file, CompilationUnit unit) {
for (Directive directive in unit.directives) {
if (directive is UriBasedDirective) {
_validateUriBasedDirective(file, directive);
}
}
}
/**
* Return `true` if the given [source] refers to a file that is assumed to be
* generated.
*/
static bool _isGenerated(Source source) {
if (source == null) {
return false;
}
// TODO(brianwilkerson) Generalize this mechanism.
const List<String> suffixes = const <String>[
'.g.dart',
'.pb.dart',
'.pbenum.dart',
'.pbserver.dart',
'.pbjson.dart',
'.template.dart'
];
String fullName = source.fullName;
for (String suffix in suffixes) {
if (fullName.endsWith(suffix)) {
return true;
}
}
return false;
}
}
/**
* Analysis result for single file.
*/
class UnitAnalysisResult {
final FileState file;
final CompilationUnit unit;
final List<AnalysisError> errors;
UnitAnalysisResult(this.file, this.unit, this.errors);
}
/**
* Either the name or the source associated with a part-of directive.
*/
class _NameOrSource {
final String name;
final Source source;
_NameOrSource(this.name, this.source);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/file_tracker.dart | // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/src/dart/analysis/file_state.dart';
import 'package:analyzer/src/dart/analysis/performance_logger.dart';
/**
* Callback used by [FileTracker] to report to its client that files have been
* added, changed, or removed, and therefore more analysis may be necessary.
* [path] is the path of the file that was added, changed, or removed,
* or `null` if multiple files were added, changed, or removed.
*/
typedef void FileTrackerChangeHook(String path);
/**
* Maintains the file system state needed by the analysis driver, as well as
* information about files that have changed and the impact of those changes.
*
* Three related sets of files are tracked: "added files" is the set of files
* for which the client would like analysis. "changed files" is the set of
* files which is known to have changed, but for which we have not yet measured
* the impact of the change. "pending files" is the subset of "added files"
* which might have been impacted by a change, and thus need analysis.
*
* Provides methods for updating the file system state in response to changes.
*/
class FileTracker {
/**
* Callback invoked whenever a change occurs that may require the client to
* perform analysis.
*/
final FileTrackerChangeHook _changeHook;
/**
* The logger to write performed operations and performance to.
*/
final PerformanceLog _logger;
/**
* The current file system state.
*/
final FileSystemState _fsState;
/**
* The set of added files.
*/
final addedFiles = new LinkedHashSet<String>();
/**
* The set of files were reported as changed through [changeFile] and not
* checked for actual changes yet.
*/
final _changedFiles = new LinkedHashSet<String>();
/**
* The set of files that are currently scheduled for analysis, which were
* reported as changed through [changeFile].
*/
var _pendingChangedFiles = new LinkedHashSet<String>();
/**
* The set of files that are currently scheduled for analysis, which directly
* import a changed file.
*/
var _pendingImportFiles = new LinkedHashSet<String>();
/**
* The set of files that are currently scheduled for analysis, which have an
* error or a warning, which might be fixed by a changed file.
*/
var _pendingErrorFiles = new LinkedHashSet<String>();
/**
* The set of files that are currently scheduled for analysis, and don't
* have any special relation with changed files.
*/
var _pendingFiles = new LinkedHashSet<String>();
FileTracker(this._logger, this._fsState, this._changeHook);
/**
* Returns the path to exactly one that needs analysis. Throws a [StateError]
* if no files need analysis.
*/
String get anyPendingFile {
if (_pendingChangedFiles.isNotEmpty) {
return _pendingChangedFiles.first;
}
if (_pendingImportFiles.isNotEmpty) {
return _pendingImportFiles.first;
}
if (_pendingErrorFiles.isNotEmpty) {
return _pendingErrorFiles.first;
}
return _pendingFiles.first;
}
/**
* Returns a boolean indicating whether there are any files that have changed,
* but for which the impact of the changes hasn't been measured.
*/
bool get hasChangedFiles => _changedFiles.isNotEmpty;
/**
* Return `true` if there are changed files that need analysis.
*/
bool get hasPendingChangedFiles => _pendingChangedFiles.isNotEmpty;
/**
* Return `true` if there are files that have an error or warning, and that
* need analysis.
*/
bool get hasPendingErrorFiles => _pendingErrorFiles.isNotEmpty;
/**
* Returns a boolean indicating whether there are any files that need
* analysis.
*/
bool get hasPendingFiles {
return hasPendingChangedFiles ||
hasPendingImportFiles ||
hasPendingErrorFiles ||
_pendingFiles.isNotEmpty;
}
/**
* Return `true` if there are files that directly import a changed file that
* need analysis.
*/
bool get hasPendingImportFiles => _pendingImportFiles.isNotEmpty;
/**
* Returns a count of how many files need analysis.
*/
int get numberOfPendingFiles {
return _pendingChangedFiles.length +
_pendingImportFiles.length +
_pendingErrorFiles.length +
_pendingFiles.length;
}
/**
* Adds the given [path] to the set of "added files".
*/
void addFile(String path) {
_fsState.markFileForReading(path);
addedFiles.add(path);
_pendingFiles.add(path);
_changeHook(path);
}
/**
* Adds the given [paths] to the set of "added files".
*/
void addFiles(Iterable<String> paths) {
addedFiles.addAll(paths);
_pendingFiles.addAll(paths);
_changeHook(null);
}
/**
* Adds the given [path] to the set of "changed files".
*/
void changeFile(String path) {
_changedFiles.add(path);
if (addedFiles.contains(path)) {
_pendingChangedFiles.add(path);
}
_fsState.markFileForReading(path);
_changeHook(path);
}
/**
* Removes the given [path] from the set of "pending files".
*
* Should be called after the client has analyzed a file.
*/
void fileWasAnalyzed(String path) {
_pendingChangedFiles.remove(path);
_pendingImportFiles.remove(path);
_pendingErrorFiles.remove(path);
_pendingFiles.remove(path);
}
/**
* Returns a boolean indicating whether the given [path] points to a file that
* requires analysis.
*/
bool isFilePending(String path) {
return _pendingChangedFiles.contains(path) ||
_pendingImportFiles.contains(path) ||
_pendingErrorFiles.contains(path) ||
_pendingFiles.contains(path);
}
/**
* Removes the given [path] from the set of "added files".
*/
void removeFile(String path) {
addedFiles.remove(path);
_pendingChangedFiles.remove(path);
_pendingImportFiles.remove(path);
_pendingErrorFiles.remove(path);
_pendingFiles.remove(path);
// TODO(paulberry): removing the path from [fsState] and re-analyzing all
// files seems extreme.
_fsState.removeFile(path);
_pendingFiles.addAll(addedFiles);
_changeHook(path);
}
/**
* Schedule all added files for analysis.
*/
void scheduleAllAddedFiles() {
_pendingFiles.addAll(addedFiles);
}
/**
* Verify the API signature for the file with the given [path], and decide
* which linked libraries should be invalidated, and files reanalyzed.
*/
FileState verifyApiSignature(String path) {
return _logger.run('Verify API signature of $path', () {
_logger.writeln('Work in ${_fsState.contextName}');
bool anyApiChanged = false;
List<FileState> files = _fsState.getFilesForPath(path);
for (FileState file in files) {
bool apiChanged = file.refresh();
if (apiChanged) {
anyApiChanged = true;
}
}
if (anyApiChanged) {
_logger.writeln('API signatures mismatch found.');
// TODO(scheglov) schedule analysis of only affected files
var pendingChangedFiles = new LinkedHashSet<String>();
var pendingImportFiles = new LinkedHashSet<String>();
var pendingErrorFiles = new LinkedHashSet<String>();
var pendingFiles = new LinkedHashSet<String>();
// Add the changed file.
if (addedFiles.contains(path)) {
pendingChangedFiles.add(path);
}
// Add files that directly import the changed file.
for (String addedPath in addedFiles) {
FileState addedFile = _fsState.getFileForPath(addedPath);
for (FileState changedFile in files) {
if (addedFile.importedFiles.contains(changedFile)) {
pendingImportFiles.add(addedPath);
}
}
}
// Add files with errors or warnings that might be fixed.
for (String addedPath in addedFiles) {
FileState addedFile = _fsState.getFileForPath(addedPath);
if (addedFile.hasErrorOrWarning) {
pendingErrorFiles.add(addedPath);
}
}
// Add all previous pending files.
pendingChangedFiles.addAll(_pendingChangedFiles);
pendingImportFiles.addAll(_pendingImportFiles);
pendingErrorFiles.addAll(_pendingErrorFiles);
pendingFiles.addAll(_pendingFiles);
// Add all the rest.
pendingFiles.addAll(addedFiles);
// Replace pending files.
_pendingChangedFiles = pendingChangedFiles;
_pendingImportFiles = pendingImportFiles;
_pendingErrorFiles = pendingErrorFiles;
_pendingFiles = pendingFiles;
}
return files[0];
});
}
/**
* If at least one file is in the "changed files" set, determines the impact
* of the change, updates the set of pending files, and returns `true`.
*
* If no files are in the "changed files" set, returns `false`.
*/
bool verifyChangedFilesIfNeeded() {
// Verify all changed files one at a time.
if (_changedFiles.isNotEmpty) {
String path = _changedFiles.first;
_changedFiles.remove(path);
// If the file has not been accessed yet, we either will eventually read
// it later while analyzing one of the added files, or don't need it.
if (_fsState.knownFilePaths.contains(path)) {
verifyApiSignature(path);
}
return true;
}
return false;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/unlinked_api_signature.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/summary/api_signature.dart';
/// Return the bytes of the unlinked API signature of the given [unit].
///
/// If API signatures of two units are different, they may have different APIs.
List<int> computeUnlinkedApiSignature(CompilationUnit unit) {
var computer = _UnitApiSignatureComputer();
computer.compute(unit);
return computer.signature.toByteList();
}
class _UnitApiSignatureComputer {
final ApiSignature signature = ApiSignature();
void addClassOrMixin(ClassOrMixinDeclaration node) {
addTokens(node.beginToken, node.leftBracket);
bool hasConstConstructor = node.members
.any((m) => m is ConstructorDeclaration && m.constKeyword != null);
signature.addInt(node.members.length);
for (var member in node.members) {
if (member is ConstructorDeclaration) {
var lastInitializer = member.constKeyword != null &&
member.initializers != null &&
member.initializers.isNotEmpty
? member.initializers.last
: null;
addTokens(
member.beginToken,
(lastInitializer ?? member.parameters ?? member.name).endToken,
);
} else if (member is FieldDeclaration) {
var variableList = member.fields;
addVariables(
member,
variableList,
!member.isStatic && variableList.isFinal && hasConstConstructor,
);
} else if (member is MethodDeclaration) {
addTokens(
member.beginToken,
(member.parameters ?? member.name).endToken,
);
signature.addBool(member.body is EmptyFunctionBody);
addFunctionBodyModifiers(member.body);
} else {
addNode(member);
}
}
addToken(node.rightBracket);
}
void addFunctionBodyModifiers(FunctionBody node) {
signature.addBool(node.isSynchronous);
signature.addBool(node.isGenerator);
}
void addNode(AstNode node) {
addTokens(node.beginToken, node.endToken);
}
void addToken(Token token) {
signature.addString(token.lexeme);
}
/// Appends tokens from [begin] (including), to [end] (also including).
void addTokens(Token begin, Token end) {
if (begin is CommentToken) {
begin = (begin as CommentToken).parent;
}
Token token = begin;
while (token != null) {
addToken(token);
if (token == end) {
break;
}
var nextToken = token.next;
// Stop if EOF.
if (nextToken == token) {
break;
}
token = nextToken;
}
}
void addVariables(
AstNode node,
VariableDeclarationList variableList,
bool includeInitializers,
) {
if (variableList.type == null ||
variableList.isConst ||
includeInitializers) {
addTokens(node.beginToken, node.endToken);
} else {
addTokens(node.beginToken, variableList.type.endToken);
signature.addInt(variableList.variables.length);
for (var variable in variableList.variables) {
addTokens(variable.beginToken, variable.name.endToken);
signature.addBool(variable.initializer != null);
addToken(variable.endToken.next); // `,` or `;`
}
}
}
void compute(CompilationUnit unit) {
signature.addInt(unit.directives.length);
unit.directives.forEach(addNode);
signature.addInt(unit.declarations.length);
for (var declaration in unit.declarations) {
if (declaration is ClassOrMixinDeclaration) {
addClassOrMixin(declaration);
} else if (declaration is FunctionDeclaration) {
var functionExpression = declaration.functionExpression;
addTokens(
declaration.beginToken,
(functionExpression.parameters ?? declaration.name).endToken,
);
addFunctionBodyModifiers(functionExpression.body);
} else if (declaration is TopLevelVariableDeclaration) {
addVariables(declaration, declaration.variables, false);
} else {
addNode(declaration);
}
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/dependency/reference_collector.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/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/analysis/dependency/node.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:meta/meta.dart';
/// Collector of information about external nodes referenced by a node.
///
/// The workflow for using it is that the library builder creates a new
/// instance, fills it with names of import prefixes using [addImportPrefix].
/// Then for each node defined in the library, [collect] is called with
/// corresponding AST nodes to record references to external names, and
/// construct the API or implementation [Dependencies].
class ReferenceCollector {
/// Local scope inside the node, containing local names such as parameters,
/// local variables, local functions, local type parameters, etc.
final _LocalScopes _localScopes = _LocalScopes();
/// The list of names that are referenced without any prefix, neither an
/// import prefix, nor a target expression.
_NameSet _unprefixedReferences = _NameSet();
/// The list of names that are referenced using an import prefix.
///
/// It is filled by [addImportPrefix] and shared across all nodes.
List<_ReferencedImportPrefixedNames> _importPrefixedReferences = [];
/// The list of names that are referenced with `super`.
_NameSet _superReferences = _NameSet();
/// The set of referenced class members.
_ClassMemberReferenceSet _memberReferences = _ClassMemberReferenceSet();
/// Record that the [name] is a name of an import prefix.
///
/// So, when we see code like `prefix.foo` we know that `foo` should be
/// resolved in the import scope that corresponds to `prefix` (unless the
/// name `prefix` is shadowed by a local declaration).
void addImportPrefix(String name) {
assert(_localScopes.isEmpty);
for (var import in _importPrefixedReferences) {
if (import.prefix == name) {
return;
}
}
_importPrefixedReferences.add(_ReferencedImportPrefixedNames(name));
}
/// Construct and return a new [Dependencies] with the given [tokenSignature]
/// and all recorded references to external nodes in the given AST nodes.
Dependencies collect(List<int> tokenSignature,
{String enclosingClassName,
String thisNodeName,
List<ConstructorInitializer> constructorInitializers,
TypeName enclosingSuperClass,
Expression expression,
ExtendsClause extendsClause,
FormalParameterList formalParameters,
FormalParameterList formalParametersForImpl,
FunctionBody functionBody,
ImplementsClause implementsClause,
OnClause onClause,
ConstructorName redirectedConstructor,
TypeAnnotation returnType,
TypeName superClass,
TypeAnnotation type,
TypeParameterList typeParameters,
TypeParameterList typeParameters2,
WithClause withClause}) {
_localScopes.enter();
// The name of the node shadows any external names.
if (enclosingClassName != null) {
_localScopes.add(enclosingClassName);
}
if (thisNodeName != null) {
_localScopes.add(thisNodeName);
}
// Add type parameters first, they might be referenced later.
_visitTypeParameterList(typeParameters);
_visitTypeParameterList(typeParameters2);
// Parts of classes.
_visitTypeAnnotation(extendsClause?.superclass);
_visitTypeAnnotation(superClass);
_visitTypeAnnotations(withClause?.mixinTypes);
_visitTypeAnnotations(onClause?.superclassConstraints);
_visitTypeAnnotations(implementsClause?.interfaces);
// Parts of executables.
_visitFormalParameterList(formalParameters);
_visitFormalParameterListImpl(formalParametersForImpl);
_visitTypeAnnotation(returnType);
_visitFunctionBody(functionBody);
// Parts of constructors.
_visitConstructorInitializers(enclosingSuperClass, constructorInitializers);
_visitConstructorName(redirectedConstructor);
// Parts of variables.
_visitTypeAnnotation(type);
_visitExpression(expression);
_localScopes.exit();
var unprefixedReferencedNames = _unprefixedReferences.toList();
_unprefixedReferences = _NameSet();
var importPrefixCount = 0;
for (var i = 0; i < _importPrefixedReferences.length; i++) {
var import = _importPrefixedReferences[i];
if (import.names.isNotEmpty) {
importPrefixCount++;
}
}
var importPrefixes = List<String>(importPrefixCount);
var importPrefixedReferencedNames = List<List<String>>(importPrefixCount);
var importIndex = 0;
for (var i = 0; i < _importPrefixedReferences.length; i++) {
var import = _importPrefixedReferences[i];
if (import.names.isNotEmpty) {
importPrefixes[importIndex] = import.prefix;
importPrefixedReferencedNames[importIndex] = import.names.toList();
importIndex++;
}
import.clear();
}
var superReferencedNames = _superReferences.toList();
_superReferences = _NameSet();
var classMemberReferences = _memberReferences.toList();
_memberReferences = _ClassMemberReferenceSet();
return Dependencies(
tokenSignature,
unprefixedReferencedNames,
importPrefixes,
importPrefixedReferencedNames,
superReferencedNames,
classMemberReferences,
);
}
/// Return the collector for the import prefix with the given [name].
_ReferencedImportPrefixedNames _importPrefix(String name) {
assert(!_localScopes.contains(name));
for (var i = 0; i < _importPrefixedReferences.length; i++) {
var references = _importPrefixedReferences[i];
if (references.prefix == name) {
return references;
}
}
return null;
}
void _recordClassMemberReference(DartType targetType, String name) {
if (targetType is InterfaceType) {
_memberReferences.add(targetType.element, name);
}
}
/// Record a new unprefixed name reference.
void _recordUnprefixedReference(String name) {
assert(!_localScopes.contains(name));
_unprefixedReferences.add(name);
}
void _visitAdjacentStrings(AdjacentStrings node) {
var strings = node.strings;
for (var i = 0; i < strings.length; i++) {
var string = strings[i];
_visitExpression(string);
}
}
void _visitArgumentList(ArgumentList node) {
var arguments = node.arguments;
for (var i = 0; i < arguments.length; i++) {
var argument = arguments[i];
_visitExpression(argument);
}
}
void _visitAssignmentExpression(AssignmentExpression node) {
var assignmentType = node.operator.type;
_visitExpression(node.leftHandSide,
get: assignmentType != TokenType.EQ, set: true);
_visitExpression(node.rightHandSide);
if (assignmentType != TokenType.EQ &&
assignmentType != TokenType.QUESTION_QUESTION_EQ) {
var operatorType = operatorFromCompoundAssignment(assignmentType);
_recordClassMemberReference(
node.leftHandSide.staticType,
operatorType.lexeme,
);
}
}
void _visitBinaryExpression(BinaryExpression node) {
var operatorName = node.operator.lexeme;
var leftOperand = node.leftOperand;
if (leftOperand is SuperExpression) {
_superReferences.add(operatorName);
} else {
_visitExpression(leftOperand);
_recordClassMemberReference(leftOperand.staticType, operatorName);
}
_visitExpression(node.rightOperand);
}
void _visitBlock(Block node) {
if (node == null) return;
_visitStatements(node.statements);
}
void _visitCascadeExpression(CascadeExpression node) {
_visitExpression(node.target);
var sections = node.cascadeSections;
for (var i = 0; i < sections.length; i++) {
var section = sections[i];
_visitExpression(section);
}
}
void _visitCollectionElement(CollectionElement node) {
if (node == null) {
return;
} else if (node is Expression) {
_visitExpression(node);
} else if (node is ForElement) {
_visitForLoopParts(node.forLoopParts);
_visitCollectionElement(node.body);
} else if (node is IfElement) {
_visitExpression(node.condition);
_visitCollectionElement(node.thenElement);
_visitCollectionElement(node.elseElement);
} else if (node is MapLiteralEntry) {
_visitExpression(node.key);
_visitExpression(node.value);
} else if (node is SpreadElement) {
_visitExpression(node.expression);
} else {
throw UnimplementedError('(${node.runtimeType}) $node');
}
}
/// Record reference to the constructor of the [type] with the given [name].
void _visitConstructor(TypeName type, SimpleIdentifier name) {
_visitTypeAnnotation(type);
if (name != null) {
_recordClassMemberReference(type.type, name.name);
} else {
_recordClassMemberReference(type.type, '');
}
}
void _visitConstructorInitializers(
TypeName superClass, List<ConstructorInitializer> initializers) {
if (initializers == null) return;
for (var i = 0; i < initializers.length; i++) {
var initializer = initializers[i];
if (initializer is AssertInitializer) {
_visitExpression(initializer.condition);
_visitExpression(initializer.message);
} else if (initializer is ConstructorFieldInitializer) {
_visitExpression(initializer.expression);
} else if (initializer is SuperConstructorInvocation) {
_visitConstructor(superClass, initializer.constructorName);
_visitArgumentList(initializer.argumentList);
} else if (initializer is RedirectingConstructorInvocation) {
_visitArgumentList(initializer.argumentList);
// Strongly speaking, we reference a field of the enclosing class.
//
// However the current plan is to resolve the whole library on a change.
// So, we will resolve the enclosing constructor anyway.
} else {
throw UnimplementedError('(${initializer.runtimeType}) $initializer');
}
}
}
void _visitConstructorName(ConstructorName node) {
if (node == null) return;
_visitConstructor(node.type, node.name);
}
void _visitExpression(Expression node, {bool get: true, bool set: false}) {
if (node == null) return;
if (node is AdjacentStrings) {
_visitAdjacentStrings(node);
} else if (node is AsExpression) {
_visitExpression(node.expression);
_visitTypeAnnotation(node.type);
} else if (node is AssignmentExpression) {
_visitAssignmentExpression(node);
} else if (node is AwaitExpression) {
_visitExpression(node.expression);
} else if (node is BinaryExpression) {
_visitBinaryExpression(node);
} else if (node is BooleanLiteral) {
// no dependencies
} else if (node is CascadeExpression) {
_visitCascadeExpression(node);
} else if (node is ConditionalExpression) {
_visitExpression(node.condition);
_visitExpression(node.thenExpression);
_visitExpression(node.elseExpression);
} else if (node is DoubleLiteral) {
// no dependencies
} else if (node is FunctionExpression) {
_visitFunctionExpression(node);
} else if (node is FunctionExpressionInvocation) {
_visitExpression(node.function);
_visitTypeArguments(node.typeArguments);
_visitArgumentList(node.argumentList);
} else if (node is IndexExpression) {
_visitIndexExpression(node, get: get, set: set);
} else if (node is InstanceCreationExpression) {
_visitInstanceCreationExpression(node);
} else if (node is IntegerLiteral) {
// no dependencies
} else if (node is IsExpression) {
_visitExpression(node.expression);
_visitTypeAnnotation(node.type);
} else if (node is ListLiteral) {
_visitListLiteral(node);
} else if (node is MethodInvocation) {
_visitMethodInvocation(node);
} else if (node is NamedExpression) {
_visitExpression(node.expression);
} else if (node is NullLiteral) {
// no dependencies
} else if (node is ParenthesizedExpression) {
_visitExpression(node.expression);
} else if (node is PostfixExpression) {
_visitPostfixExpression(node);
} else if (node is PrefixExpression) {
_visitPrefixExpression(node);
} else if (node is PrefixedIdentifier) {
_visitPrefixedIdentifier(node);
} else if (node is PropertyAccess) {
_visitPropertyAccess(node, get: get, set: set);
} else if (node is RethrowExpression) {
// no dependencies
} else if (node is SetOrMapLiteral) {
_visitSetOrMapLiteral(node);
} else if (node is SimpleIdentifier) {
_visitSimpleIdentifier(node, get: get, set: set);
} else if (node is SimpleStringLiteral) {
// no dependencies
} else if (node is StringInterpolation) {
_visitStringInterpolation(node);
} else if (node is SymbolLiteral) {
// no dependencies
} else if (node is ThisExpression) {
// Strongly speaking, "this" should add dependencies.
// Just like any class reference, it depends on the class hierarchy.
// For example adding a new type to the `implements` clause might make
// it OK to pass `this` as an argument of an invocation.
//
// However the current plan is to resolve the whole library on a change.
// So, we will resolve all implementations that reference `this`.
} else if (node is ThrowExpression) {
_visitExpression(node.expression);
} else {
throw UnimplementedError('(${node.runtimeType}) $node');
}
}
void _visitExpressionList(NodeList<Expression> nodes) {
for (Expression node in nodes) {
_visitExpression(node);
}
}
void _visitForLoopParts(ForLoopParts node) {
if (node == null) {
return;
} else if (node is ForPartsWithDeclarations) {
_visitVariableList(node.variables);
_visitExpression(node.condition);
_visitExpressionList(node.updaters);
} else if (node is ForPartsWithExpression) {
_visitExpression(node.initialization);
_visitExpression(node.condition);
_visitExpressionList(node.updaters);
} else if (node is ForEachPartsWithDeclaration) {
var variable = node.loopVariable;
_visitTypeAnnotation(variable.type);
_visitExpression(node.iterable);
_localScopes.add(variable.identifier.name);
} else if (node is ForEachPartsWithIdentifier) {
_visitExpression(node.identifier);
_visitExpression(node.iterable);
} else {
throw UnimplementedError('(${node.runtimeType}) $node');
}
}
void _visitFormalParameterList(FormalParameterList node) {
if (node == null) return;
var parameters = node.parameters;
for (var i = 0; i < parameters.length; i++) {
FormalParameter parameter = parameters[i];
if (parameter is DefaultFormalParameter) {
DefaultFormalParameter defaultParameter = parameter;
parameter = defaultParameter.parameter;
}
if (parameter.identifier != null) {
_localScopes.add(parameter.identifier.name);
}
if (parameter is FieldFormalParameter) {
_visitTypeAnnotation(parameter.type);
// Strongly speaking, we reference a field of the enclosing class.
//
// However the current plan is to resolve the whole library on a change.
// So, we will resolve the enclosing constructor anyway.
} else if (parameter is FunctionTypedFormalParameter) {
_visitTypeAnnotation(parameter.returnType);
_visitFormalParameterList(parameter.parameters);
} else if (parameter is SimpleFormalParameter) {
_visitTypeAnnotation(parameter.type);
} else {
throw StateError('Unexpected: (${parameter.runtimeType}) $parameter');
}
}
}
void _visitFormalParameterListImpl(FormalParameterList node) {
if (node == null) return;
var parameters = node.parameters;
for (var i = 0; i < parameters.length; i++) {
FormalParameter parameter = parameters[i];
if (parameter is DefaultFormalParameter) {
DefaultFormalParameter defaultParameter = parameter;
_visitExpression(defaultParameter.defaultValue);
parameter = defaultParameter.parameter;
}
if (parameter.identifier != null) {
_localScopes.add(parameter.identifier.name);
}
}
}
void _visitForStatement(ForStatement node) {
_localScopes.enter();
_visitForLoopParts(node.forLoopParts);
_visitStatement(node.body);
_localScopes.exit();
}
void _visitFunctionBody(FunctionBody node) {
if (node == null) return;
if (node is BlockFunctionBody) {
_visitStatement(node.block);
} else if (node is EmptyFunctionBody) {
return;
} else if (node is ExpressionFunctionBody) {
_visitExpression(node.expression);
} else {
throw UnimplementedError('(${node.runtimeType}) $node');
}
}
void _visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
var function = node.functionDeclaration;
_visitTypeAnnotation(function.returnType);
_visitFunctionExpression(function.functionExpression);
}
void _visitFunctionExpression(FunctionExpression node) {
_localScopes.enter();
_visitTypeParameterList(node.typeParameters);
_visitFormalParameterList(node.parameters);
_visitFormalParameterListImpl(node.parameters);
_visitFunctionBody(node.body);
_localScopes.exit();
}
void _visitIndexExpression(IndexExpression node,
{@required bool get, @required bool set}) {
var target = node.target;
if (target == null) {
// no dependencies
} else if (target is SuperExpression) {
if (get) {
_superReferences.add('[]');
}
if (set) {
_superReferences.add('[]=');
}
} else {
_visitExpression(target);
var targetType = target.staticType;
if (get) {
_recordClassMemberReference(targetType, '[]');
}
if (set) {
_recordClassMemberReference(targetType, '[]=');
}
}
_visitExpression(node.index);
}
void _visitInstanceCreationExpression(InstanceCreationExpression node) {
_visitConstructorName(node.constructorName);
_visitArgumentList(node.argumentList);
}
void _visitListLiteral(ListLiteral node) {
_visitTypeArguments(node.typeArguments);
var elements = node.elements;
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
_visitCollectionElement(element);
}
}
void _visitMethodInvocation(MethodInvocation node) {
var realTarget = node.realTarget;
if (realTarget == null) {
_visitExpression(node.methodName);
} else if (realTarget is SuperExpression) {
_superReferences.add(node.methodName.name);
} else {
_visitExpression(node.target);
_recordClassMemberReference(
realTarget.staticType,
node.methodName.name,
);
}
_visitTypeArguments(node.typeArguments);
_visitArgumentList(node.argumentList);
}
void _visitPostfixExpression(PostfixExpression node) {
_visitExpression(node.operand);
var operator = node.operator.type;
if (operator == TokenType.MINUS_MINUS) {
_recordClassMemberReference(node.operand.staticType, '-');
} else if (operator == TokenType.PLUS_PLUS) {
_recordClassMemberReference(node.operand.staticType, '+');
} else {
throw UnimplementedError('$operator');
}
}
void _visitPrefixedIdentifier(PrefixedIdentifier node) {
var prefix = node.prefix;
var prefixElement = prefix.staticElement;
if (prefixElement is PrefixElement) {
var prefixName = prefix.name;
var importPrefix = _importPrefix(prefixName);
importPrefix.add(node.identifier.name);
} else {
_visitExpression(prefix);
_recordClassMemberReference(prefix.staticType, node.identifier.name);
}
}
void _visitPrefixExpression(PrefixExpression node) {
_visitExpression(node.operand);
var operatorName = node.operator.lexeme;
if (operatorName == '-') operatorName = 'unary-';
_recordClassMemberReference(node.operand.staticType, operatorName);
}
void _visitPropertyAccess(PropertyAccess node,
{@required bool get, @required bool set}) {
var realTarget = node.realTarget;
var name = node.propertyName.name;
if (realTarget is SuperExpression) {
if (get) {
_superReferences.add(name);
}
if (set) {
_superReferences.add('$name=');
}
} else {
_visitExpression(node.target);
if (get) {
_recordClassMemberReference(realTarget.staticType, name);
}
if (set) {
_recordClassMemberReference(realTarget.staticType, '$name=');
}
}
}
void _visitSetOrMapLiteral(SetOrMapLiteral node) {
_visitTypeArguments(node.typeArguments);
var elements = node.elements;
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
_visitCollectionElement(element);
}
}
void _visitSimpleIdentifier(SimpleIdentifier node,
{@required bool get, @required bool set}) {
if (node.isSynthetic) return;
var name = node.name;
if (_localScopes.contains(name) ||
name == 'void' ||
name == 'dynamic' ||
name == 'Never') {
return;
}
if (get) {
_recordUnprefixedReference(name);
}
if (set) {
_recordUnprefixedReference('$name=');
}
}
void _visitStatement(Statement node) {
if (node == null) return;
if (node is AssertStatement) {
_visitExpression(node.condition);
_visitExpression(node.message);
} else if (node is Block) {
_visitBlock(node);
} else if (node is BreakStatement) {
// nothing
} else if (node is ContinueStatement) {
// nothing
} else if (node is DoStatement) {
_visitStatement(node.body);
_visitExpression(node.condition);
} else if (node is EmptyStatement) {
// nothing
} else if (node is ExpressionStatement) {
_visitExpression(node.expression);
} else if (node is ForStatement) {
_visitForStatement(node);
} else if (node is FunctionDeclarationStatement) {
_visitFunctionDeclarationStatement(node);
} else if (node is IfStatement) {
_visitExpression(node.condition);
_visitStatement(node.thenStatement);
_visitStatement(node.elseStatement);
} else if (node is LabeledStatement) {
_visitStatement(node.statement);
} else if (node is ReturnStatement) {
_visitExpression(node.expression);
} else if (node is SwitchStatement) {
_visitSwitchStatement(node);
} else if (node is TryStatement) {
_visitTryStatement(node);
} else if (node is VariableDeclarationStatement) {
_visitVariableList(node.variables);
} else if (node is WhileStatement) {
_visitExpression(node.condition);
_visitStatement(node.body);
} else if (node is YieldStatement) {
_visitExpression(node.expression);
} else {
throw UnimplementedError('(${node.runtimeType}) $node');
}
}
void _visitStatements(List<Statement> statements) {
_localScopes.enter();
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement is FunctionDeclarationStatement) {
_localScopes.add(statement.functionDeclaration.name.name);
} else if (statement is VariableDeclarationStatement) {
var variables = statement.variables.variables;
for (int i = 0; i < variables.length; i++) {
_localScopes.add(variables[i].name.name);
}
}
}
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
_visitStatement(statement);
}
_localScopes.exit();
}
void _visitStringInterpolation(StringInterpolation node) {
var elements = node.elements;
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element is InterpolationExpression) {
_visitExpression(element.expression);
}
}
}
void _visitSwitchStatement(SwitchStatement node) {
_visitExpression(node.expression);
var members = node.members;
for (var i = 0; i < members.length; i++) {
var member = members[i];
if (member is SwitchCase) {
_visitExpression(member.expression);
}
_visitStatements(member.statements);
}
}
void _visitTryStatement(TryStatement node) {
_visitBlock(node.body);
var catchClauses = node.catchClauses;
for (var i = 0; i < catchClauses.length; i++) {
var catchClause = catchClauses[i];
_visitTypeAnnotation(catchClause.exceptionType);
_localScopes.enter();
var exceptionParameter = catchClause.exceptionParameter;
if (exceptionParameter != null) {
_localScopes.add(exceptionParameter.name);
}
var stackTraceParameter = catchClause.stackTraceParameter;
if (stackTraceParameter != null) {
_localScopes.add(stackTraceParameter.name);
}
_visitBlock(catchClause.body);
_localScopes.exit();
}
_visitBlock(node.finallyBlock);
}
void _visitTypeAnnotation(TypeAnnotation node) {
if (node == null) return;
if (node is GenericFunctionType) {
_localScopes.enter();
if (node.typeParameters != null) {
var typeParameters = node.typeParameters.typeParameters;
for (var i = 0; i < typeParameters.length; i++) {
var typeParameter = typeParameters[i];
_localScopes.add(typeParameter.name.name);
}
for (var i = 0; i < typeParameters.length; i++) {
var typeParameter = typeParameters[i];
_visitTypeAnnotation(typeParameter.bound);
}
}
_visitTypeAnnotation(node.returnType);
_visitFormalParameterList(node.parameters);
_localScopes.exit();
} else if (node is TypeName) {
var identifier = node.name;
_visitExpression(identifier);
_visitTypeArguments(node.typeArguments);
} else {
throw UnimplementedError('(${node.runtimeType}) $node');
}
}
void _visitTypeAnnotations(List<TypeAnnotation> typeAnnotations) {
if (typeAnnotations == null) return;
for (var i = 0; i < typeAnnotations.length; i++) {
var typeAnnotation = typeAnnotations[i];
_visitTypeAnnotation(typeAnnotation);
}
}
void _visitTypeArguments(TypeArgumentList node) {
if (node == null) return;
_visitTypeAnnotations(node.arguments);
}
void _visitTypeParameterList(TypeParameterList node) {
if (node == null) return;
var typeParameters = node.typeParameters;
// Define all type parameters in the local scope.
for (var i = 0; i < typeParameters.length; i++) {
var typeParameter = typeParameters[i];
_localScopes.add(typeParameter.name.name);
}
// Record bounds.
for (var i = 0; i < typeParameters.length; i++) {
var typeParameter = typeParameters[i];
_visitTypeAnnotation(typeParameter.bound);
}
}
void _visitVariableList(VariableDeclarationList node) {
if (node == null) return;
_visitTypeAnnotation(node.type);
var variables = node.variables;
for (int i = 0; i < variables.length; i++) {
var variable = variables[i];
_localScopes.add(variable.name.name);
_visitExpression(variable.initializer);
}
}
}
/// The sorted set of [ClassMemberReference]s.
class _ClassMemberReferenceSet {
final List<ClassMemberReference> references = [];
void add(ClassElement class_, String name) {
var target = LibraryQualifiedName(class_.library.source.uri, class_.name);
var reference = ClassMemberReference(target, name);
if (!references.contains(reference)) {
references.add(reference);
}
}
/// Return the sorted list of unique class member references.
List<ClassMemberReference> toList() {
references.sort(ClassMemberReference.compare);
return references;
}
}
/// The stack of names that are defined in a local scope inside the node,
/// such as parameters, local variables, local functions, local type
/// parameters, etc.
class _LocalScopes {
/// The stack of name sets.
final List<_NameSet> scopes = [];
bool get isEmpty => scopes.isEmpty;
/// Add the given [name] to the current local scope.
void add(String name) {
scopes.last.add(name);
}
/// Return whether the given [name] is defined in one of the local scopes.
bool contains(String name) {
for (var i = 0; i < scopes.length; i++) {
if (scopes[i].contains(name)) {
return true;
}
}
return false;
}
/// Enter a new local scope, e.g. a block, or a type parameter scope.
void enter() {
scopes.add(_NameSet());
}
/// Exit the current local scope.
void exit() {
scopes.removeLast();
}
}
class _NameSet {
final List<String> names = [];
bool get isNotEmpty => names.isNotEmpty;
void add(String name) {
// TODO(scheglov) consider just adding, but toList() sort and unique
if (!contains(name)) {
names.add(name);
}
}
bool contains(String name) => names.contains(name);
List<String> toList() {
names.sort(_compareStrings);
return names;
}
static int _compareStrings(String first, String second) {
return first.compareTo(second);
}
}
class _ReferencedImportPrefixedNames {
final String prefix;
_NameSet names = _NameSet();
_ReferencedImportPrefixedNames(this.prefix);
void add(String name) {
names.add(name);
}
void clear() {
names = _NameSet();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/dependency/node.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:typed_data';
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:convert/convert.dart';
/// The reference to a class member.
class ClassMemberReference {
/// The target class name.
///
/// This is different from the class that actually turned out to define
/// the referenced member at the time of recording this reference. So, we
/// will notice added overrides in the target class, or anywhere in between.
final LibraryQualifiedName target;
/// The name referenced in the [target].
final String name;
@override
final int hashCode;
ClassMemberReference(this.target, this.name)
: hashCode = JenkinsSmiHash.hash2(target.hashCode, name.hashCode);
@override
bool operator ==(other) {
return other is ClassMemberReference &&
other.target == target &&
other.name == name;
}
@override
String toString() {
return '($target, $name)';
}
static int compare(ClassMemberReference first, ClassMemberReference second) {
var result = LibraryQualifiedName.compare(first.target, second.target);
if (result != 0) return result;
return first.name.compareTo(second.name);
}
}
/// The dependencies of the API or implementation portion of a node.
class Dependencies {
static final none = Dependencies([], [], [], [], [], []);
/// The token signature of this portion of the node. It depends on all
/// tokens that might affect the node API or implementation resolution.
final List<int> tokenSignature;
/// The names that appear unprefixed in this portion of the node, and are
/// not defined locally in the node. Locally defined names themselves
/// depend on some non-local nodes, which will also recorded here.
///
/// This list is sorted.
final List<String> unprefixedReferencedNames;
/// The names of import prefixes used to reference names in this node.
///
/// This list is sorted.
final List<String> importPrefixes;
/// The names referenced by this node with the import prefix at the
/// corresponding index in [importPrefixes].
///
/// This list is sorted.
final List<List<String>> importPrefixedReferencedNames;
/// The names that appear prefixed with `super` in this portion of the node.
///
/// This list is sorted.
final List<String> superReferencedNames;
/// The class members referenced in this portion of the node.
///
/// This list is sorted.
final List<ClassMemberReference> classMemberReferences;
/// All referenced nodes, computed from [unprefixedReferencedNames],
/// [importPrefixedReferencedNames], and [classMemberReferences].
List<Node> referencedNodes;
/// The transitive signature of this portion of the node, computed using
/// the [tokenSignature] of this node, and API signatures of the
/// [referencedNodes].
List<int> transitiveSignature;
Dependencies(
this.tokenSignature,
this.unprefixedReferencedNames,
this.importPrefixes,
this.importPrefixedReferencedNames,
this.superReferencedNames,
this.classMemberReferences);
String get tokenSignatureHex => hex.encode(tokenSignature);
}
/// A name qualified by a library URI.
class LibraryQualifiedName {
/// The URI of the defining library.
/// Not `null`.
final Uri libraryUri;
/// The name of this name object.
/// If the name starts with `_`, then the name is private.
/// Names of setters end with `=`.
final String name;
/// Whether this name is private, and its [name] starts with `_`.
final bool isPrivate;
/// The cached, pre-computed hash code.
@override
final int hashCode;
factory LibraryQualifiedName(Uri libraryUri, String name) {
var isPrivate = name.startsWith('_');
var hashCode = JenkinsSmiHash.hash2(libraryUri.hashCode, name.hashCode);
return LibraryQualifiedName._internal(
libraryUri, name, isPrivate, hashCode);
}
LibraryQualifiedName._internal(
this.libraryUri, this.name, this.isPrivate, this.hashCode);
@override
bool operator ==(Object other) {
return other is LibraryQualifiedName &&
other.hashCode == hashCode &&
name == other.name &&
libraryUri == other.libraryUri;
}
/// Whether this name us accessible for the library with the given
/// [libraryUri], i.e. when the name is public, or is defined in a library
/// with the same URI.
bool isAccessibleFor(Uri libraryUri) {
return !isPrivate || this.libraryUri == libraryUri;
}
@override
String toString() => '$libraryUri::$name';
/// Compare given names by their raw names.
///
/// This method should be used only for sorting, it does not follow the
/// complete semantics of [==] and [hashCode].
static int compare(LibraryQualifiedName first, LibraryQualifiedName second) {
return first.name.compareTo(second.name);
}
}
/// A dependency node - anything that has a name, and can be referenced.
class Node {
/// The API or implementation signature used in [Dependencies]
/// as a marker that this node is changed, explicitly because its token
/// signature changed, or implicitly - because it references a changed node.
static final changedSignature = Uint8List.fromList([0xDE, 0xAD, 0xBE, 0xEF]);
final LibraryQualifiedName name;
final NodeKind kind;
/// Dependencies that affect the API of the node, so affect API or
/// implementation dependencies of the nodes that use this node.
final Dependencies api;
/// Additional (to the [api]) dependencies that affect only the
/// "implementation" of the node, e.g. the body of a method, but are not
/// visible outside of the node, and so don't affect any other nodes.
final Dependencies impl;
/// If the node is a class member, the node of the enclosing class.
/// Otherwise `null`.
final Node enclosingClass;
/// If the node is a class, the nodes of its type parameters.
/// Otherwise `null`.
List<Node> classTypeParameters;
/// If the node is a class, the sorted list of members in this class.
/// Otherwise `null`.
List<Node> classMembers;
Node(this.name, this.kind, this.api, this.impl,
{this.enclosingClass, this.classTypeParameters});
/// Return the node that can be referenced by the given [name] from the
/// library with the given [libraryUri].
Node getClassMember(Uri libraryUri, String name) {
// TODO(scheglov) The list is sorted, use this fact to search faster.
// TODO(scheglov) Collect superclass members here or outside.
for (var i = 0; i < classMembers.length; ++i) {
var member = classMembers[i];
var memberName = member.name;
if (memberName.name == name && memberName.isAccessibleFor(libraryUri)) {
return member;
}
}
return null;
}
/// Set new class members for this class.
void setClassMembers(List<Node> newClassMembers) {
classMembers = newClassMembers;
}
/// Set new class type parameters for this class.
void setTypeParameters(List<Node> newTypeParameters) {
classTypeParameters = newTypeParameters;
}
@override
String toString() {
if (enclosingClass != null) {
return '$enclosingClass::${name.name}';
}
return name.toString();
}
/// Compare given nodes by their names.
static int compare(Node first, Node second) {
return LibraryQualifiedName.compare(first.name, second.name);
}
}
/// Kinds of nodes.
enum NodeKind {
CLASS,
CLASS_TYPE_ALIAS,
CONSTRUCTOR,
ENUM,
FUNCTION,
FUNCTION_TYPE_ALIAS,
GENERIC_TYPE_ALIAS,
GETTER,
METHOD,
MIXIN,
SETTER,
TYPE_PARAMETER,
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/analysis/dependency/library_builder.dart | // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/src/dart/analysis/dependency/node.dart';
import 'package:analyzer/src/dart/analysis/dependency/reference_collector.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/summary/api_signature.dart';
/// Build [Library] that describes nodes and dependencies of the library
/// with the given [uri] and [units].
///
/// If the [units] are just parsed, then only token signatures and referenced
/// names of nodes can be computed. If the [units] are fully resolved, then
/// also class member references can be recorded.
Library buildLibrary(Uri uri, List<CompilationUnit> units) {
return _LibraryBuilder(uri, units).build();
}
/// The `show` or `hide` namespace combinator.
class Combinator {
final bool isShow;
final List<String> names;
Combinator(this.isShow, this.names);
@override
String toString() {
if (isShow) {
return 'show ' + names.join(', ');
} else {
return 'hide ' + names.join(', ');
}
}
}
/// The `export` directive.
class Export {
/// The absolute URI of the exported library.
final Uri uri;
/// The list of namespace combinators to apply, not `null`.
final List<Combinator> combinators;
Export(this.uri, this.combinators);
@override
String toString() {
return 'Export(uri: $uri, combinators: $combinators)';
}
}
/// The `import` directive.
class Import {
/// The absolute URI of the imported library.
final Uri uri;
/// The import prefix, or `null` if not specified.
final String prefix;
/// The list of namespace combinators to apply, not `null`.
final List<Combinator> combinators;
Import(this.uri, this.prefix, this.combinators);
@override
String toString() {
return 'Import(uri: $uri, prefix: $prefix, combinators: $combinators)';
}
}
/// The collection of imports, exports, and top-level nodes.
class Library {
/// The absolute URI of the library.
final Uri uri;
/// The list of imports in this library.
final List<Import> imports;
/// The list of exports in this library.
final List<Export> exports;
/// The list of libraries that correspond to the [imports].
List<Library> importedLibraries;
/// The list of top-level nodes defined in the library.
///
/// This list is sorted.
final List<Node> declaredNodes;
/// The map of [declaredNodes], used for fast search.
/// TODO(scheglov) consider using binary search instead.
final Map<LibraryQualifiedName, Node> declaredNodeMap = {};
/// The list of nodes exported from this library, either using `export`
/// directives, or declared in this library.
///
/// This list is sorted.
List<Node> exportedNodes;
/// The map of nodes that are visible in the library, either imported,
/// or declared in this library.
///
/// TODO(scheglov) support for imports with prefixes
Map<String, Node> libraryScope;
Library(this.uri, this.imports, this.exports, this.declaredNodes) {
for (var node in declaredNodes) {
declaredNodeMap[node.name] = node;
}
}
@override
String toString() => '$uri';
}
class _LibraryBuilder {
/// The URI of the library.
final Uri uri;
/// The units of the library, parsed or fully resolved.
final List<CompilationUnit> units;
/// The instance of the referenced names, class members collector.
final ReferenceCollector referenceCollector = ReferenceCollector();
/// The list of imports in the library.
final List<Import> imports = [];
/// The list of exports in the library.
final List<Export> exports = [];
/// The top-level nodes declared in the library.
final List<Node> declaredNodes = [];
/// The precomputed signature of the [uri].
///
/// It is mixed into every API token signature, because for example even
/// though types of two functions might be the same, their locations
/// are different.
List<int> uriSignature;
/// The name of the enclosing class name, or `null` if outside a class.
String enclosingClassName;
/// The super class of the enclosing class, or `null` if outside a class.
TypeName enclosingSuperClass;
/// The precomputed signature of the enclosing class name, or `null` if
/// outside a class.
///
/// It is mixed into every API token signature of every class member, because
/// for example even though types of two methods might be the same, their
/// locations are different.
List<int> enclosingClassNameSignature;
/// The node of the enclosing class.
Node enclosingClass;
_LibraryBuilder(this.uri, this.units);
Library build() {
uriSignature = (ApiSignature()..addString(uri.toString())).toByteList();
_addImports();
_addExports();
for (var unit in units) {
_addUnit(unit);
}
declaredNodes.sort(Node.compare);
return Library(uri, imports, exports, declaredNodes);
}
void _addClassOrMixin(ClassOrMixinDeclaration node) {
enclosingClassName = node.name.name;
if (node is ClassDeclaration) {
enclosingSuperClass = node.extendsClause?.superclass;
}
enclosingClassNameSignature =
(ApiSignature()..addString(enclosingClassName)).toByteList();
var apiTokenSignature = _computeTokenSignature(
node.beginToken,
node.leftBracket,
);
Dependencies api;
if (node is ClassDeclaration) {
api = referenceCollector.collect(
apiTokenSignature,
thisNodeName: enclosingClassName,
typeParameters: node.typeParameters,
extendsClause: node.extendsClause,
withClause: node.withClause,
implementsClause: node.implementsClause,
);
} else if (node is MixinDeclaration) {
api = referenceCollector.collect(
apiTokenSignature,
thisNodeName: enclosingClassName,
typeParameters: node.typeParameters,
onClause: node.onClause,
implementsClause: node.implementsClause,
);
} else {
throw UnimplementedError('(${node.runtimeType}) $node');
}
enclosingClass = Node(
LibraryQualifiedName(uri, enclosingClassName),
node is MixinDeclaration ? NodeKind.MIXIN : NodeKind.CLASS,
api,
Dependencies.none,
);
var hasConstConstructor = node.members.any(
(m) => m is ConstructorDeclaration && m.constKeyword != null,
);
// TODO(scheglov) do we need type parameters at all?
List<Node> classTypeParameters;
if (node.typeParameters != null) {
classTypeParameters = <Node>[];
for (var typeParameter in node.typeParameters.typeParameters) {
var api = referenceCollector.collect(
_computeNodeTokenSignature(typeParameter),
enclosingClassName: enclosingClassName,
thisNodeName: typeParameter.name.name,
type: typeParameter.bound,
);
classTypeParameters.add(Node(
LibraryQualifiedName(uri, typeParameter.name.name),
NodeKind.TYPE_PARAMETER,
api,
Dependencies.none,
enclosingClass: enclosingClass,
));
}
classTypeParameters.sort(Node.compare);
enclosingClass.setTypeParameters(classTypeParameters);
}
var classMembers = <Node>[];
var hasConstructor = false;
for (var member in node.members) {
if (member is ConstructorDeclaration) {
hasConstructor = true;
_addConstructor(classMembers, member);
} else if (member is FieldDeclaration) {
_addVariables(
classMembers,
member.metadata,
member.fields,
hasConstConstructor,
);
} else if (member is MethodDeclaration) {
_addMethod(classMembers, member);
} else {
throw UnimplementedError('(${member.runtimeType}) $member');
}
}
if (node is ClassDeclaration && !hasConstructor) {
classMembers.add(Node(
LibraryQualifiedName(uri, ''),
NodeKind.CONSTRUCTOR,
Dependencies.none,
Dependencies.none,
enclosingClass: enclosingClass,
));
}
classMembers.sort(Node.compare);
enclosingClass.setClassMembers(classMembers);
declaredNodes.add(enclosingClass);
enclosingClassName = null;
enclosingClassNameSignature = null;
enclosingSuperClass = null;
enclosingClass = null;
}
void _addClassTypeAlias(ClassTypeAlias node) {
var apiTokenSignature = _computeNodeTokenSignature(node);
var api = referenceCollector.collect(
apiTokenSignature,
typeParameters: node.typeParameters,
superClass: node.superclass,
withClause: node.withClause,
implementsClause: node.implementsClause,
);
declaredNodes.add(Node(
LibraryQualifiedName(uri, node.name.name),
NodeKind.CLASS_TYPE_ALIAS,
api,
Dependencies.none,
));
}
void _addConstructor(List<Node> classMembers, ConstructorDeclaration node) {
var builder = _newApiSignatureBuilder();
_appendMetadataTokens(builder, node.metadata);
_appendFormalParametersTokens(builder, node.parameters);
var apiTokenSignature = builder.toByteList();
var api = referenceCollector.collect(
apiTokenSignature,
enclosingClassName: enclosingClassName,
formalParameters: node.parameters,
);
var implTokenSignature = _computeNodeTokenSignature(node.body);
var impl = referenceCollector.collect(
implTokenSignature,
enclosingClassName: enclosingClassName,
enclosingSuperClass: enclosingSuperClass,
formalParametersForImpl: node.parameters,
constructorInitializers: node.initializers,
redirectedConstructor: node.redirectedConstructor,
functionBody: node.body,
);
classMembers.add(Node(
LibraryQualifiedName(uri, node.name?.name ?? ''),
NodeKind.CONSTRUCTOR,
api,
impl,
enclosingClass: enclosingClass,
));
}
void _addEnum(EnumDeclaration node) {
var enumTokenSignature = _newApiSignatureBuilder().toByteList();
var enumNode = Node(
LibraryQualifiedName(uri, node.name.name),
NodeKind.ENUM,
Dependencies(enumTokenSignature, [], [], [], [], []),
Dependencies.none,
);
Dependencies fieldDependencies;
{
var builder = _newApiSignatureBuilder();
builder.addString(node.name.name);
_appendTokens(builder, node.leftBracket, node.rightBracket);
var tokenSignature = builder.toByteList();
fieldDependencies = Dependencies(tokenSignature, [], [], [], [], []);
}
var members = <Node>[];
for (var constant in node.constants) {
members.add(Node(
LibraryQualifiedName(uri, constant.name.name),
NodeKind.GETTER,
fieldDependencies,
Dependencies.none,
enclosingClass: enumNode,
));
}
members.add(Node(
LibraryQualifiedName(uri, 'index'),
NodeKind.GETTER,
fieldDependencies,
Dependencies.none,
enclosingClass: enumNode,
));
members.add(Node(
LibraryQualifiedName(uri, 'values'),
NodeKind.GETTER,
fieldDependencies,
Dependencies.none,
enclosingClass: enumNode,
));
members.sort(Node.compare);
enumNode.setClassMembers(members);
declaredNodes.add(enumNode);
}
/// Fill [exports] with information about exports.
void _addExports() {
for (var directive in units.first.directives) {
if (directive is ExportDirective) {
var refUri = directive.uri.stringValue;
var importUri = uri.resolve(refUri);
var combinators = _getCombinators(directive);
exports.add(Export(importUri, combinators));
}
}
}
void _addFunction(FunctionDeclaration node) {
var functionExpression = node.functionExpression;
var builder = _newApiSignatureBuilder();
_appendMetadataTokens(builder, node.metadata);
_appendNodeTokens(builder, node.returnType);
_appendNodeTokens(builder, functionExpression.typeParameters);
_appendFormalParametersTokens(builder, functionExpression.parameters);
var apiTokenSignature = builder.toByteList();
var rawName = node.name.name;
var name = LibraryQualifiedName(uri, node.isSetter ? '$rawName=' : rawName);
NodeKind kind;
if (node.isGetter) {
kind = NodeKind.GETTER;
} else if (node.isSetter) {
kind = NodeKind.SETTER;
} else {
kind = NodeKind.FUNCTION;
}
var api = referenceCollector.collect(
apiTokenSignature,
thisNodeName: node.name.name,
typeParameters: functionExpression.typeParameters,
formalParameters: functionExpression.parameters,
returnType: node.returnType,
);
var body = functionExpression.body;
var implTokenSignature = _computeNodeTokenSignature(body);
var impl = referenceCollector.collect(
implTokenSignature,
thisNodeName: node.name.name,
formalParametersForImpl: functionExpression.parameters,
functionBody: body,
);
declaredNodes.add(Node(name, kind, api, impl));
}
void _addFunctionTypeAlias(FunctionTypeAlias node) {
var builder = _newApiSignatureBuilder();
_appendMetadataTokens(builder, node.metadata);
_appendNodeTokens(builder, node.typeParameters);
_appendNodeTokens(builder, node.returnType);
_appendFormalParametersTokens(builder, node.parameters);
var apiTokenSignature = builder.toByteList();
var api = referenceCollector.collect(
apiTokenSignature,
thisNodeName: node.name.name,
typeParameters: node.typeParameters,
formalParameters: node.parameters,
returnType: node.returnType,
);
declaredNodes.add(Node(
LibraryQualifiedName(uri, node.name.name),
NodeKind.FUNCTION_TYPE_ALIAS,
api,
Dependencies.none,
));
}
void _addGenericTypeAlias(GenericTypeAlias node) {
var functionType = node.functionType;
var builder = _newApiSignatureBuilder();
_appendMetadataTokens(builder, node.metadata);
_appendNodeTokens(builder, node.typeParameters);
_appendNodeTokens(builder, functionType.returnType);
_appendNodeTokens(builder, functionType.typeParameters);
_appendFormalParametersTokens(builder, functionType.parameters);
var apiTokenSignature = builder.toByteList();
var api = referenceCollector.collect(
apiTokenSignature,
typeParameters: node.typeParameters,
typeParameters2: functionType.typeParameters,
formalParameters: functionType.parameters,
returnType: functionType.returnType,
);
declaredNodes.add(Node(
LibraryQualifiedName(uri, node.name.name),
NodeKind.GENERIC_TYPE_ALIAS,
api,
Dependencies.none,
));
}
/// Fill [imports] with information about imports.
void _addImports() {
var hasDartCoreImport = false;
for (var directive in units.first.directives) {
if (directive is ImportDirective) {
var refUri = directive.uri.stringValue;
var importUri = uri.resolve(refUri);
if (importUri.toString() == 'dart:core') {
hasDartCoreImport = true;
}
var combinators = _getCombinators(directive);
imports.add(Import(importUri, directive.prefix?.name, combinators));
if (directive.prefix != null) {
referenceCollector.addImportPrefix(directive.prefix.name);
}
}
}
if (!hasDartCoreImport) {
imports.add(Import(Uri.parse('dart:core'), null, []));
}
}
void _addMethod(List<Node> classMembers, MethodDeclaration node) {
var builder = _newApiSignatureBuilder();
_appendMetadataTokens(builder, node.metadata);
_appendNodeTokens(builder, node.returnType);
_appendNodeTokens(builder, node.typeParameters);
_appendFormalParametersTokens(builder, node.parameters);
var apiTokenSignature = builder.toByteList();
NodeKind kind;
if (node.isGetter) {
kind = NodeKind.GETTER;
} else if (node.isSetter) {
kind = NodeKind.SETTER;
} else {
kind = NodeKind.METHOD;
}
// TODO(scheglov) metadata, here and everywhere
var api = referenceCollector.collect(
apiTokenSignature,
enclosingClassName: enclosingClassName,
thisNodeName: node.name.name,
typeParameters: node.typeParameters,
formalParameters: node.parameters,
returnType: node.returnType,
);
var implTokenSignature = _computeNodeTokenSignature(node.body);
var impl = referenceCollector.collect(
implTokenSignature,
enclosingClassName: enclosingClassName,
thisNodeName: node.name.name,
formalParametersForImpl: node.parameters,
functionBody: node.body,
);
var name = LibraryQualifiedName(uri, node.name.name);
classMembers.add(
Node(name, kind, api, impl, enclosingClass: enclosingClass),
);
}
void _addUnit(CompilationUnit unit) {
for (var declaration in unit.declarations) {
if (declaration is ClassOrMixinDeclaration) {
_addClassOrMixin(declaration);
} else if (declaration is ClassTypeAlias) {
_addClassTypeAlias(declaration);
} else if (declaration is EnumDeclaration) {
_addEnum(declaration);
} else if (declaration is FunctionDeclaration) {
_addFunction(declaration);
} else if (declaration is FunctionTypeAlias) {
_addFunctionTypeAlias(declaration);
} else if (declaration is GenericTypeAlias) {
_addGenericTypeAlias(declaration);
} else if (declaration is TopLevelVariableDeclaration) {
_addVariables(
declaredNodes,
declaration.metadata,
declaration.variables,
false,
);
} else {
throw UnimplementedError('(${declaration.runtimeType}) $declaration');
}
}
}
void _addVariables(List<Node> variableNodes, List<Annotation> metadata,
VariableDeclarationList variables, bool appendInitializerToApi) {
if (variables.isConst || variables.type == null) {
appendInitializerToApi = true;
}
for (var variable in variables.variables) {
var initializer = variable.initializer;
var builder = _newApiSignatureBuilder();
builder.addInt(variables.isConst ? 1 : 0); // const flag
_appendMetadataTokens(builder, metadata);
_appendNodeTokens(builder, variables.type);
if (appendInitializerToApi) {
_appendNodeTokens(builder, initializer);
}
var apiTokenSignature = builder.toByteList();
var api = referenceCollector.collect(
apiTokenSignature,
enclosingClassName: enclosingClassName,
thisNodeName: variable.name.name,
type: variables.type,
expression: appendInitializerToApi ? initializer : null,
);
var implTokenSignature = _computeNodeTokenSignature(initializer);
var impl = referenceCollector.collect(
implTokenSignature,
enclosingClassName: enclosingClassName,
thisNodeName: variable.name.name,
expression: initializer,
);
var rawName = variable.name.name;
variableNodes.add(Node(
LibraryQualifiedName(uri, rawName),
NodeKind.GETTER,
api,
impl,
enclosingClass: enclosingClass,
));
if (!variables.isConst && !variables.isFinal) {
// Note that one set of dependencies is enough for body.
// So, the setter has empty "impl" dependencies.
variableNodes.add(
Node(
LibraryQualifiedName(uri, '$rawName='),
NodeKind.SETTER,
api,
Dependencies.none,
enclosingClass: enclosingClass,
),
);
}
}
}
/// Return the signature for all tokens of the [node].
List<int> _computeNodeTokenSignature(AstNode node) {
if (node == null) {
return const <int>[];
}
return _computeTokenSignature(node.beginToken, node.endToken);
}
/// Return the signature for tokens from [begin] to [end] (both including).
List<int> _computeTokenSignature(Token begin, Token end) {
var signature = _newApiSignatureBuilder();
_appendTokens(signature, begin, end);
return signature.toByteList();
}
/// Return a new signature builder, primed with the current context salts.
ApiSignature _newApiSignatureBuilder() {
var builder = ApiSignature();
builder.addBytes(uriSignature);
if (enclosingClassNameSignature != null) {
builder.addBytes(enclosingClassNameSignature);
}
return builder;
}
/// Append tokens of the given [parameters] to the [signature].
static void _appendFormalParametersTokens(
ApiSignature signature, FormalParameterList parameters) {
if (parameters == null) return;
for (var parameter in parameters.parameters) {
if (parameter.isRequiredPositional) {
signature.addInt(1);
} else if (parameter.isRequiredNamed) {
signature.addInt(4);
} else if (parameter.isOptionalPositional) {
signature.addInt(2);
} else if (parameter.isOptionalNamed) {
signature.addInt(3);
}
// If a simple not named parameter, we don't need its name.
// We should be careful to include also annotations.
if (parameter is SimpleFormalParameter && parameter.type != null) {
_appendTokens(
signature,
parameter.beginToken,
parameter.type.endToken,
);
continue;
}
// We don't know anything better than adding the whole parameter.
_appendNodeTokens(signature, parameter);
}
}
static void _appendMetadataTokens(
ApiSignature signature, List<Annotation> metadata) {
if (metadata != null) {
for (var annotation in metadata) {
_appendNodeTokens(signature, annotation);
}
}
}
/// Append tokens of the given [node] to the [signature].
static void _appendNodeTokens(ApiSignature signature, AstNode node) {
if (node != null) {
_appendTokens(signature, node.beginToken, node.endToken);
}
}
/// Append tokens from [begin] to [end] (both including) to the [signature].
static void _appendTokens(ApiSignature signature, Token begin, Token end) {
if (begin is CommentToken) {
begin = (begin as CommentToken).parent;
}
Token token = begin;
while (token != null) {
signature.addString(token.lexeme);
if (token == end) {
break;
}
var nextToken = token.next;
if (nextToken == token) {
break;
}
token = nextToken;
}
}
/// Return [Combinator]s for the given import or export [directive].
static List<Combinator> _getCombinators(NamespaceDirective directive) {
var combinators = <Combinator>[];
for (var combinator in directive.combinators) {
if (combinator is ShowCombinator) {
combinators.add(
Combinator(
true,
combinator.shownNames.map((id) => id.name).toList(),
),
);
}
if (combinator is HideCombinator) {
combinators.add(
Combinator(
false,
combinator.hiddenNames.map((id) => id.name).toList(),
),
);
}
}
return combinators;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/legacy_type_asserter.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:collection';
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/type.dart';
/// A visitor to assert that legacy libraries deal with legacy types.
///
/// Intended to be used via the static method
/// [LegacyTypeAsserter.assertLegacyTypes], inside an `assert()` node.
///
/// Has a defense against being accidentally run outside of an assert statement,
/// but that can be overridden if needed.
///
/// Checks that the static type of every node, as well as the elements of many
/// nodes, have legacy types, and asserts that the legacy types are deep legacy
/// types.
class LegacyTypeAsserter extends GeneralizingAstVisitor {
// TODO(mfairhurst): remove custom equality/hashCode once both use nullability
Set<DartType> visitedTypes = LinkedHashSet<DartType>(
equals: (a, b) =>
a == b &&
(a as TypeImpl).nullabilitySuffix ==
(b as TypeImpl).nullabilitySuffix,
hashCode: (a) =>
a.hashCode * 11 + (a as TypeImpl).nullabilitySuffix.hashCode);
LegacyTypeAsserter({bool requireIsDebug = true}) {
if (requireIsDebug) {
bool isDebug = false;
assert(() {
isDebug = true;
return true;
}());
if (!isDebug) {
throw UnsupportedError(
'Legacy type asserter is being run outside of a debug environment');
}
}
}
@override
visitClassMember(ClassMember node) {
final element = node.declaredElement;
if (element is ExecutableElement) {
_assertLegacyType(element?.type);
}
super.visitClassMember(node);
}
@override
visitCompilationUnit(CompilationUnit node) {
if (!node.featureSet.isEnabled(Feature.non_nullable)) {
super.visitCompilationUnit(node);
}
}
@override
visitDeclaredIdentifier(DeclaredIdentifier node) {
_assertLegacyType(node.declaredElement?.type);
super.visitDeclaredIdentifier(node);
}
@override
visitExpression(Expression e) {
_assertLegacyType(e.staticType);
super.visitExpression(e);
}
@override
visitFormalParameter(FormalParameter node) {
_assertLegacyType(node.declaredElement?.type);
super.visitFormalParameter(node);
}
@override
visitFunctionDeclaration(FunctionDeclaration node) {
_assertLegacyType(node.declaredElement?.type);
super.visitFunctionDeclaration(node);
}
@override
visitTypeAnnotation(TypeAnnotation node) {
_assertLegacyType(node.type);
super.visitTypeAnnotation(node);
}
@override
visitTypeName(TypeName node) {
_assertLegacyType(node.type);
super.visitTypeName(node);
}
@override
visitVariableDeclaration(VariableDeclaration node) {
_assertLegacyType(node.declaredElement?.type);
super.visitVariableDeclaration(node);
}
void _assertLegacyType(DartType type) {
if (type == null) {
return;
}
if (type.isDynamic || type.isVoid) {
return;
}
if (type.isBottom && type.isDartCoreNull) {
// Never?, which is ok.
//
// Note: we could allow Null? and Null, but we really should be able to
// guarantee that we are only working with Null*, so that's what this
// currently does.
return;
}
if (visitedTypes.contains(type)) {
return;
}
visitedTypes.add(type);
if (type is TypeParameterType) {
_assertLegacyType(type.bound);
} else if (type is InterfaceType) {
type.typeArguments.forEach(_assertLegacyType);
type.typeParameters
.map((param) => param.bound)
.forEach(_assertLegacyType);
} else if (type is FunctionType) {
_assertLegacyType(type.returnType);
type.parameters.map((param) => param.type).forEach(_assertLegacyType);
type.typeArguments.forEach(_assertLegacyType);
type.typeParameters
.map((param) => param.bound)
.forEach(_assertLegacyType);
}
if ((type as TypeImpl).nullabilitySuffix == NullabilitySuffix.star) {
return;
}
throw StateError('Expected all legacy types, but got '
'${(type as TypeImpl).toString(withNullability: true)} '
'(${type.runtimeType})');
}
static bool assertLegacyTypes(CompilationUnit compilationUnit) {
new LegacyTypeAsserter().visitCompilationUnit(compilationUnit);
return true;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/extension_member_resolver.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/dart/element/type_algebra.dart';
import 'package:analyzer/src/dart/resolver/resolution_result.dart';
import 'package:analyzer/src/dart/resolver/scope.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/type_system.dart';
class ExtensionMemberResolver {
final ResolverVisitor _resolver;
ExtensionMemberResolver(this._resolver);
DartType get _dynamicType => _typeProvider.dynamicType;
ErrorReporter get _errorReporter => _resolver.errorReporter;
Scope get _nameScope => _resolver.nameScope;
TypeProvider get _typeProvider => _resolver.typeProvider;
TypeSystem get _typeSystem => _resolver.typeSystem;
/// Return the most specific extension in the current scope for this [type],
/// that defines the member with the given [name].
///
/// If no applicable extensions, return [ResolutionResult.none].
///
/// If the match is ambiguous, report an error and return
/// [ResolutionResult.ambiguous].
ResolutionResult findExtension(
DartType type,
String name,
Expression target,
) {
var extensions = _getApplicable(type, name);
if (extensions.isEmpty) {
return ResolutionResult.none;
}
if (extensions.length == 1) {
return extensions[0].asResolutionResult;
}
var extension = _chooseMostSpecific(extensions);
if (extension != null) {
return extension.asResolutionResult;
}
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.AMBIGUOUS_EXTENSION_MEMBER_ACCESS,
target,
[
name,
extensions[0].extension.name,
extensions[1].extension.name,
],
);
return ResolutionResult.ambiguous;
}
/// Resolve the [name] (without `=`) to the corresponding getter and setter
/// members of the extension [node].
///
/// The [node] is fully resolved, and its type arguments are set.
ResolutionResult getOverrideMember(ExtensionOverride node, String name) {
ExtensionElement element = node.extensionName.staticElement;
ExecutableElement getter;
ExecutableElement setter;
if (name == '[]') {
getter = element.getMethod('[]');
setter = element.getMethod('[]=');
} else {
getter = element.getGetter(name) ?? element.getMethod(name);
setter = element.getSetter(name);
}
if (getter == null && setter == null) {
return ResolutionResult.none;
}
var substitution = Substitution.fromPairs(
element.typeParameters,
node.typeArgumentTypes,
);
var getterMember =
getter != null ? ExecutableMember.from2(getter, substitution) : null;
var setterMember =
setter != null ? ExecutableMember.from2(setter, substitution) : null;
return ResolutionResult(getter: getterMember, setter: setterMember);
}
/// Perform upward inference for the override.
void resolveOverride(ExtensionOverride node) {
var nodeImpl = node as ExtensionOverrideImpl;
var element = node.staticElement;
var typeParameters = element.typeParameters;
if (!_isValidContext(node)) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.EXTENSION_OVERRIDE_WITHOUT_ACCESS,
node,
);
nodeImpl.staticType = _dynamicType;
}
var arguments = node.argumentList.arguments;
if (arguments.length != 1) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.INVALID_EXTENSION_ARGUMENT_COUNT,
node.argumentList,
);
nodeImpl.typeArgumentTypes = _listOfDynamic(typeParameters);
nodeImpl.extendedType = _dynamicType;
return;
}
var receiverExpression = arguments[0];
var receiverType = receiverExpression.staticType;
var typeArgumentTypes = _inferTypeArguments(node, receiverType);
nodeImpl.typeArgumentTypes = typeArgumentTypes;
var substitution = Substitution.fromPairs(
typeParameters,
typeArgumentTypes,
);
nodeImpl.extendedType = substitution.substituteType(element.extendedType);
_checkTypeArgumentsMatchingBounds(
typeParameters,
node.typeArguments,
typeArgumentTypes,
substitution,
);
if (!_typeSystem.isAssignableTo(receiverType, node.extendedType)) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.EXTENSION_OVERRIDE_ARGUMENT_NOT_ASSIGNABLE,
receiverExpression,
[receiverType, node.extendedType],
);
}
}
/// Set the type context for the receiver of the override.
///
/// The context of the invocation that is made through the override does
/// not affect the type inference of the override and the receiver.
void setOverrideReceiverContextType(ExtensionOverride node) {
var element = node.staticElement;
var typeParameters = element.typeParameters;
var arguments = node.argumentList.arguments;
if (arguments.length != 1) {
return;
}
List<DartType> typeArgumentTypes;
var typeArguments = node.typeArguments;
if (typeArguments != null) {
var arguments = typeArguments.arguments;
if (arguments.length == typeParameters.length) {
typeArgumentTypes = arguments.map((a) => a.type).toList();
} else {
typeArgumentTypes = _listOfDynamic(typeParameters);
}
} else {
typeArgumentTypes = List.filled(
typeParameters.length,
UnknownInferredType.instance,
);
}
var extendedForDownward = Substitution.fromPairs(
typeParameters,
typeArgumentTypes,
).substituteType(element.extendedType);
var receiver = arguments[0];
InferenceContext.setType(receiver, extendedForDownward);
}
void _checkTypeArgumentsMatchingBounds(
List<TypeParameterElement> typeParameters,
TypeArgumentList typeArgumentList,
List<DartType> typeArgumentTypes,
Substitution substitution,
) {
if (typeArgumentList != null) {
for (var i = 0; i < typeArgumentTypes.length; i++) {
var argType = typeArgumentTypes[i];
var boundType = typeParameters[i].bound;
if (boundType != null) {
boundType = substitution.substituteType(boundType);
if (!_typeSystem.isSubtypeOf(argType, boundType)) {
_errorReporter.reportTypeErrorForNode(
CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
typeArgumentList.arguments[i],
[argType, boundType],
);
}
}
}
}
}
/// Return the most specific extension or `null` if no single one can be
/// identified.
_InstantiatedExtension _chooseMostSpecific(
List<_InstantiatedExtension> extensions) {
for (var i = 0; i < extensions.length; i++) {
var e1 = extensions[i];
var isMoreSpecific = true;
for (var j = 0; j < extensions.length; j++) {
var e2 = extensions[j];
if (i != j && !_isMoreSpecific(e1, e2)) {
isMoreSpecific = false;
break;
}
}
if (isMoreSpecific) {
return e1;
}
}
// Otherwise fail.
return null;
}
/// Return extensions for the [type] that match the given [name] in the
/// current scope.
List<_InstantiatedExtension> _getApplicable(DartType type, String name) {
var candidates = _getExtensionsWithMember(name);
var instantiatedExtensions = <_InstantiatedExtension>[];
for (var candidate in candidates) {
var typeParameters = candidate.extension.typeParameters;
var inferrer = GenericInferrer(
_typeProvider,
_typeSystem,
typeParameters,
);
inferrer.constrainArgument(
type,
candidate.extension.extendedType,
'extendedType',
);
var typeArguments = inferrer.infer(typeParameters, failAtError: true);
if (typeArguments == null) {
continue;
}
var substitution = Substitution.fromPairs(
typeParameters,
typeArguments,
);
var extendedType = substitution.substituteType(
candidate.extension.extendedType,
);
if (!_isSubtypeOf(type, extendedType)) {
continue;
}
instantiatedExtensions.add(
_InstantiatedExtension(candidate, substitution, extendedType),
);
}
return instantiatedExtensions;
}
/// Return extensions from the current scope, that define a member with the
/// given [name].
List<_CandidateExtension> _getExtensionsWithMember(String name) {
var candidates = <_CandidateExtension>[];
/// Add the given [extension] to the list of [candidates] if it defined a
/// member whose name matches the target [name].
void checkExtension(ExtensionElement extension) {
for (var field in extension.fields) {
if (field.name == name) {
candidates.add(
_CandidateExtension(
extension,
getter: field.getter,
setter: field.setter,
),
);
return;
}
}
if (name == '[]') {
ExecutableElement getter;
ExecutableElement setter;
for (var method in extension.methods) {
if (method.name == '[]') {
getter = method;
} else if (method.name == '[]=') {
setter = method;
}
}
if (getter != null || setter != null) {
candidates.add(
_CandidateExtension(extension, getter: getter, setter: setter),
);
}
} else {
for (var method in extension.methods) {
if (method.name == name) {
candidates.add(
_CandidateExtension(extension, getter: method),
);
return;
}
}
}
}
for (var extension in _nameScope.extensions) {
checkExtension(extension);
}
return candidates;
}
/// Given the generic [element] element, either return types specified
/// explicitly in [typeArguments], or infer type arguments from the given
/// [receiverType].
///
/// If the number of explicit type arguments is different than the number
/// of extension's type parameters, or inference fails, return `dynamic`
/// for all type parameters.
List<DartType> _inferTypeArguments(
ExtensionOverride node,
DartType receiverType,
) {
var element = node.staticElement;
var typeParameters = element.typeParameters;
if (typeParameters.isEmpty) {
return const <DartType>[];
}
var typeArguments = node.typeArguments;
if (typeArguments != null) {
var arguments = typeArguments.arguments;
if (arguments.length == typeParameters.length) {
return arguments.map((a) => a.type).toList();
} else {
// TODO(scheglov) Report an error.
return _listOfDynamic(typeParameters);
}
} else {
var inferrer = GenericInferrer(
_typeProvider,
_typeSystem,
typeParameters,
);
inferrer.constrainArgument(
receiverType,
element.extendedType,
'extendedType',
);
return inferrer.infer(
typeParameters,
errorReporter: _errorReporter,
errorNode: node.extensionName,
);
}
}
/// Instantiate the extended type of the [extension] to the bounds of the
/// type formals of the extension.
DartType _instantiateToBounds(ExtensionElement extension) {
var typeParameters = extension.typeParameters;
return Substitution.fromPairs(
typeParameters,
_typeSystem.instantiateTypeFormalsToBounds(typeParameters),
).substituteType(extension.extendedType);
}
/// Return `true` is [e1] is more specific than [e2].
bool _isMoreSpecific(_InstantiatedExtension e1, _InstantiatedExtension e2) {
// 1. The latter extension is declared in a platform library, and the
// former extension is not.
// 2. They are both declared in platform libraries, or both declared in
// non-platform libraries.
var e1_isInSdk = e1.extension.library.isInSdk;
var e2_isInSdk = e2.extension.library.isInSdk;
if (e1_isInSdk && !e2_isInSdk) {
return false;
} else if (!e1_isInSdk && e2_isInSdk) {
return true;
}
var extendedType1 = e1.extendedType;
var extendedType2 = e2.extendedType;
// 3. The instantiated type (the type after applying type inference from
// the receiver) of T1 is a subtype of the instantiated type of T2,
// and either...
if (!_isSubtypeOf(extendedType1, extendedType2)) {
return false;
}
// 4. ...not vice versa, or...
if (!_isSubtypeOf(extendedType2, extendedType1)) {
return true;
}
// 5. ...the instantiate-to-bounds type of T1 is a subtype of the
// instantiate-to-bounds type of T2 and not vice versa.
// TODO(scheglov) store instantiated types
var extendedTypeBound1 = _instantiateToBounds(e1.extension);
var extendedTypeBound2 = _instantiateToBounds(e2.extension);
return _isSubtypeOf(extendedTypeBound1, extendedTypeBound2) &&
!_isSubtypeOf(extendedTypeBound2, extendedTypeBound1);
}
/// Ask the type system for a subtype check.
bool _isSubtypeOf(DartType type1, DartType type2) =>
_typeSystem.isSubtypeOf(type1, type2);
List<DartType> _listOfDynamic(List<TypeParameterElement> parameters) {
return List<DartType>.filled(parameters.length, _dynamicType);
}
/// Return `true` if the extension override [node] is being used as a target
/// of an operation that might be accessing an instance member.
static bool _isValidContext(ExtensionOverride node) {
AstNode parent = node.parent;
return parent is BinaryExpression && parent.leftOperand == node ||
parent is CascadeExpression && parent.target == node ||
parent is FunctionExpressionInvocation && parent.function == node ||
parent is IndexExpression && parent.target == node ||
parent is MethodInvocation && parent.target == node ||
parent is PrefixExpression ||
parent is PropertyAccess && parent.target == node;
}
}
class _CandidateExtension {
final ExtensionElement extension;
final ExecutableElement getter;
final ExecutableElement setter;
_CandidateExtension(this.extension, {this.getter, this.setter})
: assert(getter != null || setter != null);
}
class _InstantiatedExtension {
final _CandidateExtension candidate;
final MapSubstitution substitution;
final DartType extendedType;
_InstantiatedExtension(this.candidate, this.substitution, this.extendedType);
ResolutionResult get asResolutionResult {
return ResolutionResult(getter: getter, setter: setter);
}
ExtensionElement get extension => candidate.extension;
ExecutableElement get getter {
if (candidate.getter == null) {
return null;
}
return ExecutableMember.from2(candidate.getter, substitution);
}
ExecutableElement get setter {
if (candidate.setter == null) {
return null;
}
return ExecutableMember.from2(candidate.setter, substitution);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/flow_analysis_visitor.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/dart/element/type_system.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/generated/variable_type_provider.dart';
import 'package:front_end/src/fasta/flow_analysis/flow_analysis.dart';
import 'package:meta/meta.dart';
class AnalyzerFunctionBodyAccess
implements FunctionBodyAccess<PromotableElement> {
final FunctionBody node;
AnalyzerFunctionBodyAccess(this.node);
@override
bool isPotentiallyMutatedInClosure(PromotableElement variable) {
return node.isPotentiallyMutatedInClosure(variable);
}
@override
bool isPotentiallyMutatedInScope(PromotableElement variable) {
return node.isPotentiallyMutatedInScope(variable);
}
}
class AnalyzerNodeOperations implements NodeOperations<Expression> {
const AnalyzerNodeOperations();
@override
Expression unwrapParenthesized(Expression node) {
return node.unParenthesized;
}
}
/// The helper for performing flow analysis during resolution.
///
/// It contains related precomputed data, result, and non-trivial pieces of
/// code that are independent from visiting AST during resolution, so can
/// be extracted.
class FlowAnalysisHelper {
/// The reused instance for creating new [FlowAnalysis] instances.
final NodeOperations<Expression> _nodeOperations;
/// The reused instance for creating new [FlowAnalysis] instances.
final TypeSystemTypeOperations _typeOperations;
/// Precomputed sets of potentially assigned variables.
final AssignedVariables<AstNode, PromotableElement> assignedVariables;
/// The result for post-resolution stages of analysis.
final FlowAnalysisResult result;
/// The current flow, when resolving a function body, or `null` otherwise.
FlowAnalysis<Statement, Expression, PromotableElement, DartType> flow;
int _blockFunctionBodyLevel = 0;
factory FlowAnalysisHelper(
TypeSystem typeSystem, AstNode node, bool retainDataForTesting) {
return FlowAnalysisHelper._(
const AnalyzerNodeOperations(),
TypeSystemTypeOperations(typeSystem),
computeAssignedVariables(node),
retainDataForTesting ? FlowAnalysisResult() : null);
}
FlowAnalysisHelper._(this._nodeOperations, this._typeOperations,
this.assignedVariables, this.result);
LocalVariableTypeProvider get localVariableTypeProvider {
return _LocalVariableTypeProvider(this);
}
VariableElement assignmentExpression(AssignmentExpression node) {
if (flow == null) return null;
var left = node.leftHandSide;
if (left is SimpleIdentifier) {
var element = left.staticElement;
if (element is VariableElement) {
return element;
}
}
return null;
}
void assignmentExpression_afterRight(
VariableElement localElement, Expression right) {
if (localElement == null) return;
flow.write(localElement);
}
void binaryExpression_equal(
BinaryExpression node, Expression left, Expression right,
{@required bool notEqual}) {
if (flow == null) return;
if (right is NullLiteral) {
if (left is SimpleIdentifier) {
var element = left.staticElement;
if (element is VariableElement) {
flow.conditionEqNull(node, element, notEqual: notEqual);
}
}
} else if (left is NullLiteral) {
if (right is SimpleIdentifier) {
var element = right.staticElement;
if (element is VariableElement) {
flow.conditionEqNull(node, element, notEqual: notEqual);
}
}
}
}
void breakStatement(BreakStatement node) {
var target = getLabelTarget(node, node.label?.staticElement);
flow.handleBreak(target);
}
/// Mark the [node] as unreachable if it is not covered by another node that
/// is already known to be unreachable.
void checkUnreachableNode(AstNode node) {
if (flow == null) return;
if (flow.isReachable) return;
if (result != null) {
// Ignore the [node] if it is fully covered by the last unreachable.
if (result.unreachableNodes.isNotEmpty) {
var last = result.unreachableNodes.last;
if (node.offset >= last.offset && node.end <= last.end) return;
}
result.unreachableNodes.add(node);
}
}
void continueStatement(ContinueStatement node) {
var target = getLabelTarget(node, node.label?.staticElement);
flow.handleContinue(target);
}
void for_bodyBegin(AstNode node, Expression condition) {
flow.for_bodyBegin(node is Statement ? node : null, condition);
}
void for_conditionBegin(AstNode node, Expression condition) {
var assigned = assignedVariables.writtenInNode(node);
flow.for_conditionBegin(assigned);
}
void functionBody_enter(FunctionBody node) {
_blockFunctionBodyLevel++;
if (_blockFunctionBodyLevel > 1) {
assert(flow != null);
} else {
flow = FlowAnalysis<Statement, Expression, PromotableElement, DartType>(
_nodeOperations,
_typeOperations,
AnalyzerFunctionBodyAccess(node),
);
}
var parameters = _enclosingExecutableParameters(node);
if (parameters != null) {
for (var parameter in parameters.parameters) {
flow.write(parameter.declaredElement);
}
}
}
void functionBody_exit(FunctionBody node) {
_blockFunctionBodyLevel--;
if (_blockFunctionBodyLevel > 0) {
return;
}
// Set this.flow to null before doing any clean-up so that if an exception
// is raised, the state is already updated correctly, and we don't have
// cascading failures.
var flow = this.flow;
this.flow = null;
if (!flow.isReachable) {
result?.functionBodiesThatDontComplete?.add(node);
}
flow.finish();
}
void isExpression(IsExpression node) {
if (flow == null) return;
var expression = node.expression;
var typeAnnotation = node.type;
if (expression is SimpleIdentifier) {
var element = expression.staticElement;
if (element is VariableElement) {
flow.isExpression_end(
node,
element,
node.notOperator != null,
typeAnnotation.type,
);
}
}
}
bool isPotentiallyNonNullableLocalReadBeforeWrite(SimpleIdentifier node) {
if (flow == null) return false;
if (node.inDeclarationContext()) return false;
if (!node.inGetterContext()) return false;
var element = node.staticElement;
if (element is LocalVariableElement) {
var typeSystem = _typeOperations.typeSystem;
if (typeSystem.isPotentiallyNonNullable(element.type)) {
var isUnassigned = !flow.isAssigned(element);
if (isUnassigned) {
result?.unassignedNodes?.add(node);
}
// Note: in principle we could make this slightly more performant by
// checking element.isLate earlier, but we would lose the ability to
// test the flow analysis mechanism using late variables. And it seems
// unlikely that the `late` modifier will be used often enough for it to
// make a significant difference.
if (element.isLate) return false;
return isUnassigned;
}
}
return false;
}
void variableDeclarationList(VariableDeclarationList node) {
if (flow != null) {
var variables = node.variables;
for (var i = 0; i < variables.length; ++i) {
var variable = variables[i];
if (variable.initializer != null) {
flow.write(variable.declaredElement);
}
}
}
}
FormalParameterList _enclosingExecutableParameters(FunctionBody node) {
var parent = node.parent;
if (parent is ConstructorDeclaration) {
return parent.parameters;
}
if (parent is FunctionExpression) {
return parent.parameters;
}
if (parent is MethodDeclaration) {
return parent.parameters;
}
return null;
}
/// Computes the [AssignedVariables] map for the given [node].
static AssignedVariables<AstNode, PromotableElement> computeAssignedVariables(
AstNode node) {
var assignedVariables = AssignedVariables<AstNode, PromotableElement>();
node.accept(_AssignedVariablesVisitor(assignedVariables));
return assignedVariables;
}
/// Return the target of the `break` or `continue` statement with the
/// [element] label. The [element] might be `null` (when the statement does
/// not specify a label), so the default enclosing target is returned.
static Statement getLabelTarget(AstNode node, LabelElement element) {
for (; node != null; node = node.parent) {
if (node is DoStatement ||
node is ForStatement ||
node is SwitchStatement ||
node is WhileStatement) {
if (element == null) {
return node;
}
var parent = node.parent;
if (parent is LabeledStatement) {
for (var nodeLabel in parent.labels) {
if (identical(nodeLabel.label.staticElement, element)) {
return node;
}
}
}
}
if (element != null && node is SwitchStatement) {
for (var member in node.members) {
for (var nodeLabel in member.labels) {
if (identical(nodeLabel.label.staticElement, element)) {
return node;
}
}
}
}
}
return null;
}
}
/// The result of performing flow analysis on a unit.
class FlowAnalysisResult {
/// The list of nodes, [Expression]s or [Statement]s, that cannot be reached,
/// for example because a previous statement always exits.
final List<AstNode> unreachableNodes = [];
/// The list of [FunctionBody]s that don't complete, for example because
/// there is a `return` statement at the end of the function body block.
final List<FunctionBody> functionBodiesThatDontComplete = [];
/// The list of [Expression]s representing variable accesses that occur before
/// the corresponding variable has been definitely assigned.
final List<AstNode> unassignedNodes = [];
}
class TypeSystemTypeOperations
implements TypeOperations<PromotableElement, DartType> {
final TypeSystem typeSystem;
TypeSystemTypeOperations(this.typeSystem);
@override
bool isSameType(covariant TypeImpl type1, covariant TypeImpl type2) {
return type1 == type2;
}
@override
bool isSubtypeOf(DartType leftType, DartType rightType) {
return typeSystem.isSubtypeOf(leftType, rightType);
}
@override
DartType promoteToNonNull(DartType type) {
return typeSystem.promoteToNonNull(type);
}
@override
DartType variableType(PromotableElement variable) {
return variable.type;
}
}
/// The visitor that gathers local variables that are potentially assigned
/// in corresponding statements, such as loops, `switch` and `try`.
class _AssignedVariablesVisitor extends RecursiveAstVisitor<void> {
final AssignedVariables assignedVariables;
_AssignedVariablesVisitor(this.assignedVariables);
@override
void visitAssignmentExpression(AssignmentExpression node) {
var left = node.leftHandSide;
super.visitAssignmentExpression(node);
if (left is SimpleIdentifier) {
var element = left.staticElement;
if (element is VariableElement) {
assignedVariables.write(element);
}
}
}
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
assignedVariables.beginNode();
super.visitConstructorDeclaration(node);
assignedVariables.endNode(node);
}
@override
void visitDoStatement(DoStatement node) {
assignedVariables.beginNode();
super.visitDoStatement(node);
assignedVariables.endNode(node);
}
@override
void visitForElement(ForElement node) {
_handleFor(node, node.forLoopParts, node.body);
}
@override
void visitForStatement(ForStatement node) {
_handleFor(node, node.forLoopParts, node.body);
}
@override
void visitFunctionDeclaration(FunctionDeclaration node) {
bool isClosure = node.parent is! CompilationUnit;
assignedVariables.beginNode(isClosure: isClosure);
// Note: we bypass this.visitFunctionExpression so that the function
// expression isn't mistaken for a closure.
super.visitFunctionExpression(node.functionExpression);
assignedVariables.endNode(node, isClosure: isClosure);
}
@override
void visitFunctionExpression(FunctionExpression node) {
assignedVariables.beginNode(isClosure: true);
super.visitFunctionExpression(node);
assignedVariables.endNode(node, isClosure: true);
}
@override
void visitMethodDeclaration(MethodDeclaration node) {
assignedVariables.beginNode();
super.visitMethodDeclaration(node);
assignedVariables.endNode(node);
}
@override
void visitSwitchStatement(SwitchStatement node) {
var expression = node.expression;
var members = node.members;
expression.accept(this);
assignedVariables.beginNode();
members.accept(this);
assignedVariables.endNode(node);
}
@override
void visitTryStatement(TryStatement node) {
assignedVariables.beginNode();
node.body.accept(this);
assignedVariables.endNode(node.body);
node.catchClauses.accept(this);
var finallyBlock = node.finallyBlock;
if (finallyBlock != null) {
assignedVariables.beginNode();
finallyBlock.accept(this);
assignedVariables.endNode(finallyBlock);
}
}
@override
void visitWhileStatement(WhileStatement node) {
assignedVariables.beginNode();
super.visitWhileStatement(node);
assignedVariables.endNode(node);
}
void _handleFor(AstNode node, ForLoopParts forLoopParts, AstNode body) {
if (forLoopParts is ForParts) {
if (forLoopParts is ForPartsWithExpression) {
forLoopParts.initialization?.accept(this);
} else if (forLoopParts is ForPartsWithDeclarations) {
forLoopParts.variables?.accept(this);
} else {
throw new StateError('Unrecognized for loop parts');
}
assignedVariables.beginNode();
forLoopParts.condition?.accept(this);
body.accept(this);
forLoopParts.updaters?.accept(this);
assignedVariables.endNode(node);
} else if (forLoopParts is ForEachParts) {
var iterable = forLoopParts.iterable;
iterable.accept(this);
assignedVariables.beginNode();
if (forLoopParts is ForEachPartsWithIdentifier) {
var element = forLoopParts.identifier.staticElement;
if (element is VariableElement) {
assignedVariables.write(element);
}
} else if (forLoopParts is ForEachPartsWithDeclaration) {
assignedVariables.write(forLoopParts.loopVariable.declaredElement);
} else {
throw new StateError('Unrecognized for loop parts');
}
body.accept(this);
assignedVariables.endNode(node);
} else {
throw new StateError('Unrecognized for loop parts');
}
}
}
/// The flow analysis based implementation of [LocalVariableTypeProvider].
class _LocalVariableTypeProvider implements LocalVariableTypeProvider {
final FlowAnalysisHelper _manager;
_LocalVariableTypeProvider(this._manager);
@override
DartType getType(SimpleIdentifier node) {
var variable = node.staticElement as VariableElement;
var promotedType = _manager.flow?.promotedType(variable);
return promotedType ?? variable.type;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/exit_detector.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
/// Instances of the class `ExitDetector` determine whether the visited AST node
/// is guaranteed to terminate by executing a `return` statement, `throw`
/// expression, `rethrow` expression, or simple infinite loop such as
/// `while(true)`.
class ExitDetector extends GeneralizingAstVisitor<bool> {
/// Set to `true` when a `break` is encountered, and reset to `false` when a
/// `do`, `while`, `for` or `switch` block is entered.
bool _enclosingBlockContainsBreak = false;
/// Set to `true` when a `continue` is encountered, and reset to `false` when
/// a `do`, `while`, `for` or `switch` block is entered.
bool _enclosingBlockContainsContinue = false;
/// Add node when a labelled `break` is encountered.
Set<AstNode> _enclosingBlockBreaksLabel = new Set<AstNode>();
@override
bool visitArgumentList(ArgumentList node) =>
_visitExpressions(node.arguments);
@override
bool visitAsExpression(AsExpression node) => _nodeExits(node.expression);
@override
bool visitAssertInitializer(AssertInitializer node) => false;
@override
bool visitAssertStatement(AssertStatement node) => false;
@override
bool visitAssignmentExpression(AssignmentExpression node) {
Expression leftHandSide = node.leftHandSide;
if (_nodeExits(leftHandSide)) {
return true;
}
TokenType operatorType = node.operator.type;
if (operatorType == TokenType.AMPERSAND_AMPERSAND_EQ ||
operatorType == TokenType.BAR_BAR_EQ ||
operatorType == TokenType.QUESTION_QUESTION_EQ) {
return false;
}
if (leftHandSide is PropertyAccess && leftHandSide.isNullAware) {
return false;
}
return _nodeExits(node.rightHandSide);
}
@override
bool visitAwaitExpression(AwaitExpression node) =>
_nodeExits(node.expression);
@override
bool visitBinaryExpression(BinaryExpression node) {
Expression lhsExpression = node.leftOperand;
Expression rhsExpression = node.rightOperand;
TokenType operatorType = node.operator.type;
// If the operator is ||, then only consider the RHS of the binary
// expression if the left hand side is the false literal.
// TODO(jwren) Do we want to take constant expressions into account,
// evaluate if(false) {} differently than if(<condition>), when <condition>
// evaluates to a constant false value?
if (operatorType == TokenType.BAR_BAR) {
if (lhsExpression is BooleanLiteral) {
if (!lhsExpression.value) {
return _nodeExits(rhsExpression);
}
}
return _nodeExits(lhsExpression);
}
// If the operator is &&, then only consider the RHS of the binary
// expression if the left hand side is the true literal.
if (operatorType == TokenType.AMPERSAND_AMPERSAND) {
if (lhsExpression is BooleanLiteral) {
if (lhsExpression.value) {
return _nodeExits(rhsExpression);
}
}
return _nodeExits(lhsExpression);
}
// If the operator is ??, then don't consider the RHS of the binary
// expression.
if (operatorType == TokenType.QUESTION_QUESTION) {
return _nodeExits(lhsExpression);
}
return _nodeExits(lhsExpression) || _nodeExits(rhsExpression);
}
@override
bool visitBlock(Block node) => _visitStatements(node.statements);
@override
bool visitBlockFunctionBody(BlockFunctionBody node) => _nodeExits(node.block);
@override
bool visitBreakStatement(BreakStatement node) {
_enclosingBlockContainsBreak = true;
if (node.label != null) {
_enclosingBlockBreaksLabel.add(node.target);
}
return false;
}
@override
bool visitCascadeExpression(CascadeExpression node) =>
_nodeExits(node.target) || _visitExpressions(node.cascadeSections);
@override
bool visitConditionalExpression(ConditionalExpression node) {
Expression conditionExpression = node.condition;
Expression thenStatement = node.thenExpression;
Expression elseStatement = node.elseExpression;
// TODO(jwren) Do we want to take constant expressions into account,
// evaluate if(false) {} differently than if(<condition>), when <condition>
// evaluates to a constant false value?
if (_nodeExits(conditionExpression)) {
return true;
}
if (thenStatement == null || elseStatement == null) {
return false;
}
return thenStatement.accept(this) && elseStatement.accept(this);
}
@override
bool visitContinueStatement(ContinueStatement node) {
_enclosingBlockContainsContinue = true;
return false;
}
@override
bool visitDoStatement(DoStatement node) {
bool outerBreakValue = _enclosingBlockContainsBreak;
bool outerContinueValue = _enclosingBlockContainsContinue;
_enclosingBlockContainsBreak = false;
_enclosingBlockContainsContinue = false;
try {
bool bodyExits = _nodeExits(node.body);
bool containsBreakOrContinue =
_enclosingBlockContainsBreak || _enclosingBlockContainsContinue;
// Even if we determine that the body "exits", there might be break or
// continue statements that actually mean it _doesn't_ always exit.
if (bodyExits && !containsBreakOrContinue) {
return true;
}
Expression conditionExpression = node.condition;
if (_nodeExits(conditionExpression)) {
return true;
}
// TODO(jwren) Do we want to take all constant expressions into account?
if (conditionExpression is BooleanLiteral) {
// If do {} while (true), and the body doesn't break, then return true.
if (conditionExpression.value && !_enclosingBlockContainsBreak) {
return true;
}
}
return false;
} finally {
_enclosingBlockContainsBreak = outerBreakValue;
_enclosingBlockContainsContinue = outerContinueValue;
}
}
@override
bool visitEmptyStatement(EmptyStatement node) => false;
@override
bool visitExpressionStatement(ExpressionStatement node) =>
_nodeExits(node.expression);
@override
bool visitExtensionOverride(ExtensionOverride node) => false;
@override
bool visitForElement(ForElement node) {
bool outerBreakValue = _enclosingBlockContainsBreak;
_enclosingBlockContainsBreak = false;
try {
ForLoopParts forLoopParts = node.forLoopParts;
if (forLoopParts is ForParts) {
if (forLoopParts is ForPartsWithDeclarations) {
if (forLoopParts.variables != null &&
_visitVariableDeclarations(forLoopParts.variables.variables)) {
return true;
}
} else if (forLoopParts is ForPartsWithExpression) {
if (forLoopParts.initialization != null &&
_nodeExits(forLoopParts.initialization)) {
return true;
}
}
Expression conditionExpression = forLoopParts.condition;
if (conditionExpression != null && _nodeExits(conditionExpression)) {
return true;
}
if (_visitExpressions(forLoopParts.updaters)) {
return true;
}
bool blockReturns = _nodeExits(node.body);
// TODO(jwren) Do we want to take all constant expressions into account?
// If for(; true; ) (or for(;;)), and the body doesn't return or the body
// doesn't have a break, then return true.
bool implicitOrExplictTrue = conditionExpression == null ||
(conditionExpression is BooleanLiteral &&
conditionExpression.value);
if (implicitOrExplictTrue) {
if (blockReturns || !_enclosingBlockContainsBreak) {
return true;
}
}
return false;
} else if (forLoopParts is ForEachParts) {
bool iterableExits = _nodeExits(forLoopParts.iterable);
// Discard whether the for-each body exits; since the for-each iterable
// may be empty, execution may never enter the body, so it doesn't matter
// if it exits or not. We still must visit the body, to accurately
// manage `_enclosingBlockBreaksLabel`.
_nodeExits(node.body);
return iterableExits;
}
} finally {
_enclosingBlockContainsBreak = outerBreakValue;
}
return false;
}
@override
bool visitForStatement(ForStatement node) {
bool outerBreakValue = _enclosingBlockContainsBreak;
_enclosingBlockContainsBreak = false;
ForLoopParts parts = node.forLoopParts;
try {
if (parts is ForEachParts) {
bool iterableExits = _nodeExits(parts.iterable);
// Discard whether the for-each body exits; since the for-each iterable
// may be empty, execution may never enter the body, so it doesn't matter
// if it exits or not. We still must visit the body, to accurately
// manage `_enclosingBlockBreaksLabel`.
_nodeExits(node.body);
return iterableExits;
}
VariableDeclarationList variables;
Expression initialization;
Expression condition;
NodeList<Expression> updaters;
if (parts is ForPartsWithDeclarations) {
variables = parts.variables;
condition = parts.condition;
updaters = parts.updaters;
} else if (parts is ForPartsWithExpression) {
initialization = parts.initialization;
condition = parts.condition;
updaters = parts.updaters;
}
if (variables != null &&
_visitVariableDeclarations(variables.variables)) {
return true;
}
if (initialization != null && _nodeExits(initialization)) {
return true;
}
if (condition != null && _nodeExits(condition)) {
return true;
}
if (_visitExpressions(updaters)) {
return true;
}
bool blockReturns = _nodeExits(node.body);
// TODO(jwren) Do we want to take all constant expressions into account?
// If for(; true; ) (or for(;;)), and the body doesn't return or the body
// doesn't have a break, then return true.
bool implicitOrExplictTrue =
condition == null || (condition is BooleanLiteral && condition.value);
if (implicitOrExplictTrue) {
if (blockReturns || !_enclosingBlockContainsBreak) {
return true;
}
}
return false;
} finally {
_enclosingBlockContainsBreak = outerBreakValue;
}
}
@override
bool visitFunctionDeclarationStatement(FunctionDeclarationStatement node) =>
false;
@override
bool visitFunctionExpression(FunctionExpression node) => false;
@override
bool visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
if (_nodeExits(node.function)) {
return true;
}
return node.argumentList.accept(this);
}
@override
bool visitGenericFunctionType(GenericFunctionType node) => false;
@override
bool visitIdentifier(Identifier node) => false;
@override
bool visitIfElement(IfElement node) {
Expression conditionExpression = node.condition;
CollectionElement thenElement = node.thenElement;
CollectionElement elseElement = node.elseElement;
if (_nodeExits(conditionExpression)) {
return true;
}
bool conditionValue = _knownConditionValue(conditionExpression);
if (conditionValue == true) {
return _nodeExits(thenElement);
} else if (conditionValue == false && elseElement != null) {
return _nodeExits(elseElement);
}
bool thenExits = _nodeExits(thenElement);
bool elseExits = _nodeExits(elseElement);
if (thenElement == null || elseElement == null) {
return false;
}
return thenExits && elseExits;
}
@override
bool visitIfStatement(IfStatement node) {
Expression conditionExpression = node.condition;
Statement thenStatement = node.thenStatement;
Statement elseStatement = node.elseStatement;
if (_nodeExits(conditionExpression)) {
return true;
}
bool conditionValue = _knownConditionValue(conditionExpression);
if (conditionValue == true) {
return _nodeExits(thenStatement);
} else if (conditionValue == false && elseStatement != null) {
return _nodeExits(elseStatement);
}
bool thenExits = _nodeExits(thenStatement);
bool elseExits = _nodeExits(elseStatement);
if (thenStatement == null || elseStatement == null) {
return false;
}
return thenExits && elseExits;
}
@override
bool visitIndexExpression(IndexExpression node) {
Expression target = node.realTarget;
if (_nodeExits(target)) {
return true;
}
if (_nodeExits(node.index)) {
return true;
}
return false;
}
@override
bool visitInstanceCreationExpression(InstanceCreationExpression node) =>
_nodeExits(node.argumentList);
@override
bool visitIsExpression(IsExpression node) => node.expression.accept(this);
@override
bool visitLabel(Label node) => false;
@override
bool visitLabeledStatement(LabeledStatement node) {
try {
bool statementExits = _nodeExits(node.statement);
bool neverBrokeFromLabel =
!_enclosingBlockBreaksLabel.contains(node.statement);
return statementExits && neverBrokeFromLabel;
} finally {
_enclosingBlockBreaksLabel.remove(node.statement);
}
}
@override
bool visitListLiteral(ListLiteral node) {
for (CollectionElement element in node.elements) {
if (_nodeExits(element)) {
return true;
}
}
return false;
}
@override
bool visitLiteral(Literal node) => false;
@override
bool visitMapLiteralEntry(MapLiteralEntry node) {
return _nodeExits(node.key) || _nodeExits(node.value);
}
@override
bool visitMethodInvocation(MethodInvocation node) {
Expression target = node.realTarget;
if (target != null) {
if (target.accept(this)) {
return true;
}
if (node.isNullAware) {
return false;
}
}
Element element = node.methodName.staticElement;
if (element != null && element.hasAlwaysThrows) {
return true;
}
return _nodeExits(node.argumentList);
}
@override
bool visitNamedExpression(NamedExpression node) =>
node.expression.accept(this);
@override
bool visitNode(AstNode node) {
throw new StateError(
'Missing a visit method for a node of type ${node.runtimeType}');
}
@override
bool visitParenthesizedExpression(ParenthesizedExpression node) =>
node.expression.accept(this);
@override
bool visitPostfixExpression(PostfixExpression node) => false;
@override
bool visitPrefixExpression(PrefixExpression node) => false;
@override
bool visitPropertyAccess(PropertyAccess node) {
Expression target = node.realTarget;
if (target != null && target.accept(this)) {
return true;
}
return false;
}
@override
bool visitRethrowExpression(RethrowExpression node) => true;
@override
bool visitReturnStatement(ReturnStatement node) => true;
@override
bool visitSetOrMapLiteral(SetOrMapLiteral node) {
for (CollectionElement element in node.elements) {
if (_nodeExits(element)) {
return true;
}
}
return false;
}
@override
bool visitSpreadElement(SpreadElement node) {
return _nodeExits(node.expression);
}
@override
bool visitSuperExpression(SuperExpression node) => false;
@override
bool visitSwitchCase(SwitchCase node) => _visitStatements(node.statements);
@override
bool visitSwitchDefault(SwitchDefault node) =>
_visitStatements(node.statements);
@override
bool visitSwitchStatement(SwitchStatement node) {
bool outerBreakValue = _enclosingBlockContainsBreak;
_enclosingBlockContainsBreak = false;
try {
bool hasDefault = false;
bool hasNonExitingCase = false;
List<SwitchMember> members = node.members;
for (int i = 0; i < members.length; i++) {
SwitchMember switchMember = members[i];
if (switchMember is SwitchDefault) {
hasDefault = true;
// If this is the last member and there are no statements, then it
// does not exit.
if (switchMember.statements.isEmpty && i + 1 == members.length) {
hasNonExitingCase = true;
continue;
}
}
// For switch members with no statements, don't visit the children.
// Otherwise, if there children statements don't exit, mark this as a
// non-exiting case.
if (switchMember.statements.isNotEmpty && !switchMember.accept(this)) {
hasNonExitingCase = true;
}
}
if (hasNonExitingCase) {
return false;
}
// As all cases exit, return whether that list includes `default`.
return hasDefault;
} finally {
_enclosingBlockContainsBreak = outerBreakValue;
}
}
@override
bool visitThisExpression(ThisExpression node) => false;
@override
bool visitThrowExpression(ThrowExpression node) => true;
@override
bool visitTryStatement(TryStatement node) {
if (_nodeExits(node.finallyBlock)) {
return true;
}
if (!_nodeExits(node.body)) {
return false;
}
for (CatchClause c in node.catchClauses) {
if (!_nodeExits(c.body)) {
return false;
}
}
return true;
}
@override
bool visitTypeName(TypeName node) => false;
@override
bool visitVariableDeclaration(VariableDeclaration node) {
Expression initializer = node.initializer;
if (initializer != null) {
return initializer.accept(this);
}
return false;
}
@override
bool visitVariableDeclarationList(VariableDeclarationList node) =>
_visitVariableDeclarations(node.variables);
@override
bool visitVariableDeclarationStatement(VariableDeclarationStatement node) {
NodeList<VariableDeclaration> variables = node.variables.variables;
for (int i = 0; i < variables.length; i++) {
if (variables[i].accept(this)) {
return true;
}
}
return false;
}
@override
bool visitWhileStatement(WhileStatement node) {
bool outerBreakValue = _enclosingBlockContainsBreak;
_enclosingBlockContainsBreak = false;
try {
Expression conditionExpression = node.condition;
if (conditionExpression.accept(this)) {
return true;
}
node.body.accept(this);
// TODO(jwren) Do we want to take all constant expressions into account?
if (conditionExpression is BooleanLiteral) {
// If while(true), and the body doesn't have a break, then return true.
// The body might be found to exit, but if there are any break
// statements, then it is a faulty finding. In other words:
//
// * If the body exits, and does not contain a break statement, then
// it exits.
// * If the body does not exit, and does not contain a break statement,
// then it loops infinitely (also an exit).
//
// As both conditions forbid any break statements to be found, the logic
// just boils down to checking [_enclosingBlockContainsBreak].
if (conditionExpression.value && !_enclosingBlockContainsBreak) {
return true;
}
}
return false;
} finally {
_enclosingBlockContainsBreak = outerBreakValue;
}
}
@override
bool visitYieldStatement(YieldStatement node) => _nodeExits(node.expression);
/// If the given [expression] has a known Boolean value, return the known
/// value, otherwise return `null`.
bool _knownConditionValue(Expression conditionExpression) {
// TODO(jwren) Do we want to take all constant expressions into account?
if (conditionExpression is BooleanLiteral) {
return conditionExpression.value;
}
return null;
}
/// Return `true` if the given [node] exits.
bool _nodeExits(AstNode node) {
if (node == null) {
return false;
}
return node.accept(this);
}
bool _visitExpressions(NodeList<Expression> expressions) {
for (int i = expressions.length - 1; i >= 0; i--) {
if (expressions[i].accept(this)) {
return true;
}
}
return false;
}
bool _visitStatements(NodeList<Statement> statements) {
for (int i = 0; i < statements.length; i++) {
if (statements[i].accept(this)) {
return true;
}
}
return false;
}
bool _visitVariableDeclarations(
NodeList<VariableDeclaration> variableDeclarations) {
for (int i = variableDeclarations.length - 1; i >= 0; i--) {
if (variableDeclarations[i].accept(this)) {
return true;
}
}
return false;
}
/// Return `true` if the given [node] exits.
static bool exits(AstNode node) {
return new ExitDetector()._nodeExits(node);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/resolution_result.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:analyzer/dart/element/element.dart';
/// The result of attempting to resolve an identifier to elements.
class ResolutionResult {
/// An instance that can be used anywhere that no element was found.
static const ResolutionResult none =
ResolutionResult._(_ResolutionResultState.none);
/// An instance that can be used anywhere that multiple elements were found.
static const ResolutionResult ambiguous =
ResolutionResult._(_ResolutionResultState.ambiguous);
/// The state of the result.
final _ResolutionResultState state;
/// Return the element that is invoked for reading.
final ExecutableElement getter;
/// Return the element that is invoked for writing.
final ExecutableElement setter;
/// Initialize a newly created result to represent resolving a single
/// reading and / or writing result.
ResolutionResult({this.getter, this.setter})
: assert(getter != null || setter != null),
state = _ResolutionResultState.single;
/// Initialize a newly created result with no elements and the given [state].
const ResolutionResult._(this.state)
: getter = null,
setter = null;
/// Return `true` if this result represents the case where multiple ambiguous
/// elements were found.
bool get isAmbiguous => state == _ResolutionResultState.ambiguous;
/// Return `true` if this result represents the case where no element was
/// found.
bool get isNone => state == _ResolutionResultState.none;
/// Return `true` if this result represents the case where a single element
/// was found.
bool get isSingle => state == _ResolutionResultState.single;
/// If this is a property, return `true` is the property is static.
/// If this is a function, return `true` is the function is static.
/// Otherwise return `false`.
bool get isStatic {
return getter?.isStatic ?? setter?.isStatic ?? false;
}
}
/// The state of a [ResolutionResult].
enum _ResolutionResultState {
/// Indicates that no element was found.
none,
/// Indicates that a single element was found.
single,
/// Indicates that multiple ambiguous elements were found.
ambiguous
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/scope.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
/**
* The scope defined by a block.
*/
class BlockScope extends EnclosedScope {
/**
* Initialize a newly created scope, enclosed within the [enclosingScope],
* based on the given [block].
*/
BlockScope(Scope enclosingScope, Block block) : super(enclosingScope) {
if (block == null) {
throw new ArgumentError("block cannot be null");
}
_defineElements(block);
}
void _defineElements(Block block) {
for (Element element in elementsInBlock(block)) {
define(element);
}
}
/**
* Return the elements that are declared directly in the given [block]. This
* does not include elements declared in nested blocks.
*/
static Iterable<Element> elementsInBlock(Block block) sync* {
NodeList<Statement> statements = block.statements;
int statementCount = statements.length;
for (int i = 0; i < statementCount; i++) {
Statement statement = statements[i];
if (statement is VariableDeclarationStatement) {
NodeList<VariableDeclaration> variables = statement.variables.variables;
int variableCount = variables.length;
for (int j = 0; j < variableCount; j++) {
yield variables[j].declaredElement;
}
} else if (statement is FunctionDeclarationStatement) {
yield statement.functionDeclaration.declaredElement;
}
}
}
}
/**
* The scope defined by a class.
*/
class ClassScope extends EnclosedScope {
/**
* Initialize a newly created scope, enclosed within the [enclosingScope],
* based on the given [classElement].
*/
ClassScope(Scope enclosingScope, ClassElement classElement)
: super(enclosingScope) {
if (classElement == null) {
throw new ArgumentError("class element cannot be null");
}
_defineMembers(classElement);
}
/**
* Define the instance members defined by the given [classElement].
*/
void _defineMembers(ClassElement classElement) {
List<PropertyAccessorElement> accessors = classElement.accessors;
int accessorLength = accessors.length;
for (int i = 0; i < accessorLength; i++) {
define(accessors[i]);
}
List<MethodElement> methods = classElement.methods;
int methodLength = methods.length;
for (int i = 0; i < methodLength; i++) {
define(methods[i]);
}
}
}
/**
* The scope defined for the initializers in a constructor.
*/
class ConstructorInitializerScope extends EnclosedScope {
/**
* Initialize a newly created scope, enclosed within the [enclosingScope].
*/
ConstructorInitializerScope(Scope enclosingScope, ConstructorElement element)
: super(enclosingScope) {
_initializeFieldFormalParameters(element);
}
/**
* Initialize the local scope with all of the field formal parameters.
*/
void _initializeFieldFormalParameters(ConstructorElement element) {
for (ParameterElement parameter in element.parameters) {
if (parameter is FieldFormalParameterElement) {
define(parameter);
}
}
}
}
/**
* A scope that is lexically enclosed in another scope.
*/
class EnclosedScope extends Scope {
/**
* The scope in which this scope is lexically enclosed.
*/
@override
final Scope enclosingScope;
/**
* Initialize a newly created scope, enclosed within the [enclosingScope].
*/
EnclosedScope(this.enclosingScope);
@override
Element internalLookup(
Identifier identifier, String name, LibraryElement referencingLibrary) {
Element element = localLookup(name, referencingLibrary);
if (element != null) {
return element;
}
// Check enclosing scope.
return enclosingScope.internalLookup(identifier, name, referencingLibrary);
}
@override
Element _internalLookupPrefixed(PrefixedIdentifier identifier, String prefix,
String name, LibraryElement referencingLibrary) {
return enclosingScope._internalLookupPrefixed(
identifier, prefix, name, referencingLibrary);
}
}
/// The scope defined by an extension.
class ExtensionScope extends EnclosedScope {
/// Initialize a newly created scope, enclosed within the [enclosingScope],
/// that represents the given [_extensionElement].
ExtensionScope(Scope enclosingScope, ExtensionElement extensionElement)
: super(enclosingScope) {
_defineMembers(extensionElement);
}
/// Define the static members defined by the given [extensionElement]. The
/// instance members should only be found if they would be found by normal
/// lookup on `this`.
void _defineMembers(ExtensionElement extensionElement) {
List<PropertyAccessorElement> accessors = extensionElement.accessors;
int accessorLength = accessors.length;
for (int i = 0; i < accessorLength; i++) {
define(accessors[i]);
}
List<MethodElement> methods = extensionElement.methods;
int methodLength = methods.length;
for (int i = 0; i < methodLength; i++) {
define(methods[i]);
}
}
}
/**
* The scope defined by a function.
*/
class FunctionScope extends EnclosedScope {
/**
* The element representing the function that defines this scope.
*/
final FunctionTypedElement _functionElement;
/**
* A flag indicating whether the parameters have already been defined, used to
* prevent the parameters from being defined multiple times.
*/
bool _parametersDefined = false;
/**
* Initialize a newly created scope, enclosed within the [enclosingScope],
* that represents the given [_functionElement].
*/
FunctionScope(Scope enclosingScope, this._functionElement)
: super(new EnclosedScope(new EnclosedScope(enclosingScope))) {
if (_functionElement == null) {
throw new ArgumentError("function element cannot be null");
}
_defineTypeParameters();
}
/**
* Define the parameters for the given function in the scope that encloses
* this function.
*/
void defineParameters() {
if (_parametersDefined) {
return;
}
_parametersDefined = true;
Scope parameterScope = enclosingScope;
List<ParameterElement> parameters = _functionElement.parameters;
int length = parameters.length;
for (int i = 0; i < length; i++) {
ParameterElement parameter = parameters[i];
if (!parameter.isInitializingFormal) {
parameterScope.define(parameter);
}
}
}
/**
* Define the type parameters for the function.
*/
void _defineTypeParameters() {
Scope typeParameterScope = enclosingScope.enclosingScope;
List<TypeParameterElement> typeParameters = _functionElement.typeParameters;
int length = typeParameters.length;
for (int i = 0; i < length; i++) {
TypeParameterElement typeParameter = typeParameters[i];
typeParameterScope.define(typeParameter);
}
}
}
/**
* The scope defined by a function type alias.
*/
class FunctionTypeScope extends EnclosedScope {
final FunctionTypeAliasElement _typeElement;
bool _parametersDefined = false;
/**
* Initialize a newly created scope, enclosed within the [enclosingScope],
* that represents the given [_typeElement].
*/
FunctionTypeScope(Scope enclosingScope, this._typeElement)
: super(new EnclosedScope(enclosingScope)) {
_defineTypeParameters();
}
/**
* Define the parameters for the function type alias.
*/
void defineParameters() {
if (_parametersDefined) {
return;
}
_parametersDefined = true;
for (ParameterElement parameter in _typeElement.parameters) {
define(parameter);
}
}
/**
* Define the type parameters for the function type alias.
*/
void _defineTypeParameters() {
Scope typeParameterScope = enclosingScope;
for (TypeParameterElement typeParameter in _typeElement.typeParameters) {
typeParameterScope.define(typeParameter);
}
}
}
/**
* The scope statements that can be the target of unlabeled `break` and
* `continue` statements.
*/
class ImplicitLabelScope {
/**
* The implicit label scope associated with the top level of a function.
*/
static const ImplicitLabelScope ROOT = const ImplicitLabelScope._(null, null);
/**
* The implicit label scope enclosing this implicit label scope.
*/
final ImplicitLabelScope outerScope;
/**
* The statement that acts as a target for break and/or continue statements
* at this scoping level.
*/
final Statement statement;
/**
* Initialize a newly created scope, enclosed within the [outerScope],
* representing the given [statement].
*/
const ImplicitLabelScope._(this.outerScope, this.statement);
/**
* Return the statement which should be the target of an unlabeled `break` or
* `continue` statement, or `null` if there is no appropriate target.
*/
Statement getTarget(bool isContinue) {
if (outerScope == null) {
// This scope represents the toplevel of a function body, so it doesn't
// match either break or continue.
return null;
}
if (isContinue && statement is SwitchStatement) {
return outerScope.getTarget(isContinue);
}
return statement;
}
/**
* Initialize a newly created scope to represent a switch statement or loop
* nested within the current scope. [statement] is the statement associated
* with the newly created scope.
*/
ImplicitLabelScope nest(Statement statement) =>
new ImplicitLabelScope._(this, statement);
}
/**
* A scope in which a single label is defined.
*/
class LabelScope {
/**
* The label scope enclosing this label scope.
*/
final LabelScope _outerScope;
/**
* The label defined in this scope.
*/
final String _label;
/**
* The element to which the label resolves.
*/
final LabelElement element;
/**
* The AST node to which the label resolves.
*/
final AstNode node;
/**
* Initialize a newly created scope, enclosed within the [_outerScope],
* representing the label [_label]. The [node] is the AST node the label
* resolves to. The [element] is the element the label resolves to.
*/
LabelScope(this._outerScope, this._label, this.node, this.element);
/**
* Return the LabelScope which defines [targetLabel], or `null` if it is not
* defined in this scope.
*/
LabelScope lookup(String targetLabel) {
if (_label == targetLabel) {
return this;
}
return _outerScope?.lookup(targetLabel);
}
}
/**
* The scope containing all of the names available from imported libraries.
*/
class LibraryImportScope extends Scope {
/**
* The element representing the library in which this scope is enclosed.
*/
final LibraryElement _definingLibrary;
/**
* A list of the namespaces representing the names that are available in this scope from imported
* libraries.
*/
List<Namespace> _importedNamespaces;
/**
* A table mapping prefixes that have been referenced to a map from the names
* that have been referenced to the element associated with the prefixed name.
*/
Map<String, Map<String, Element>> _definedPrefixedNames;
/**
* Cache of public extensions defined in this library's imported namespaces.
*/
List<ExtensionElement> _extensions;
/**
* Initialize a newly created scope representing the names imported into the
* [_definingLibrary].
*/
LibraryImportScope(this._definingLibrary) {
_createImportedNamespaces();
}
@override
List<ExtensionElement> get extensions {
if (_extensions == null) {
_extensions = [];
List<ImportElement> imports = _definingLibrary.imports;
int count = imports.length;
for (int i = 0; i < count; i++) {
if (imports[i].prefix == null) {
for (var element in imports[i].namespace.definedNames.values) {
if (element is ExtensionElement && !_extensions.contains(element)) {
_extensions.add(element);
}
}
}
}
}
return _extensions;
}
@override
void define(Element element) {
if (!Scope.isPrivateName(element.displayName)) {
super.define(element);
}
}
@override
Source getSource(AstNode node) {
Source source = super.getSource(node);
if (source == null) {
source = _definingLibrary.definingCompilationUnit.source;
}
return source;
}
@override
Element internalLookup(
Identifier identifier, String name, LibraryElement referencingLibrary) {
Element element = localLookup(name, referencingLibrary);
if (element != null) {
return element;
}
element = _lookupInImportedNamespaces(
identifier, (Namespace namespace) => namespace.get(name));
if (element != null) {
defineNameWithoutChecking(name, element);
}
return element;
}
@override
bool shouldIgnoreUndefined(Identifier node) {
Iterable<NamespaceCombinator> getShowCombinators(
ImportElement importElement) =>
importElement.combinators.where((NamespaceCombinator combinator) =>
combinator is ShowElementCombinator);
if (node is PrefixedIdentifier) {
String prefix = node.prefix.name;
String name = node.identifier.name;
List<ImportElement> imports = _definingLibrary.imports;
int count = imports.length;
for (int i = 0; i < count; i++) {
ImportElement importElement = imports[i];
if (importElement.prefix?.name == prefix &&
importElement.importedLibrary?.isSynthetic != false) {
Iterable<NamespaceCombinator> showCombinators =
getShowCombinators(importElement);
if (showCombinators.isEmpty) {
return true;
}
for (ShowElementCombinator combinator in showCombinators) {
if (combinator.shownNames.contains(name)) {
return true;
}
}
}
}
} else if (node is SimpleIdentifier) {
String name = node.name;
List<ImportElement> imports = _definingLibrary.imports;
int count = imports.length;
for (int i = 0; i < count; i++) {
ImportElement importElement = imports[i];
if (importElement.prefix == null &&
importElement.importedLibrary?.isSynthetic != false) {
for (ShowElementCombinator combinator
in getShowCombinators(importElement)) {
if (combinator.shownNames.contains(name)) {
return true;
}
}
}
}
}
return false;
}
/**
* Create all of the namespaces associated with the libraries imported into
* this library. The names are not added to this scope, but are stored for
* later reference.
*/
void _createImportedNamespaces() {
List<ImportElement> imports = _definingLibrary.imports;
int count = imports.length;
_importedNamespaces = new List<Namespace>(count);
for (int i = 0; i < count; i++) {
_importedNamespaces[i] = imports[i].namespace;
}
}
/**
* Add the given [element] to this scope without checking for duplication or
* hiding.
*/
void _definePrefixedNameWithoutChecking(
String prefix, String name, Element element) {
_definedPrefixedNames ??= new HashMap<String, Map<String, Element>>();
Map<String, Element> unprefixedNames = _definedPrefixedNames.putIfAbsent(
prefix, () => new HashMap<String, Element>());
unprefixedNames[name] = element;
}
@override
Element _internalLookupPrefixed(PrefixedIdentifier identifier, String prefix,
String name, LibraryElement referencingLibrary) {
Element element = _localPrefixedLookup(prefix, name);
if (element != null) {
return element;
}
element = _lookupInImportedNamespaces(identifier.identifier,
(Namespace namespace) => namespace.getPrefixed(prefix, name));
if (element != null) {
_definePrefixedNameWithoutChecking(prefix, name, element);
}
return element;
}
/**
* Return the element with which the given [prefix] and [name] are associated,
* or `null` if the name is not defined within this scope.
*/
Element _localPrefixedLookup(String prefix, String name) {
if (_definedPrefixedNames != null) {
Map<String, Element> unprefixedNames = _definedPrefixedNames[prefix];
if (unprefixedNames != null) {
return unprefixedNames[name];
}
}
return null;
}
Element _lookupInImportedNamespaces(
Identifier identifier, Element lookup(Namespace namespace)) {
Element result;
bool hasPotentialConflict = false;
for (int i = 0; i < _importedNamespaces.length; i++) {
Element element = lookup(_importedNamespaces[i]);
if (element != null) {
if (result == null || result == element) {
result = element;
} else {
hasPotentialConflict = true;
}
}
}
if (hasPotentialConflict) {
var sdkElements = new Set<Element>();
var nonSdkElements = new Set<Element>();
for (int i = 0; i < _importedNamespaces.length; i++) {
Element element = lookup(_importedNamespaces[i]);
if (element != null) {
if (element is NeverElementImpl || element.library.isInSdk) {
sdkElements.add(element);
} else {
nonSdkElements.add(element);
}
}
}
if (sdkElements.length > 1 || nonSdkElements.length > 1) {
var conflictingElements = <Element>[]
..addAll(sdkElements)
..addAll(nonSdkElements);
return new MultiplyDefinedElementImpl(
_definingLibrary.context,
_definingLibrary.session,
conflictingElements.first.name,
conflictingElements);
}
if (nonSdkElements.isNotEmpty) {
result = nonSdkElements.first;
} else if (sdkElements.isNotEmpty) {
result = sdkElements.first;
}
}
return result;
}
}
/**
* A scope containing all of the names defined in a given library.
*/
class LibraryScope extends EnclosedScope {
List<ExtensionElement> _extensions = <ExtensionElement>[];
/**
* Initialize a newly created scope representing the names defined in the
* [definingLibrary].
*/
LibraryScope(LibraryElement definingLibrary)
: super(new LibraryImportScope(definingLibrary)) {
_defineTopLevelNames(definingLibrary);
// For `dart:core` to be able to pass analysis, it has to have `dynamic`
// added to its library scope. Note that this is not true of, for instance,
// `Object`, because `Object` has a source definition which is not possible
// for `dynamic`.
if (definingLibrary.isDartCore) {
define(DynamicElementImpl.instance);
}
}
@override
List<ExtensionElement> get extensions =>
enclosingScope.extensions.toList()..addAll(_extensions);
/**
* Add to this scope all of the public top-level names that are defined in the
* given [compilationUnit].
*/
void _defineLocalNames(CompilationUnitElement compilationUnit) {
for (PropertyAccessorElement element in compilationUnit.accessors) {
define(element);
}
for (ClassElement element in compilationUnit.enums) {
define(element);
}
for (ExtensionElement element in compilationUnit.extensions) {
define(element);
_extensions.add(element);
}
for (FunctionElement element in compilationUnit.functions) {
define(element);
}
for (FunctionTypeAliasElement element
in compilationUnit.functionTypeAliases) {
define(element);
}
for (ClassElement element in compilationUnit.mixins) {
define(element);
}
for (ClassElement element in compilationUnit.types) {
define(element);
}
}
/**
* Add to this scope all of the names that are explicitly defined in the
* [definingLibrary].
*/
void _defineTopLevelNames(LibraryElement definingLibrary) {
for (PrefixElement prefix in definingLibrary.prefixes) {
define(prefix);
}
_defineLocalNames(definingLibrary.definingCompilationUnit);
for (CompilationUnitElement compilationUnit in definingLibrary.parts) {
_defineLocalNames(compilationUnit);
}
}
}
/**
* A mapping of identifiers to the elements represented by those identifiers.
* Namespaces are the building blocks for scopes.
*/
class Namespace {
/**
* An empty namespace.
*/
static Namespace EMPTY = new Namespace(new HashMap<String, Element>());
/**
* A table mapping names that are defined in this namespace to the element
* representing the thing declared with that name.
*/
final Map<String, Element> _definedNames;
/**
* Initialize a newly created namespace to have the [_definedNames].
*/
Namespace(this._definedNames);
/**
* Return a table containing the same mappings as those defined by this
* namespace.
*/
Map<String, Element> get definedNames => _definedNames;
/**
* Return the element in this namespace that is available to the containing
* scope using the given name, or `null` if there is no such element.
*/
Element get(String name) => _definedNames[name];
/**
* Return the element in this namespace whose name is the result of combining
* the [prefix] and the [name], separated by a period, or `null` if there is
* no such element.
*/
Element getPrefixed(String prefix, String name) => null;
}
/**
* The builder used to build a namespace. Namespace builders are thread-safe and
* re-usable.
*/
class NamespaceBuilder {
/**
* Create a namespace representing the export namespace of the given [element].
*/
Namespace createExportNamespaceForDirective(ExportElement element) {
LibraryElement exportedLibrary = element.exportedLibrary;
if (exportedLibrary == null) {
//
// The exported library will be null if the URI does not reference a valid
// library.
//
return Namespace.EMPTY;
}
Map<String, Element> exportedNames = _getExportMapping(exportedLibrary);
exportedNames = _applyCombinators(exportedNames, element.combinators);
return new Namespace(exportedNames);
}
/**
* Create a namespace representing the export namespace of the given [library].
*/
Namespace createExportNamespaceForLibrary(LibraryElement library) {
Map<String, Element> exportedNames = _getExportMapping(library);
return new Namespace(exportedNames);
}
/**
* Create a namespace representing the import namespace of the given [element].
*/
Namespace createImportNamespaceForDirective(ImportElement element) {
LibraryElement importedLibrary = element.importedLibrary;
if (importedLibrary == null) {
//
// The imported library will be null if the URI does not reference a valid
// library.
//
return Namespace.EMPTY;
}
Map<String, Element> exportedNames = _getExportMapping(importedLibrary);
exportedNames = _applyCombinators(exportedNames, element.combinators);
PrefixElement prefix = element.prefix;
if (prefix != null) {
return new PrefixedNamespace(prefix.name, exportedNames);
}
return new Namespace(exportedNames);
}
/**
* Create a namespace representing the public namespace of the given
* [library].
*/
Namespace createPublicNamespaceForLibrary(LibraryElement library) {
Map<String, Element> definedNames = new HashMap<String, Element>();
_addPublicNames(definedNames, library.definingCompilationUnit);
for (CompilationUnitElement compilationUnit in library.parts) {
_addPublicNames(definedNames, compilationUnit);
}
// For libraries that import `dart:core` with a prefix, we have to add
// `dynamic` to the `dart:core` [Namespace] specially. Note that this is not
// true of, for instance, `Object`, because `Object` has a source definition
// which is not possible for `dynamic`.
if (library.isDartCore) {
definedNames['dynamic'] = DynamicElementImpl.instance;
definedNames['Never'] = BottomTypeImpl.instance.element;
}
return new Namespace(definedNames);
}
/**
* Add all of the names in the given [namespace] to the table of
* [definedNames].
*/
void _addAllFromNamespace(
Map<String, Element> definedNames, Namespace namespace) {
if (namespace != null) {
definedNames.addAll(namespace.definedNames);
}
}
/**
* Add the given [element] to the table of [definedNames] if it has a
* publicly visible name.
*/
void _addIfPublic(Map<String, Element> definedNames, Element element) {
String name = element.name;
if (name != null && name.isNotEmpty && !Scope.isPrivateName(name)) {
definedNames[name] = element;
}
}
/**
* Add to the table of [definedNames] all of the public top-level names that
* are defined in the given [compilationUnit].
* namespace
*/
void _addPublicNames(Map<String, Element> definedNames,
CompilationUnitElement compilationUnit) {
for (PropertyAccessorElement element in compilationUnit.accessors) {
_addIfPublic(definedNames, element);
}
for (ClassElement element in compilationUnit.enums) {
_addIfPublic(definedNames, element);
}
for (ExtensionElement element in compilationUnit.extensions) {
_addIfPublic(definedNames, element);
}
for (FunctionElement element in compilationUnit.functions) {
_addIfPublic(definedNames, element);
}
for (FunctionTypeAliasElement element
in compilationUnit.functionTypeAliases) {
_addIfPublic(definedNames, element);
}
for (ClassElement element in compilationUnit.mixins) {
_addIfPublic(definedNames, element);
}
for (ClassElement element in compilationUnit.types) {
_addIfPublic(definedNames, element);
}
}
/**
* Apply the given [combinators] to all of the names in the given table of
* [definedNames].
*/
Map<String, Element> _applyCombinators(Map<String, Element> definedNames,
List<NamespaceCombinator> combinators) {
for (NamespaceCombinator combinator in combinators) {
if (combinator is HideElementCombinator) {
definedNames = _hide(definedNames, combinator.hiddenNames);
} else if (combinator is ShowElementCombinator) {
definedNames = _show(definedNames, combinator.shownNames);
} else {
// Internal error.
AnalysisEngine.instance.logger
.logError("Unknown type of combinator: ${combinator.runtimeType}");
}
}
return definedNames;
}
/**
* Create a mapping table representing the export namespace of the given
* [library]. The set of [visitedElements] contains the libraries that do not
* need to be visited when processing the export directives of the given
* library because all of the names defined by them will be added by another
* library.
*/
Map<String, Element> _computeExportMapping(
LibraryElement library, HashSet<LibraryElement> visitedElements) {
visitedElements.add(library);
try {
Map<String, Element> definedNames = new HashMap<String, Element>();
for (ExportElement element in library.exports) {
LibraryElement exportedLibrary = element.exportedLibrary;
if (exportedLibrary != null &&
!visitedElements.contains(exportedLibrary)) {
//
// The exported library will be null if the URI does not reference a
// valid library.
//
Map<String, Element> exportedNames =
_computeExportMapping(exportedLibrary, visitedElements);
exportedNames = _applyCombinators(exportedNames, element.combinators);
definedNames.addAll(exportedNames);
}
}
_addAllFromNamespace(
definedNames,
createPublicNamespaceForLibrary(library),
);
return definedNames;
} finally {
visitedElements.remove(library);
}
}
Map<String, Element> _getExportMapping(LibraryElement library) {
if (library.exportNamespace != null) {
return library.exportNamespace.definedNames;
}
if (library is LibraryElementImpl) {
Map<String, Element> exportMapping =
_computeExportMapping(library, new HashSet<LibraryElement>());
library.exportNamespace = new Namespace(exportMapping);
return exportMapping;
}
return _computeExportMapping(library, new HashSet<LibraryElement>());
}
/**
* Return a new map of names which has all the names from [definedNames]
* with exception of [hiddenNames].
*/
Map<String, Element> _hide(
Map<String, Element> definedNames, List<String> hiddenNames) {
Map<String, Element> newNames =
new HashMap<String, Element>.from(definedNames);
for (String name in hiddenNames) {
newNames.remove(name);
newNames.remove("$name=");
}
return newNames;
}
/**
* Return a new map of names which has only [shownNames] from [definedNames].
*/
Map<String, Element> _show(
Map<String, Element> definedNames, List<String> shownNames) {
Map<String, Element> newNames = new HashMap<String, Element>();
for (String name in shownNames) {
Element element = definedNames[name];
if (element != null) {
newNames[name] = element;
}
String setterName = "$name=";
element = definedNames[setterName];
if (element != null) {
newNames[setterName] = element;
}
}
return newNames;
}
}
/**
* A mapping of identifiers to the elements represented by those identifiers.
* Namespaces are the building blocks for scopes.
*/
class PrefixedNamespace implements Namespace {
/**
* The prefix that is prepended to each of the defined names.
*/
final String _prefix;
/**
* The length of the prefix.
*/
final int _length;
/**
* A table mapping names that are defined in this namespace to the element
* representing the thing declared with that name.
*/
final Map<String, Element> _definedNames;
/**
* Initialize a newly created namespace to have the names resulting from
* prefixing each of the [_definedNames] with the given [_prefix] (and a
* period).
*/
PrefixedNamespace(String prefix, this._definedNames)
: _prefix = prefix,
_length = prefix.length;
@override
Map<String, Element> get definedNames {
Map<String, Element> definedNames = <String, Element>{};
_definedNames.forEach((String name, Element element) {
definedNames["$_prefix.$name"] = element;
});
return definedNames;
}
@override
Element get(String name) {
if (name.length > _length && name.startsWith(_prefix)) {
if (name.codeUnitAt(_length) == '.'.codeUnitAt(0)) {
return _definedNames[name.substring(_length + 1)];
}
}
return null;
}
@override
Element getPrefixed(String prefix, String name) {
if (prefix == _prefix) {
return _definedNames[name];
}
return null;
}
}
/**
* A name scope used by the resolver to determine which names are visible at any
* given point in the code.
*/
abstract class Scope {
/**
* The prefix used to mark an identifier as being private to its library.
*/
static int PRIVATE_NAME_PREFIX = 0x5F;
/**
* The suffix added to the declared name of a setter when looking up the
* setter. Used to disambiguate between a getter and a setter that have the
* same name.
*/
static String SETTER_SUFFIX = "=";
/**
* The name used to look up the method used to implement the unary minus
* operator. Used to disambiguate between the unary and binary operators.
*/
static String UNARY_MINUS = "unary-";
/**
* A table mapping names that are defined in this scope to the element
* representing the thing declared with that name.
*/
Map<String, Element> _definedNames;
/**
* Return the scope in which this scope is lexically enclosed.
*/
Scope get enclosingScope => null;
/**
* The list of extensions defined in this scope.
*/
List<ExtensionElement> get extensions =>
enclosingScope == null ? <ExtensionElement>[] : enclosingScope.extensions;
/**
* Add the given [element] to this scope. If there is already an element with
* the given name defined in this scope, then the original element will
* continue to be mapped to the name.
*/
void define(Element element) {
String name = _getName(element);
if (name != null && name.isNotEmpty) {
_definedNames ??= new HashMap<String, Element>();
_definedNames.putIfAbsent(name, () => element);
}
}
/**
* Add the given [element] to this scope without checking for duplication or
* hiding.
*/
void defineNameWithoutChecking(String name, Element element) {
_definedNames ??= new HashMap<String, Element>();
_definedNames[name] = element;
}
/**
* Add the given [element] to this scope without checking for duplication or
* hiding.
*/
void defineWithoutChecking(Element element) {
_definedNames ??= new HashMap<String, Element>();
_definedNames[_getName(element)] = element;
}
/**
* Return the source that contains the given [identifier], or the source
* associated with this scope if the source containing the identifier could
* not be determined.
*/
Source getSource(AstNode identifier) {
CompilationUnit unit = identifier.thisOrAncestorOfType<CompilationUnit>();
if (unit != null) {
CompilationUnitElement unitElement = unit.declaredElement;
if (unitElement != null) {
return unitElement.source;
}
}
return null;
}
/**
* Return the element with which the given [name] is associated, or `null` if
* the name is not defined within this scope. The [identifier] is the
* identifier node to lookup element for, used to report correct kind of a
* problem and associate problem with. The [referencingLibrary] is the library
* that contains the reference to the name, used to implement library-level
* privacy.
*/
Element internalLookup(
Identifier identifier, String name, LibraryElement referencingLibrary);
/**
* Return the element with which the given [name] is associated, or `null` if
* the name is not defined within this scope. This method only returns
* elements that are directly defined within this scope, not elements that are
* defined in an enclosing scope. The [referencingLibrary] is the library that
* contains the reference to the name, used to implement library-level privacy.
*/
Element localLookup(String name, LibraryElement referencingLibrary) {
if (_definedNames != null) {
return _definedNames[name];
}
return null;
}
/**
* Return the element with which the given [identifier] is associated, or
* `null` if the name is not defined within this scope. The
* [referencingLibrary] is the library that contains the reference to the
* name, used to implement library-level privacy.
*/
Element lookup(Identifier identifier, LibraryElement referencingLibrary) {
if (identifier is PrefixedIdentifier) {
return _internalLookupPrefixed(identifier, identifier.prefix.name,
identifier.identifier.name, referencingLibrary);
}
return internalLookup(identifier, identifier.name, referencingLibrary);
}
/**
* Return `true` if the fact that the given [node] is not defined should be
* ignored (from the perspective of error reporting). This will be the case if
* there is at least one import that defines the node's prefix, and if that
* import either has no show combinators or has a show combinator that
* explicitly lists the node's name.
*/
bool shouldIgnoreUndefined(Identifier node) {
if (enclosingScope != null) {
return enclosingScope.shouldIgnoreUndefined(node);
}
return false;
}
/**
* Return the name that will be used to look up the given [element].
*/
String _getName(Element element) {
if (element is MethodElement) {
MethodElement method = element;
if (method.name == "-" && method.parameters.isEmpty) {
return UNARY_MINUS;
}
}
return element.name;
}
/**
* Return the element with which the given [prefix] and [name] are associated,
* or `null` if the name is not defined within this scope. The [identifier] is
* the identifier node to lookup element for, used to report correct kind of a
* problem and associate problem with. The [referencingLibrary] is the library
* that contains the reference to the name, used to implement library-level
* privacy.
*/
Element _internalLookupPrefixed(PrefixedIdentifier identifier, String prefix,
String name, LibraryElement referencingLibrary);
/**
* Return `true` if the given [name] is a library-private name.
*/
static bool isPrivateName(String name) =>
name != null && StringUtilities.startsWithChar(name, PRIVATE_NAME_PREFIX);
}
/**
* The scope defined by the type parameters in an element that defines type
* parameters.
*/
class TypeParameterScope extends EnclosedScope {
/**
* Initialize a newly created scope, enclosed within the [enclosingScope],
* that defines the type parameters from the given [element].
*/
TypeParameterScope(Scope enclosingScope, TypeParameterizedElement element)
: super(enclosingScope) {
if (element == null) {
throw new ArgumentError("element cannot be null");
}
_defineTypeParameters(element);
}
/**
* Define the type parameters declared by the [element].
*/
void _defineTypeParameters(TypeParameterizedElement element) {
for (TypeParameterElement typeParameter in element.typeParameters) {
define(typeParameter);
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/method_invocation_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 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/element/inheritance_manager3.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/dart/resolver/extension_member_resolver.dart';
import 'package:analyzer/src/dart/resolver/resolution_result.dart';
import 'package:analyzer/src/dart/resolver/scope.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/super_context.dart';
import 'package:analyzer/src/generated/variable_type_provider.dart';
class MethodInvocationResolver {
static final _nameCall = new Name(null, 'call');
/// The resolver driving this participant.
final ResolverVisitor _resolver;
/// The type representing the type 'dynamic'.
final DynamicTypeImpl _dynamicType = DynamicTypeImpl.instance;
/// The type representing the type 'type'.
final InterfaceType _typeType;
/// The manager for the inheritance mappings.
final InheritanceManager3 _inheritance;
/// The element for the library containing the compilation unit being visited.
final LibraryElement _definingLibrary;
/// The URI of [_definingLibrary].
final Uri _definingLibraryUri;
/// The object providing promoted or declared types of variables.
final LocalVariableTypeProvider _localVariableTypeProvider;
/// Helper for extension method resolution.
final ExtensionMemberResolver _extensionResolver;
/// The invocation being resolved.
MethodInvocationImpl _invocation;
/// The [Name] object of the invocation being resolved by [resolve].
Name _currentName;
MethodInvocationResolver(this._resolver)
: _typeType = _resolver.typeProvider.typeType,
_inheritance = _resolver.inheritance,
_definingLibrary = _resolver.definingLibrary,
_definingLibraryUri = _resolver.definingLibrary.source.uri,
_localVariableTypeProvider = _resolver.localVariableTypeProvider,
_extensionResolver = _resolver.extensionResolver;
/// The scope used to resolve identifiers.
Scope get nameScope => _resolver.nameScope;
void resolve(MethodInvocation node) {
_invocation = node;
SimpleIdentifier nameNode = node.methodName;
String name = nameNode.name;
_currentName = Name(_definingLibraryUri, name);
//
// Synthetic identifiers have been already reported during parsing.
//
if (nameNode.isSynthetic) {
return;
}
Expression receiver = node.realTarget;
if (receiver == null) {
_resolveReceiverNull(node, nameNode, name);
return;
}
if (receiver is NullLiteral) {
_setDynamicResolution(node);
return;
}
if (receiver is SimpleIdentifier) {
var receiverElement = receiver.staticElement;
if (receiverElement is PrefixElement) {
_resolveReceiverPrefix(node, receiver, receiverElement, nameNode, name);
return;
}
}
if (receiver is Identifier) {
var receiverElement = receiver.staticElement;
if (receiverElement is ExtensionElement) {
_resolveExtensionMember(
node, receiver, receiverElement, nameNode, name);
return;
}
}
if (receiver is SuperExpression) {
_resolveReceiverSuper(node, receiver, nameNode, name);
return;
}
if (receiver is ExtensionOverride) {
_resolveExtensionOverride(node, receiver, nameNode, name);
return;
}
ClassElement typeReference = getTypeReference(receiver);
if (typeReference != null) {
_resolveReceiverTypeLiteral(node, typeReference, nameNode, name);
return;
}
DartType receiverType = receiver.staticType;
receiverType = _resolveTypeParameter(receiverType);
if (receiverType is InterfaceType) {
_resolveReceiverInterfaceType(node, receiverType, nameNode, name);
return;
}
if (receiverType is DynamicTypeImpl) {
_resolveReceiverDynamic(node, name);
return;
}
if (receiverType is FunctionType) {
_resolveReceiverFunctionType(
node, receiver, receiverType, nameNode, name);
return;
}
if (receiverType is VoidType) {
_reportUseOfVoidType(node, receiver);
return;
}
if (receiverType == BottomTypeImpl.instance) {
_reportUseOfNeverType(node, receiver);
return;
}
}
/// Given an [argumentList] and the executable [element] that will be invoked
/// using those arguments, compute the list of parameters that correspond to
/// the list of arguments. Return the parameters that correspond to the
/// arguments, or `null` if no correspondence could be computed.
List<ParameterElement> _computeCorrespondingParameters(
ArgumentList argumentList, DartType type) {
if (type is InterfaceType) {
MethodElement callMethod =
type.lookUpMethod(FunctionElement.CALL_METHOD_NAME, _definingLibrary);
if (callMethod != null) {
return _resolveArgumentsToFunction(argumentList, callMethod);
}
} else if (type is FunctionType) {
return _resolveArgumentsToParameters(argumentList, type.parameters);
}
return null;
}
/// If the invoked [target] is a getter, then actually the return type of
/// the [target] is invoked. So, remember the [target] into
/// [MethodInvocationImpl.methodNameType] and return the actual invoked type.
DartType _getCalleeType(MethodInvocation node, ExecutableElement target) {
if (target.kind == ElementKind.GETTER) {
(node as MethodInvocationImpl).methodNameType = target.type;
var calleeType = target.returnType;
calleeType = _resolveTypeParameter(calleeType);
return calleeType;
}
return target.type;
}
/// Check for a generic type, and apply type arguments.
FunctionType _instantiateFunctionType(
FunctionType invokeType, TypeArgumentList typeArguments, AstNode node) {
var typeFormals = invokeType.typeFormals;
var arguments = typeArguments?.arguments;
if (arguments != null && arguments.length != typeFormals.length) {
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS_METHOD,
node,
[invokeType, typeFormals.length, arguments?.length ?? 0]);
arguments = null;
}
if (typeFormals.isNotEmpty) {
if (arguments == null) {
var typeArguments =
_resolver.typeSystem.instantiateTypeFormalsToBounds(typeFormals);
_invocation.typeArgumentTypes = typeArguments;
return invokeType.instantiate(typeArguments);
} else {
var typeArguments = arguments.map((n) => n.type).toList();
_invocation.typeArgumentTypes = typeArguments;
return invokeType.instantiate(typeArguments);
}
} else {
_invocation.typeArgumentTypes = const <DartType>[];
}
return invokeType;
}
bool _isCoreFunction(DartType type) {
// TODO(scheglov) Can we optimize this?
return type is InterfaceType && type.isDartCoreFunction;
}
ExecutableElement _lookUpClassMember(ClassElement element, String name) {
// TODO(scheglov) Use class hierarchy.
return element.lookUpMethod(name, _definingLibrary);
}
void _reportInvocationOfNonFunction(MethodInvocation node) {
_setDynamicResolution(node, setNameTypeToDynamic: false);
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION,
node.methodName,
[node.methodName.name],
);
}
void _reportPrefixIdentifierNotFollowedByDot(SimpleIdentifier target) {
_resolver.errorReporter.reportErrorForNode(
CompileTimeErrorCode.PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT,
target,
[target.name],
);
}
void _reportUndefinedFunction(
MethodInvocation node, Identifier ignorableIdentifier) {
_setDynamicResolution(node);
// TODO(scheglov) This is duplication.
if (nameScope.shouldIgnoreUndefined(ignorableIdentifier)) {
return;
}
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode.UNDEFINED_FUNCTION,
node.methodName,
[node.methodName.name],
);
}
void _reportUndefinedMethod(
MethodInvocation node, String name, ClassElement typeReference) {
_setDynamicResolution(node);
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode.UNDEFINED_METHOD,
node.methodName,
[name, typeReference.displayName],
);
}
void _reportUseOfNeverType(MethodInvocation node, AstNode errorNode) {
_setDynamicResolution(node);
_resolver.errorReporter.reportErrorForNode(
StaticWarningCode.INVALID_USE_OF_NEVER_VALUE,
errorNode,
);
}
void _reportUseOfVoidType(MethodInvocation node, AstNode errorNode) {
_setDynamicResolution(node);
_resolver.errorReporter.reportErrorForNode(
StaticWarningCode.USE_OF_VOID_RESULT,
errorNode,
);
}
/// Given an [argumentList] and the [executableElement] that will be invoked
/// using those argument, compute the list of parameters that correspond to
/// the list of arguments. An error will be reported if any of the arguments
/// cannot be matched to a parameter. Return the parameters that correspond to
/// the arguments, or `null` if no correspondence could be computed.
List<ParameterElement> _resolveArgumentsToFunction(
ArgumentList argumentList, ExecutableElement executableElement) {
if (executableElement == null) {
return null;
}
List<ParameterElement> parameters = executableElement.parameters;
return _resolveArgumentsToParameters(argumentList, parameters);
}
/// Given an [argumentList] and the [parameters] related to the element that
/// will be invoked using those arguments, compute the list of parameters that
/// correspond to the list of arguments. An error will be reported if any of
/// the arguments cannot be matched to a parameter. Return the parameters that
/// correspond to the arguments.
List<ParameterElement> _resolveArgumentsToParameters(
ArgumentList argumentList, List<ParameterElement> parameters) {
return ResolverVisitor.resolveArgumentsToParameters(
argumentList, parameters, _resolver.errorReporter.reportErrorForNode);
}
/// Given that we are accessing a property of the given [classElement] with the
/// given [propertyName], return the element that represents the property.
Element _resolveElement(
ClassElement classElement, SimpleIdentifier propertyName) {
// TODO(scheglov) Replace with class hierarchy.
String name = propertyName.name;
Element element;
if (propertyName.inSetterContext()) {
element = classElement.getSetter(name);
}
if (element == null) {
element = classElement.getGetter(name);
}
if (element == null) {
element = classElement.getMethod(name);
}
if (element != null && element.isAccessibleIn(_definingLibrary)) {
return element;
}
return null;
}
/// If there is an extension matching the [receiverType] and defining a
/// member with the given [name], resolve to the corresponding extension
/// method. Return a result indicating whether the [node] was resolved and if
/// not why.
ResolutionResult _resolveExtension(
MethodInvocation node,
DartType receiverType,
SimpleIdentifier nameNode,
String name,
) {
var result = _extensionResolver.findExtension(
receiverType,
name,
nameNode,
);
if (!result.isSingle) {
_setDynamicResolution(node);
return result;
}
ExecutableElement member = result.getter;
nameNode.staticElement = member;
if (member.isStatic) {
_setDynamicResolution(node);
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER,
nameNode,
[name, member.kind.displayName, member.enclosingElement.name]);
return result;
}
var calleeType = _getCalleeType(node, member);
_setResolution(node, calleeType);
return result;
}
void _resolveExtensionMember(MethodInvocation node, Identifier receiver,
ExtensionElement extension, SimpleIdentifier nameNode, String name) {
ExecutableElement element =
extension.getMethod(name) ?? extension.getGetter(name);
if (element == null) {
_setDynamicResolution(node);
_resolver.errorReporter.reportErrorForNode(
CompileTimeErrorCode.UNDEFINED_EXTENSION_METHOD,
nameNode,
[name, extension.name],
);
} else {
if (!element.isStatic) {
_resolver.errorReporter.reportErrorForNode(
StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER,
nameNode,
[name]);
}
nameNode.staticElement = element;
_setResolution(node, _getCalleeType(node, element));
}
}
void _resolveExtensionOverride(MethodInvocation node,
ExtensionOverride override, SimpleIdentifier nameNode, String name) {
var result = _extensionResolver.getOverrideMember(override, name);
var member = result.getter;
if (member == null) {
_setDynamicResolution(node);
_resolver.errorReporter.reportErrorForNode(
CompileTimeErrorCode.UNDEFINED_EXTENSION_METHOD,
nameNode,
[name, override.staticElement.name],
);
return;
}
if (member.isStatic) {
_resolver.errorReporter.reportErrorForNode(
CompileTimeErrorCode.EXTENSION_OVERRIDE_ACCESS_TO_STATIC_MEMBER,
nameNode,
);
}
if (node.isCascaded) {
// Report this error and recover by treating it like a non-cascade.
_resolver.errorReporter.reportErrorForToken(
CompileTimeErrorCode.EXTENSION_OVERRIDE_WITH_CASCADE, node.operator);
}
nameNode.staticElement = member;
var calleeType = _getCalleeType(node, member);
_setResolution(node, calleeType);
}
void _resolveReceiverDynamic(MethodInvocation node, String name) {
_setDynamicResolution(node);
}
void _resolveReceiverFunctionType(MethodInvocation node, Expression receiver,
FunctionType receiverType, SimpleIdentifier nameNode, String name) {
if (name == FunctionElement.CALL_METHOD_NAME) {
_setResolution(node, receiverType);
// TODO(scheglov) Replace this with using FunctionType directly.
// Here was erase resolution that _setResolution() sets.
nameNode.staticElement = null;
nameNode.staticType = _dynamicType;
return;
}
ResolutionResult result =
_extensionResolver.findExtension(receiverType, name, nameNode);
if (result.isSingle) {
nameNode.staticElement = result.getter;
var calleeType = _getCalleeType(node, result.getter);
return _setResolution(node, calleeType);
} else if (result.isAmbiguous) {
return;
}
// We can invoke Object methods on Function.
var member = _inheritance.getMember(
_resolver.typeProvider.functionType,
new Name(null, name),
);
if (member != null) {
nameNode.staticElement = member;
return _setResolution(node, member.type);
}
_reportUndefinedMethod(
node,
name,
_resolver.typeProvider.functionType.element,
);
}
void _resolveReceiverInterfaceType(MethodInvocation node,
InterfaceType receiverType, SimpleIdentifier nameNode, String name) {
if (_isCoreFunction(receiverType) &&
name == FunctionElement.CALL_METHOD_NAME) {
_setDynamicResolution(node);
return;
}
var target = _inheritance.getMember(receiverType, _currentName);
if (target != null) {
nameNode.staticElement = target;
var calleeType = _getCalleeType(node, target);
return _setResolution(node, calleeType);
}
// Look for an applicable extension.
var result = _resolveExtension(node, receiverType, nameNode, name);
if (result.isSingle) {
return;
}
// The interface of the receiver does not have an instance member.
// Try to recover and find a member in the class.
var targetElement = _lookUpClassMember(receiverType.element, name);
if (targetElement != null && targetElement.isStatic) {
nameNode.staticElement = targetElement;
_setDynamicResolution(node);
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER,
nameNode,
[
name,
targetElement.kind.displayName,
targetElement.enclosingElement.displayName,
],
);
return;
}
_setDynamicResolution(node);
if (result.isNone) {
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode.UNDEFINED_METHOD,
nameNode,
[name, receiverType.element.displayName],
);
}
}
void _resolveReceiverNull(
MethodInvocation node, SimpleIdentifier nameNode, String name) {
var element = nameScope.lookup(nameNode, _definingLibrary);
if (element != null) {
nameNode.staticElement = element;
if (element is MultiplyDefinedElement) {
MultiplyDefinedElement multiply = element;
element = multiply.conflictingElements[0];
}
if (element is ExecutableElement) {
var calleeType = _getCalleeType(node, element);
return _setResolution(node, calleeType);
}
if (element is VariableElement) {
var targetType = _localVariableTypeProvider.getType(nameNode);
return _setResolution(node, targetType);
}
// TODO(scheglov) This is a questionable distinction.
if (element is PrefixElement) {
_setDynamicResolution(node);
return _reportPrefixIdentifierNotFollowedByDot(nameNode);
}
return _reportInvocationOfNonFunction(node);
}
InterfaceType receiverType;
ClassElement enclosingClass = _resolver.enclosingClass;
if (enclosingClass == null) {
if (_resolver.enclosingExtension == null) {
return _reportUndefinedFunction(node, node.methodName);
}
var extendedType =
_resolveTypeParameter(_resolver.enclosingExtension.extendedType);
if (extendedType is InterfaceType) {
receiverType = extendedType;
} else if (extendedType is FunctionType) {
receiverType = _resolver.typeProvider.functionType;
} else {
return _reportUndefinedFunction(node, node.methodName);
}
enclosingClass = receiverType.element;
} else {
receiverType = enclosingClass.thisType;
}
var target = _inheritance.getMember(receiverType, _currentName);
if (target != null) {
nameNode.staticElement = target;
var calleeType = _getCalleeType(node, target);
return _setResolution(node, calleeType);
}
var targetElement = _lookUpClassMember(enclosingClass, name);
if (targetElement != null && targetElement.isStatic) {
nameNode.staticElement = targetElement;
_setDynamicResolution(node);
if (_resolver.enclosingExtension != null) {
_resolver.errorReporter.reportErrorForNode(
CompileTimeErrorCode
.UNQUALIFIED_REFERENCE_TO_STATIC_MEMBER_OF_EXTENDED_TYPE,
nameNode,
[targetElement.enclosingElement.displayName]);
} else {
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode
.UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER,
nameNode,
[targetElement.enclosingElement.displayName]);
}
return;
}
var result = _extensionResolver.findExtension(receiverType, name, nameNode);
if (result.isSingle) {
var target = result.getter;
if (target != null) {
nameNode.staticElement = target;
var calleeType = _getCalleeType(node, target);
_setResolution(node, calleeType);
return;
}
}
return _reportUndefinedMethod(node, name, enclosingClass);
}
void _resolveReceiverPrefix(MethodInvocation node, SimpleIdentifier receiver,
PrefixElement prefix, SimpleIdentifier nameNode, String name) {
// Note: prefix?.bar is reported as an error in ElementResolver.
if (name == FunctionElement.LOAD_LIBRARY_NAME) {
var imports = _definingLibrary.getImportsWithPrefix(prefix);
if (imports.length == 1 && imports[0].isDeferred) {
var importedLibrary = imports[0].importedLibrary;
var loadLibraryFunction = importedLibrary?.loadLibraryFunction;
nameNode.staticElement = loadLibraryFunction;
node.staticInvokeType = loadLibraryFunction?.type;
node.staticType = loadLibraryFunction?.returnType;
_setExplicitTypeArgumentTypes();
return;
}
}
// TODO(scheglov) I don't like how we resolve prefixed names.
// But maybe this is the only one solution.
var prefixedName = new PrefixedIdentifierImpl.temp(receiver, nameNode);
var element = nameScope.lookup(prefixedName, _definingLibrary);
nameNode.staticElement = element;
if (element is MultiplyDefinedElement) {
MultiplyDefinedElement multiply = element;
element = multiply.conflictingElements[0];
}
if (element is ExecutableElement) {
var calleeType = _getCalleeType(node, element);
return _setResolution(node, calleeType);
}
_reportUndefinedFunction(node, prefixedName);
}
void _resolveReceiverSuper(MethodInvocation node, SuperExpression receiver,
SimpleIdentifier nameNode, String name) {
var enclosingClass = _resolver.enclosingClass;
if (SuperContext.of(receiver) != SuperContext.valid) {
return;
}
var receiverType = enclosingClass.thisType;
var target = _inheritance.getMember(
receiverType,
_currentName,
forSuper: true,
);
// If there is that concrete dispatch target, then we are done.
if (target != null) {
nameNode.staticElement = target;
var calleeType = _getCalleeType(node, target);
_setResolution(node, calleeType);
return;
}
// Otherwise, this is an error.
// But we would like to give the user at least some resolution.
// So, we try to find the interface target.
target = _inheritance.getInherited(receiverType, _currentName);
if (target != null) {
nameNode.staticElement = target;
var calleeType = _getCalleeType(node, target);
_setResolution(node, calleeType);
_resolver.errorReporter.reportErrorForNode(
CompileTimeErrorCode.ABSTRACT_SUPER_MEMBER_REFERENCE,
nameNode,
[target.kind.displayName, name]);
return;
}
// Nothing help, there is no target at all.
_setDynamicResolution(node);
_resolver.errorReporter.reportErrorForNode(
StaticTypeWarningCode.UNDEFINED_SUPER_METHOD,
nameNode,
[name, enclosingClass.displayName]);
}
void _resolveReceiverTypeLiteral(MethodInvocation node, ClassElement receiver,
SimpleIdentifier nameNode, String name) {
if (node.isCascaded) {
receiver = _typeType.element;
}
var element = _resolveElement(receiver, nameNode);
if (element != null) {
if (element is ExecutableElement) {
nameNode.staticElement = element;
var calleeType = _getCalleeType(node, element);
_setResolution(node, calleeType);
} else {
_reportInvocationOfNonFunction(node);
}
return;
}
_reportUndefinedMethod(node, name, receiver);
}
/// If the given [type] is a type parameter, replace with its bound.
/// Otherwise, return the original type.
DartType _resolveTypeParameter(DartType type) {
if (type is TypeParameterType) {
return type.resolveToBound(_resolver.typeProvider.objectType);
}
return type;
}
void _setDynamicResolution(MethodInvocation node,
{bool setNameTypeToDynamic: true}) {
if (setNameTypeToDynamic) {
node.methodName.staticType = _dynamicType;
}
node.staticInvokeType = _dynamicType;
node.staticType = _dynamicType;
_setExplicitTypeArgumentTypes();
}
/// Set explicitly specified type argument types, or empty if not specified.
/// Inference is done in type analyzer, so inferred type arguments might be
/// set later.
void _setExplicitTypeArgumentTypes() {
var typeArgumentList = _invocation.typeArguments;
if (typeArgumentList != null) {
var arguments = typeArgumentList.arguments;
_invocation.typeArgumentTypes = arguments.map((n) => n.type).toList();
} else {
_invocation.typeArgumentTypes = [];
}
}
void _setResolution(MethodInvocation node, DartType type) {
// TODO(scheglov) We need this for StaticTypeAnalyzer to run inference.
// But it seems weird. Do we need to know the raw type of a function?!
node.methodName.staticType = type;
if (type == _dynamicType || _isCoreFunction(type)) {
_setDynamicResolution(node, setNameTypeToDynamic: false);
return;
}
if (type is InterfaceType) {
var call = _inheritance.getMember(type, _nameCall);
if (call == null) {
var result = _extensionResolver.findExtension(
type, _nameCall.name, node.methodName);
if (result.isSingle) {
call = result.getter;
} else if (result.isAmbiguous) {
return;
}
}
if (call != null && call.kind == ElementKind.METHOD) {
type = call.type;
}
}
if (type is FunctionType) {
// TODO(scheglov) Extract this when receiver is already FunctionType?
var instantiatedType = _instantiateFunctionType(
type,
node.typeArguments,
node.methodName,
);
instantiatedType = _toSyntheticFunctionType(instantiatedType);
node.staticInvokeType = instantiatedType;
node.staticType = instantiatedType.returnType;
// TODO(scheglov) too much magic
node.argumentList.correspondingStaticParameters =
_computeCorrespondingParameters(
node.argumentList,
instantiatedType,
);
return;
}
if (type is VoidType) {
return _reportUseOfVoidType(node, node.methodName);
}
if (type == BottomTypeImpl.instance) {
return _reportUseOfNeverType(node, node.methodName);
}
_reportInvocationOfNonFunction(node);
}
/// Checks whether the given [expression] is a reference to a class. If it is
/// then the element representing the class is returned, otherwise `null` is
/// returned.
static ClassElement getTypeReference(Expression expression) {
if (expression is Identifier) {
Element staticElement = expression.staticElement;
if (staticElement is ClassElement) {
return staticElement;
}
}
return null;
}
/// As an experiment for using synthetic [FunctionType]s, we replace some
/// function types with the equivalent synthetic function type instance.
/// The assumption that we try to prove is that only the set of parameters,
/// with their names, types and kinds is important, but the element that
/// encloses them is not (`null` for synthetic function types).
static FunctionType _toSyntheticFunctionType(FunctionType type) {
// if (type.element is GenericFunctionTypeElement) {
// var synthetic = FunctionTypeImpl.synthetic(
// type.returnType,
// type.typeFormals.map((e) {
// return TypeParameterElementImpl.synthetic(e.name)..bound = e.bound;
// }).toList(),
// type.parameters.map((p) {
// return ParameterElementImpl.synthetic(
// p.name,
// p.type,
// // ignore: deprecated_member_use_from_same_package
// p.parameterKind,
// );
// }).toList(),
// );
// return synthetic;
// }
return type;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/variance.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:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
/// Computes the variance of the [typeParameter] in the [type].
int computeVariance(TypeParameterElement typeParameter, DartType type) {
if (type is TypeParameterType) {
if (type.element == typeParameter) {
return Variance.covariant;
} else {
return Variance.unrelated;
}
} else if (type is InterfaceType) {
var result = Variance.unrelated;
for (var argument in type.typeArguments) {
result = Variance.meet(
result,
computeVariance(typeParameter, argument),
);
}
return result;
} else if (type is FunctionType) {
var result = computeVariance(typeParameter, type.returnType);
for (var parameter in type.typeFormals) {
// If [parameter] is referenced in the bound at all, it makes the
// variance of [parameter] in the entire type invariant. The invocation
// of [computeVariance] below is made to simply figure out if [variable]
// occurs in the bound.
var bound = parameter.bound;
if (bound != null &&
computeVariance(typeParameter, bound) != Variance.unrelated) {
result = Variance.invariant;
}
}
for (var parameter in type.parameters) {
result = Variance.meet(
result,
Variance.combine(
Variance.contravariant,
computeVariance(typeParameter, parameter.type),
),
);
}
return result;
}
return Variance.unrelated;
}
/// Value set for variance of a type parameter `X` in a type `T`.
class Variance {
/// Used when `X` does not occur free in `T`.
static const int unrelated = 0;
/// Used when `X` occurs free in `T`, and `U <: V` implies `[U/X]T <: [V/X]T`.
static const int covariant = 1;
/// Used when `X` occurs free in `T`, and `U <: V` implies `[V/X]T <: [U/X]T`.
static const int contravariant = 2;
/// Used when there exists a pair `U` and `V` such that `U <: V`, but
/// `[U/X]T` and `[V/X]T` are incomparable.
static const int invariant = 3;
/// Combines variances of `X` in `T` and `Y` in `S` into variance of `X` in
/// `[Y/T]S`.
///
/// Consider the following examples:
///
/// * variance of `X` in `Function(X)` is [contravariant], variance of `Y`
/// in `List<Y>` is [covariant], so variance of `X` in `List<Function(X)>` is
/// [contravariant];
///
/// * variance of `X` in `List<X>` is [covariant], variance of `Y` in
/// `Function(Y)` is [contravariant], so variance of `X` in
/// `Function(List<X>)` is [contravariant];
///
/// * variance of `X` in `Function(X)` is [contravariant], variance of `Y` in
/// `Function(Y)` is [contravariant], so variance of `X` in
/// `Function(Function(X))` is [covariant];
///
/// * let the following be declared:
///
/// typedef F<Z> = Function();
///
/// then variance of `X` in `F<X>` is [unrelated], variance of `Y` in
/// `List<Y>` is [covariant], so variance of `X` in `List<F<X>>` is
/// [unrelated];
///
/// * let the following be declared:
///
/// typedef G<Z> = Z Function(Z);
///
/// then variance of `X` in `List<X>` is [covariant], variance of `Y` in
/// `G<Y>` is [invariant], so variance of `X` in `G<List<X>>` is [invariant].
static int combine(int a, int b) {
if (a == unrelated || b == unrelated) return unrelated;
if (a == invariant || b == invariant) return invariant;
return a == b ? covariant : contravariant;
}
/// Variance values form a lattice where [unrelated] is the top, [invariant]
/// is the bottom, and [covariant] and [contravariant] are incomparable.
/// [meet] calculates the meet of two elements of such lattice. It can be
/// used, for example, to calculate the variance of a typedef type parameter
/// if it's encountered on the RHS of the typedef multiple times.
static int meet(int a, int b) => a | b;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/inheritance_manager.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/standard_ast_factory.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/generated/type_system.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
/**
* Instances of the class `InheritanceManager` manage the knowledge of where class members
* (methods, getters & setters) are inherited from.
*/
@Deprecated('Use InheritanceManager3 instead.')
class InheritanceManager {
/**
* The [LibraryElement] that is managed by this manager.
*/
LibraryElement _library;
/**
* A flag indicating whether abstract methods should be included when looking
* up the superclass chain.
*/
bool _includeAbstractFromSuperclasses;
/**
* This is a mapping between each [ClassElement] and a map between the [String] member
* names and the associated [ExecutableElement] in the mixin and superclass chain.
*/
Map<ClassElement, Map<String, ExecutableElement>> _classLookup;
/**
* This is a mapping between each [ClassElement] and a map between the [String] member
* names and the associated [ExecutableElement] in the interface set.
*/
Map<ClassElement, Map<String, ExecutableElement>> _interfaceLookup;
/**
* Initialize a newly created inheritance manager.
*
* @param library the library element context that the inheritance mappings are being generated
*/
InheritanceManager(LibraryElement library,
{bool includeAbstractFromSuperclasses: false}) {
this._library = library;
_includeAbstractFromSuperclasses = includeAbstractFromSuperclasses;
_classLookup = new HashMap<ClassElement, Map<String, ExecutableElement>>();
_interfaceLookup =
new HashMap<ClassElement, Map<String, ExecutableElement>>();
}
/**
* Set the new library element context.
*
* @param library the new library element
*/
void set libraryElement(LibraryElement library) {
this._library = library;
}
/**
* Get and return a mapping between the set of all string names of the members inherited from the
* passed [ClassElement] superclass hierarchy, and the associated [ExecutableElement].
*
* @param classElt the class element to query
* @return a mapping between the set of all members inherited from the passed [ClassElement]
* superclass hierarchy, and the associated [ExecutableElement]
*/
@Deprecated('Use InheritanceManager3.getInheritedConcreteMap() instead.')
MemberMap getMapOfMembersInheritedFromClasses(ClassElement classElt) =>
new MemberMap.fromMap(
_computeClassChainLookupMap(classElt, new HashSet<ClassElement>()));
/**
* Get and return a mapping between the set of all string names of the members inherited from the
* passed [ClassElement] interface hierarchy, and the associated [ExecutableElement].
*
* @param classElt the class element to query
* @return a mapping between the set of all string names of the members inherited from the passed
* [ClassElement] interface hierarchy, and the associated [ExecutableElement].
*/
@Deprecated('Use InheritanceManager3.getInheritedMap() instead.')
MemberMap getMapOfMembersInheritedFromInterfaces(ClassElement classElt) =>
new MemberMap.fromMap(
_computeInterfaceLookupMap(classElt, new HashSet<ClassElement>()));
/**
* Return a table mapping the string names of the members inherited from the
* passed [ClassElement]'s superclass hierarchy, and the associated executable
* element.
*/
@deprecated
Map<String, ExecutableElement> getMembersInheritedFromClasses(
ClassElement classElt) =>
_computeClassChainLookupMap(classElt, new HashSet<ClassElement>());
/**
* Return a table mapping the string names of the members inherited from the
* passed [ClassElement]'s interface hierarchy, and the associated executable
* element.
*/
@deprecated
Map<String, ExecutableElement> getMembersInheritedFromInterfaces(
ClassElement classElt) =>
_computeInterfaceLookupMap(classElt, new HashSet<ClassElement>());
/**
* Given some [ClassElement] and some member name, this returns the
* [ExecutableElement] that the class inherits from the mixins,
* superclasses or interfaces, that has the member name, if no member is inherited `null` is
* returned.
*
* @param classElt the class element to query
* @param memberName the name of the executable element to find and return
* @return the inherited executable element with the member name, or `null` if no such
* member exists
*/
@Deprecated('Use InheritanceManager3.getInherited() instead.')
ExecutableElement lookupInheritance(
ClassElement classElt, String memberName) {
if (memberName == null || memberName.isEmpty) {
return null;
}
ExecutableElement executable = _computeClassChainLookupMap(
classElt, new HashSet<ClassElement>())[memberName];
if (executable == null) {
return _computeInterfaceLookupMap(
classElt, new HashSet<ClassElement>())[memberName];
}
return executable;
}
/**
* Given some [ClassElement] and some member name, this returns the
* [ExecutableElement] that the class either declares itself, or
* inherits, that has the member name, if no member is inherited `null` is returned.
*
* @param classElt the class element to query
* @param memberName the name of the executable element to find and return
* @return the inherited executable element with the member name, or `null` if no such
* member exists
*/
@Deprecated('Use InheritanceManager3.getMember() instead.')
ExecutableElement lookupMember(ClassElement classElt, String memberName) {
ExecutableElement element = _lookupMemberInClass(classElt, memberName);
if (element != null) {
return element;
}
return lookupInheritance(classElt, memberName);
}
/**
* Determine the set of methods which is overridden by the given class member. If no member is
* inherited, an empty list is returned. If one of the inherited members is a
* [MultiplyInheritedExecutableElement], then it is expanded into its constituent inherited
* elements.
*
* @param classElt the class to query
* @param memberName the name of the class member to query
* @return a list of overridden methods
*/
@Deprecated('Use InheritanceManager3.getOverridden() instead.')
List<ExecutableElement> lookupOverrides(
ClassElement classElt, String memberName) {
List<ExecutableElement> result = new List<ExecutableElement>();
if (memberName == null || memberName.isEmpty) {
return result;
}
List<Map<String, ExecutableElement>> interfaceMaps =
_gatherInterfaceLookupMaps(classElt, new HashSet<ClassElement>());
if (interfaceMaps != null) {
for (Map<String, ExecutableElement> interfaceMap in interfaceMaps) {
ExecutableElement overriddenElement = interfaceMap[memberName];
if (overriddenElement != null) {
if (overriddenElement is MultiplyInheritedExecutableElement) {
for (ExecutableElement element
in overriddenElement.inheritedElements) {
result.add(element);
}
} else {
result.add(overriddenElement);
}
}
}
}
return result;
}
/**
* Compute and return a mapping between the set of all string names of the members inherited from
* the passed [ClassElement] superclass hierarchy, and the associated
* [ExecutableElement].
*
* @param classElt the class element to query
* @param visitedClasses a set of visited classes passed back into this method when it calls
* itself recursively
* @return a mapping between the set of all string names of the members inherited from the passed
* [ClassElement] superclass hierarchy, and the associated [ExecutableElement]
*/
Map<String, ExecutableElement> _computeClassChainLookupMap(
ClassElement classElt, Set<ClassElement> visitedClasses) {
Map<String, ExecutableElement> resultMap = _classLookup[classElt];
if (resultMap != null) {
return resultMap;
} else {
resultMap = new Map<String, ExecutableElement>();
}
InterfaceType supertype = classElt.supertype;
if (supertype == null) {
// classElt is Object or a mixin
_classLookup[classElt] = resultMap;
return resultMap;
}
ClassElement superclassElt = supertype.element;
if (superclassElt != null) {
if (!visitedClasses.contains(superclassElt)) {
visitedClasses.add(superclassElt);
try {
resultMap = new Map<String, ExecutableElement>.from(
_computeClassChainLookupMap(superclassElt, visitedClasses));
//
// Substitute the super types down the hierarchy.
//
_substituteTypeParametersDownHierarchy(supertype, resultMap);
//
// Include the members from the superclass in the resultMap.
//
_recordMapWithClassMembers(
resultMap, supertype, _includeAbstractFromSuperclasses);
} finally {
visitedClasses.remove(superclassElt);
}
} else {
// This case happens only when the superclass was previously visited and
// not in the lookup, meaning this is meant to shorten the compute for
// recursive cases.
_classLookup[superclassElt] = resultMap;
return resultMap;
}
}
//
// Include the members from the mixins in the resultMap. If there are
// multiple mixins, visit them in the order listed so that methods in later
// mixins will overwrite identically-named methods in earlier mixins.
//
List<InterfaceType> mixins = classElt.mixins;
for (InterfaceType mixin in mixins) {
ClassElement mixinElement = mixin.element;
if (mixinElement != null) {
if (!visitedClasses.contains(mixinElement)) {
visitedClasses.add(mixinElement);
try {
Map<String, ExecutableElement> map =
new Map<String, ExecutableElement>();
//
// Include the members from the mixin in the resultMap.
//
_recordMapWithClassMembers(
map, mixin, _includeAbstractFromSuperclasses);
//
// Add the members from map into result map.
//
for (String memberName in map.keys) {
ExecutableElement value = map[memberName];
ClassElement definingClass = value
.getAncestor((Element element) => element is ClassElement);
if (!definingClass.isDartCoreObject) {
ExecutableElement existingValue = resultMap[memberName];
if (existingValue == null ||
(existingValue != null && !_isAbstract(value))) {
resultMap[memberName] = value;
}
}
}
} finally {
visitedClasses.remove(mixinElement);
}
} else {
// This case happens only when the superclass was previously visited
// and not in the lookup, meaning this is meant to shorten the compute
// for recursive cases.
_classLookup[mixinElement] = resultMap;
return resultMap;
}
}
}
_classLookup[classElt] = resultMap;
return resultMap;
}
/**
* Compute and return a mapping between the set of all string names of the members inherited from
* the passed [ClassElement] interface hierarchy, and the associated
* [ExecutableElement].
*
* @param classElt the class element to query
* @param visitedInterfaces a set of visited classes passed back into this method when it calls
* itself recursively
* @return a mapping between the set of all string names of the members inherited from the passed
* [ClassElement] interface hierarchy, and the associated [ExecutableElement]
*/
Map<String, ExecutableElement> _computeInterfaceLookupMap(
ClassElement classElt, HashSet<ClassElement> visitedInterfaces) {
Map<String, ExecutableElement> resultMap = _interfaceLookup[classElt];
if (resultMap != null) {
return resultMap;
}
List<Map<String, ExecutableElement>> lookupMaps =
_gatherInterfaceLookupMaps(classElt, visitedInterfaces);
if (lookupMaps == null) {
resultMap = new Map<String, ExecutableElement>();
} else {
Map<String, List<ExecutableElement>> unionMap =
_unionInterfaceLookupMaps(lookupMaps);
resultMap = _resolveInheritanceLookup(classElt, unionMap);
}
_interfaceLookup[classElt] = resultMap;
return resultMap;
}
/**
* Given some array of [ExecutableElement]s, this method creates a synthetic element as
* described in 8.1.1:
*
* Let <i>numberOfPositionals</i>(<i>f</i>) denote the number of positional parameters of a
* function <i>f</i>, and let <i>numberOfRequiredParams</i>(<i>f</i>) denote the number of
* required parameters of a function <i>f</i>. Furthermore, let <i>s</i> denote the set of all
* named parameters of the <i>m<sub>1</sub>, …, m<sub>k</sub></i>. Then let
* * <i>h = max(numberOfPositionals(m<sub>i</sub>)),</i>
* * <i>r = min(numberOfRequiredParams(m<sub>i</sub>)), for all <i>i</i>, 1 <= i <= k.</i>
* Then <i>I</i> has a method named <i>n</i>, with <i>r</i> required parameters of type
* <b>dynamic</b>, <i>h</i> positional parameters of type <b>dynamic</b>, named parameters
* <i>s</i> of type <b>dynamic</b> and return type <b>dynamic</b>.
*
*/
ExecutableElement _computeMergedExecutableElement(
List<ExecutableElement> elementArrayToMerge) {
int h = _getNumOfPositionalParameters(elementArrayToMerge[0]);
int r = _getNumOfRequiredParameters(elementArrayToMerge[0]);
Set<String> namedParametersList = new HashSet<String>();
for (int i = 1; i < elementArrayToMerge.length; i++) {
ExecutableElement element = elementArrayToMerge[i];
int numOfPositionalParams = _getNumOfPositionalParameters(element);
if (h < numOfPositionalParams) {
h = numOfPositionalParams;
}
int numOfRequiredParams = _getNumOfRequiredParameters(element);
if (r > numOfRequiredParams) {
r = numOfRequiredParams;
}
// TODO(brianwilkerson) Handle the fact that named parameters can now be
// required.
namedParametersList.addAll(_getNamedParameterNames(element));
}
return _createSyntheticExecutableElement(
elementArrayToMerge,
elementArrayToMerge[0].displayName,
r,
h - r,
new List.from(namedParametersList));
}
/**
* Used by [computeMergedExecutableElement] to actually create the
* synthetic element.
*
* @param elementArrayToMerge the array used to create the synthetic element
* @param name the name of the method, getter or setter
* @param numOfRequiredParameters the number of required parameters
* @param numOfPositionalParameters the number of positional parameters
* @param namedParameters the list of [String]s that are the named parameters
* @return the created synthetic element
*/
ExecutableElement _createSyntheticExecutableElement(
List<ExecutableElement> elementArrayToMerge,
String name,
int numOfRequiredParameters,
int numOfPositionalParameters,
List<String> namedParameters) {
DynamicTypeImpl dynamicType = DynamicTypeImpl.instance;
DartType bottomType = BottomTypeImpl.instance;
SimpleIdentifier nameIdentifier = astFactory
.simpleIdentifier(new StringToken(TokenType.IDENTIFIER, name, 0));
ExecutableElementImpl executable;
ExecutableElement elementToMerge = elementArrayToMerge[0];
if (elementToMerge is MethodElement) {
MultiplyInheritedMethodElementImpl unionedMethod =
new MultiplyInheritedMethodElementImpl(nameIdentifier);
unionedMethod.inheritedElements = elementArrayToMerge;
executable = unionedMethod;
} else if (elementToMerge is PropertyAccessorElement) {
MultiplyInheritedPropertyAccessorElementImpl unionedPropertyAccessor =
new MultiplyInheritedPropertyAccessorElementImpl(nameIdentifier);
unionedPropertyAccessor.getter = elementToMerge.isGetter;
unionedPropertyAccessor.setter = elementToMerge.isSetter;
unionedPropertyAccessor.inheritedElements = elementArrayToMerge;
executable = unionedPropertyAccessor;
} else {
throw new AnalysisException(
'Invalid class of element in merge: ${elementToMerge.runtimeType}');
}
int numOfParameters = numOfRequiredParameters +
numOfPositionalParameters +
namedParameters.length;
List<ParameterElement> parameters =
new List<ParameterElement>(numOfParameters);
int i = 0;
for (int j = 0; j < numOfRequiredParameters; j++, i++) {
ParameterElementImpl parameter = new ParameterElementImpl("", 0);
parameter.type = bottomType;
parameter.parameterKind = ParameterKind.REQUIRED;
parameters[i] = parameter;
}
for (int k = 0; k < numOfPositionalParameters; k++, i++) {
ParameterElementImpl parameter = new ParameterElementImpl("", 0);
parameter.type = bottomType;
parameter.parameterKind = ParameterKind.POSITIONAL;
parameters[i] = parameter;
}
// TODO(brianwilkerson) Handle the fact that named parameters can now be
// required.
for (int m = 0; m < namedParameters.length; m++, i++) {
ParameterElementImpl parameter =
new ParameterElementImpl(namedParameters[m], 0);
parameter.type = bottomType;
parameter.parameterKind = ParameterKind.NAMED;
parameters[i] = parameter;
}
executable.returnType = dynamicType;
executable.parameters = parameters;
FunctionTypeImpl methodType = new FunctionTypeImpl(executable);
executable.type = methodType;
return executable;
}
/**
* Collect a list of interface lookup maps whose elements correspond to all of the classes
* directly above [classElt] in the class hierarchy (the direct superclass if any, all
* mixins, and all direct superinterfaces). Each item in the list is the interface lookup map
* returned by [computeInterfaceLookupMap] for the corresponding super, except with type
* parameters appropriately substituted.
*
* @param classElt the class element to query
* @param visitedInterfaces a set of visited classes passed back into this method when it calls
* itself recursively
* @return `null` if there was a problem (such as a loop in the class hierarchy) or if there
* are no classes above this one in the class hierarchy. Otherwise, a list of interface
* lookup maps.
*/
List<Map<String, ExecutableElement>> _gatherInterfaceLookupMaps(
ClassElement classElt, HashSet<ClassElement> visitedInterfaces) {
List<Map<String, ExecutableElement>> lookupMaps =
new List<Map<String, ExecutableElement>>();
bool hasProblem = false;
void recordInterface(InterfaceType type) {
ClassElement element = type.element;
if (!visitedInterfaces.add(element)) {
hasProblem = true;
return;
}
try {
//
// Recursively compute the map for the interfaces.
//
Map<String, ExecutableElement> map =
_computeInterfaceLookupMap(element, visitedInterfaces);
map = new Map<String, ExecutableElement>.from(map);
//
// Substitute the supertypes down the hierarchy.
//
_substituteTypeParametersDownHierarchy(type, map);
//
// And any members from the interface into the map as well.
//
_recordMapWithClassMembers(map, type, true);
lookupMaps.add(map);
} finally {
visitedInterfaces.remove(element);
}
}
void recordInterfaces(List<InterfaceType> types) {
for (int i = types.length - 1; i >= 0; i--) {
InterfaceType type = types[i];
recordInterface(type);
}
}
InterfaceType superType = classElt.supertype;
if (superType != null) {
recordInterface(superType);
}
recordInterfaces(classElt.mixins);
recordInterfaces(classElt.superclassConstraints);
recordInterfaces(classElt.interfaces);
if (hasProblem || lookupMaps.isEmpty) {
return null;
}
return lookupMaps;
}
/**
* Given some [classElement], this method finds and returns the executable
* element with the given [memberName] in the class element. Static members,
* members in super types and members not accessible from the current library
* are not considered.
*/
ExecutableElement _lookupMemberInClass(
ClassElement classElement, String memberName) {
List<MethodElement> methods = classElement.methods;
int methodLength = methods.length;
for (int i = 0; i < methodLength; i++) {
MethodElement method = methods[i];
if (memberName == method.name &&
method.isAccessibleIn(_library) &&
!method.isStatic) {
return method;
}
}
List<PropertyAccessorElement> accessors = classElement.accessors;
int accessorLength = accessors.length;
for (int i = 0; i < accessorLength; i++) {
PropertyAccessorElement accessor = accessors[i];
if (memberName == accessor.name &&
accessor.isAccessibleIn(_library) &&
!accessor.isStatic) {
return accessor;
}
}
return null;
}
/**
* Record the passed map with the set of all members (methods, getters and setters) in the type
* into the passed map.
*
* @param map some non-`null` map to put the methods and accessors from the passed
* [ClassElement] into
* @param type the type that will be recorded into the passed map
* @param doIncludeAbstract `true` if abstract members will be put into the map
*/
void _recordMapWithClassMembers(Map<String, ExecutableElement> map,
InterfaceType type, bool doIncludeAbstract) {
Set<InterfaceType> seenTypes = new HashSet<InterfaceType>();
while (type.element.isMixinApplication) {
List<InterfaceType> mixins = type.mixins;
if (!seenTypes.add(type) || mixins.isEmpty) {
// In the case of a circularity in the type hierarchy, just don't add
// any members to the map.
return;
}
type = mixins.last;
}
List<MethodElement> methods = type.methods;
for (MethodElement method in methods) {
if (method.isAccessibleIn(_library) &&
!method.isStatic &&
(doIncludeAbstract || !method.isAbstract)) {
map[method.name] = method;
}
}
List<PropertyAccessorElement> accessors = type.accessors;
for (PropertyAccessorElement accessor in accessors) {
if (accessor.isAccessibleIn(_library) &&
!accessor.isStatic &&
(doIncludeAbstract || !accessor.isAbstract)) {
map[accessor.name] = accessor;
}
}
}
/**
* Given the set of methods defined by classes above [classElt] in the class hierarchy,
* apply the appropriate inheritance rules to determine those methods inherited by or overridden
* by [classElt].
*
* @param classElt the class element to query.
* @param unionMap a mapping from method name to the set of unique (in terms of signature) methods
* defined in superclasses of [classElt].
* @return the inheritance lookup map for [classElt].
*/
Map<String, ExecutableElement> _resolveInheritanceLookup(
ClassElement classElt, Map<String, List<ExecutableElement>> unionMap) {
Map<String, ExecutableElement> resultMap =
new Map<String, ExecutableElement>();
unionMap.forEach((String key, List<ExecutableElement> list) {
int numOfEltsWithMatchingNames = list.length;
if (numOfEltsWithMatchingNames == 1) {
//
// Example: class A inherits only 1 method named 'm'.
// Since it is the only such method, it is inherited.
// Another example: class A inherits 2 methods named 'm' from 2
// different interfaces, but they both have the same signature, so it is
// the method inherited.
//
resultMap[key] = list[0];
} else {
//
// Then numOfEltsWithMatchingNames > 1, check for the warning cases.
//
bool allMethods = true;
bool allSetters = true;
bool allGetters = true;
for (ExecutableElement executableElement in list) {
if (executableElement is PropertyAccessorElement) {
allMethods = false;
if (executableElement.isSetter) {
allGetters = false;
} else {
allSetters = false;
}
} else {
allGetters = false;
allSetters = false;
}
}
//
// If there isn't a mixture of methods with getters, then continue,
// otherwise create a warning.
//
if (allMethods || allGetters || allSetters) {
//
// Compute the element whose type is the subtype of all of the other
// types.
//
List<ExecutableElement> elements = new List.from(list);
List<FunctionType> executableElementTypes =
new List<FunctionType>(numOfEltsWithMatchingNames);
for (int i = 0; i < numOfEltsWithMatchingNames; i++) {
executableElementTypes[i] = elements[i].type;
}
List<int> subtypesOfAllOtherTypesIndexes = new List<int>();
for (int i = 0; i < numOfEltsWithMatchingNames; i++) {
FunctionType subtype = executableElementTypes[i];
if (subtype == null) {
continue;
}
bool subtypeOfAllTypes = true;
TypeSystem typeSystem = _library.context.typeSystem;
for (int j = 0;
j < numOfEltsWithMatchingNames && subtypeOfAllTypes;
j++) {
if (i != j) {
if (!typeSystem.isSubtypeOf(
subtype, executableElementTypes[j])) {
subtypeOfAllTypes = false;
break;
}
}
}
if (subtypeOfAllTypes) {
subtypesOfAllOtherTypesIndexes.add(i);
}
}
//
// The following is split into three cases determined by the number of
// elements in subtypesOfAllOtherTypes
//
if (subtypesOfAllOtherTypesIndexes.length == 1) {
//
// Example: class A inherited only 2 method named 'm'.
// One has the function type '() -> dynamic' and one has the
// function type '([int]) -> dynamic'. Since the second method is a
// subtype of all the others, it is the inherited method.
// Tests: InheritanceManagerTest.
// test_getMapOfMembersInheritedFromInterfaces_union_oneSubtype_*
//
resultMap[key] = elements[subtypesOfAllOtherTypesIndexes[0]];
} else {
if (subtypesOfAllOtherTypesIndexes.isNotEmpty) {
//
// Example: class A inherits 2 methods named 'm'.
// One has the function type '(int) -> dynamic' and one has the
// function type '(num) -> dynamic'. Since they are both a subtype
// of the other, a synthetic function '(dynamic) -> dynamic' is
// inherited.
// Tests: test_getMapOfMembersInheritedFromInterfaces_
// union_multipleSubtypes_*
//
// TODO(leafp): this produces (dynamic) -> dynamic even if
// the types are equal which gives bad error messages. If
// types are equal, we should consider using them. Even
// better, consider using the GLB of the parameter types
// and the LUB of the return types
List<ExecutableElement> elementArrayToMerge =
new List<ExecutableElement>(
subtypesOfAllOtherTypesIndexes.length);
for (int i = 0; i < elementArrayToMerge.length; i++) {
elementArrayToMerge[i] =
elements[subtypesOfAllOtherTypesIndexes[i]];
}
ExecutableElement mergedExecutableElement =
_computeMergedExecutableElement(elementArrayToMerge);
resultMap[key] = mergedExecutableElement;
}
}
}
}
});
return resultMap;
}
/**
* Loop through all of the members in the given [map], performing type
* parameter substitutions using a passed [supertype].
*/
void _substituteTypeParametersDownHierarchy(
InterfaceType superType, Map<String, ExecutableElement> map) {
for (String memberName in map.keys) {
ExecutableElement executableElement = map[memberName];
if (executableElement is MethodMember) {
map[memberName] = MethodMember.from(executableElement, superType);
} else if (executableElement is PropertyAccessorMember) {
map[memberName] =
PropertyAccessorMember.from(executableElement, superType);
}
}
}
/**
* Union all of the [lookupMaps] together into a single map, grouping the ExecutableElements
* into a list where none of the elements are equal where equality is determined by having equal
* function types. (We also take note too of the kind of the element: ()->int and () -> int may
* not be equal if one is a getter and the other is a method.)
*
* @param lookupMaps the maps to be unioned together.
* @return the resulting union map.
*/
Map<String, List<ExecutableElement>> _unionInterfaceLookupMaps(
List<Map<String, ExecutableElement>> lookupMaps) {
Map<String, List<ExecutableElement>> unionMap =
new HashMap<String, List<ExecutableElement>>();
for (Map<String, ExecutableElement> lookupMap in lookupMaps) {
for (String memberName in lookupMap.keys) {
// Get the list value out of the unionMap
List<ExecutableElement> list = unionMap.putIfAbsent(
memberName, () => new List<ExecutableElement>());
// Fetch the entry out of this lookupMap
ExecutableElement newExecutableElementEntry = lookupMap[memberName];
if (list.isEmpty) {
// If the list is empty, just the new value
list.add(newExecutableElementEntry);
} else {
// Otherwise, only add the newExecutableElementEntry if it isn't
// already in the list, this covers situation where a class inherits
// two methods (or two getters) that are identical.
bool alreadyInList = false;
bool isMethod1 = newExecutableElementEntry is MethodElement;
for (ExecutableElement executableElementInList in list) {
bool isMethod2 = executableElementInList is MethodElement;
if (isMethod1 == isMethod2 &&
executableElementInList.type ==
newExecutableElementEntry.type) {
alreadyInList = true;
break;
}
}
if (!alreadyInList) {
list.add(newExecutableElementEntry);
}
}
}
}
return unionMap;
}
/**
* Given some [ExecutableElement], return the list of named parameters.
*/
static List<String> _getNamedParameterNames(
ExecutableElement executableElement) {
List<String> namedParameterNames = new List<String>();
List<ParameterElement> parameters = executableElement.parameters;
for (int i = 0; i < parameters.length; i++) {
ParameterElement parameterElement = parameters[i];
if (parameterElement.isNamed) {
namedParameterNames.add(parameterElement.name);
}
}
return namedParameterNames;
}
/**
* Given some [ExecutableElement] return the number of parameters of the specified kind.
*/
static int _getNumOfParameters(
ExecutableElement executableElement, ParameterKind parameterKind) {
int parameterCount = 0;
List<ParameterElement> parameters = executableElement.parameters;
for (int i = 0; i < parameters.length; i++) {
ParameterElement parameterElement = parameters[i];
// ignore: deprecated_member_use_from_same_package
if (parameterElement.parameterKind == parameterKind) {
parameterCount++;
}
}
return parameterCount;
}
/**
* Given some [ExecutableElement] return the number of positional parameters.
*
* Note: by positional we mean [ParameterKind.REQUIRED] or [ParameterKind.POSITIONAL].
*/
static int _getNumOfPositionalParameters(
ExecutableElement executableElement) =>
_getNumOfParameters(executableElement, ParameterKind.REQUIRED) +
_getNumOfParameters(executableElement, ParameterKind.POSITIONAL);
/**
* Given some [ExecutableElement] return the number of required parameters.
*/
static int _getNumOfRequiredParameters(ExecutableElement executableElement) =>
_getNumOfParameters(executableElement, ParameterKind.REQUIRED);
/**
* Given some [ExecutableElement] returns `true` if it is an abstract member of a
* class.
*
* @param executableElement some [ExecutableElement] to evaluate
* @return `true` if the given element is an abstract member of a class
*/
static bool _isAbstract(ExecutableElement executableElement) {
if (executableElement is MethodElement) {
return executableElement.isAbstract;
} else if (executableElement is PropertyAccessorElement) {
return executableElement.isAbstract;
}
return false;
}
}
/**
* This class is used to replace uses of `HashMap<String, ExecutableElement>`
* which are not as performant as this class.
*/
@deprecated
class MemberMap {
/**
* The current size of this map.
*/
int _size = 0;
/**
* The array of keys.
*/
List<String> _keys;
/**
* The array of ExecutableElement values.
*/
List<ExecutableElement> _values;
/**
* Initialize a newly created member map to have the given [initialCapacity].
* The map will grow if needed.
*/
MemberMap([int initialCapacity = 10]) {
_initArrays(initialCapacity);
}
/**
* Initialize a newly created member map to contain the same members as the
* given [memberMap].
*/
MemberMap.from(MemberMap memberMap) {
_initArrays(memberMap._size + 5);
for (int i = 0; i < memberMap._size; i++) {
_keys[i] = memberMap._keys[i];
_values[i] = memberMap._values[i];
}
_size = memberMap._size;
}
/**
* Initialize a newly created member map to contain the same members as the
* given [map].
*/
MemberMap.fromMap(Map<String, ExecutableElement> map) {
_size = map.length;
_initArrays(_size + 5);
int index = 0;
map.forEach((String memberName, ExecutableElement element) {
_keys[index] = memberName;
_values[index] = element;
index++;
});
}
/**
* The size of the map.
*
* @return the size of the map.
*/
int get size => _size;
/**
* Given some key, return the ExecutableElement value from the map, if the key does not exist in
* the map, `null` is returned.
*
* @param key some key to look up in the map
* @return the associated ExecutableElement value from the map, if the key does not exist in the
* map, `null` is returned
*/
ExecutableElement get(String key) {
for (int i = 0; i < _size; i++) {
if (_keys[i] != null && _keys[i] == key) {
return _values[i];
}
}
return null;
}
/**
* Get and return the key at the specified location. If the key/value pair has been removed from
* the set, then `null` is returned.
*
* @param i some non-zero value less than size
* @return the key at the passed index
* @throw ArrayIndexOutOfBoundsException this exception is thrown if the passed index is less than
* zero or greater than or equal to the capacity of the arrays
*/
String getKey(int i) => _keys[i];
/**
* Get and return the ExecutableElement at the specified location. If the key/value pair has been
* removed from the set, then then `null` is returned.
*
* @param i some non-zero value less than size
* @return the key at the passed index
* @throw ArrayIndexOutOfBoundsException this exception is thrown if the passed index is less than
* zero or greater than or equal to the capacity of the arrays
*/
ExecutableElement getValue(int i) => _values[i];
/**
* Given some key/value pair, store the pair in the map. If the key exists already, then the new
* value overrides the old value.
*
* @param key the key to store in the map
* @param value the ExecutableElement value to store in the map
*/
void put(String key, ExecutableElement value) {
// If we already have a value with this key, override the value
for (int i = 0; i < _size; i++) {
if (_keys[i] != null && _keys[i] == key) {
_values[i] = value;
return;
}
}
// If needed, double the size of our arrays and copy values over in both
// arrays
if (_size == _keys.length) {
int newArrayLength = _size * 2;
List<String> keys_new_array = new List<String>(newArrayLength);
List<ExecutableElement> values_new_array =
new List<ExecutableElement>(newArrayLength);
for (int i = 0; i < _size; i++) {
keys_new_array[i] = _keys[i];
}
for (int i = 0; i < _size; i++) {
values_new_array[i] = _values[i];
}
_keys = keys_new_array;
_values = values_new_array;
}
// Put new value at end of array
_keys[_size] = key;
_values[_size] = value;
_size++;
}
/**
* Given some [String] key, this method replaces the associated key and value pair with
* `null`. The size is not decremented with this call, instead it is expected that the users
* check for `null`.
*
* @param key the key of the key/value pair to remove from the map
*/
void remove(String key) {
for (int i = 0; i < _size; i++) {
if (_keys[i] == key) {
_keys[i] = null;
_values[i] = null;
return;
}
}
}
/**
* Sets the ExecutableElement at the specified location.
*
* @param i some non-zero value less than size
* @param value the ExecutableElement value to store in the map
*/
void setValue(int i, ExecutableElement value) {
_values[i] = value;
}
/**
* Initializes [keys] and [values].
*/
void _initArrays(int initialCapacity) {
_keys = new List<String>(initialCapacity);
_values = new List<ExecutableElement>(initialCapacity);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/resolver/ast_rewrite.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/standard_ast_factory.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/resolver/scope.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/type_system.dart';
/// A visitor that will re-write an AST to support the optional `new` and
/// `const` feature.
class AstRewriteVisitor extends ScopedVisitor {
final TypeSystem typeSystem;
/// Initialize a newly created visitor.
AstRewriteVisitor(
this.typeSystem,
LibraryElement definingLibrary,
Source source,
TypeProvider typeProvider,
AnalysisErrorListener errorListener,
{Scope nameScope})
: super(definingLibrary, source, typeProvider, errorListener,
nameScope: nameScope);
@override
void visitMethodInvocation(MethodInvocation node) {
super.visitMethodInvocation(node);
SimpleIdentifier methodName = node.methodName;
if (methodName.isSynthetic) {
// This isn't a constructor invocation because the method name is
// synthetic.
return;
}
Expression target = node.target;
if (target == null) {
// Possible cases: C() or C<>()
if (node.realTarget != null) {
// This isn't a constructor invocation because it's in a cascade.
return;
}
Element element = nameScope.lookup(methodName, definingLibrary);
if (element is ClassElement) {
TypeName typeName = astFactory.typeName(methodName, node.typeArguments);
ConstructorName constructorName =
astFactory.constructorName(typeName, null, null);
InstanceCreationExpression instanceCreationExpression =
astFactory.instanceCreationExpression(
null, constructorName, node.argumentList);
NodeReplacer.replace(node, instanceCreationExpression);
} else if (element is ExtensionElement) {
ExtensionOverride extensionOverride = astFactory.extensionOverride(
extensionName: methodName,
typeArguments: node.typeArguments,
argumentList: node.argumentList);
NodeReplacer.replace(node, extensionOverride);
}
} else if (target is SimpleIdentifier) {
// Possible cases: C.n(), p.C() or p.C<>()
if (node.isNullAware) {
// This isn't a constructor invocation because a null aware operator is
// being used.
}
Element element = nameScope.lookup(target, definingLibrary);
if (element is ClassElement) {
// Possible case: C.n()
var constructorElement = element.getNamedConstructor(methodName.name);
if (constructorElement != null) {
var typeArguments = node.typeArguments;
if (typeArguments != null) {
errorReporter.reportErrorForNode(
StaticTypeWarningCode
.WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR,
typeArguments,
[element.name, constructorElement.name]);
}
TypeName typeName = astFactory.typeName(target, null);
ConstructorName constructorName =
astFactory.constructorName(typeName, node.operator, methodName);
// TODO(scheglov) I think we should drop "typeArguments" below.
InstanceCreationExpression instanceCreationExpression =
astFactory.instanceCreationExpression(
null, constructorName, node.argumentList,
typeArguments: typeArguments);
NodeReplacer.replace(node, instanceCreationExpression);
}
} else if (element is PrefixElement) {
// Possible cases: p.C() or p.C<>()
Identifier identifier = astFactory.prefixedIdentifier(
astFactory.simpleIdentifier(target.token),
null,
astFactory.simpleIdentifier(methodName.token));
Element prefixedElement = nameScope.lookup(identifier, definingLibrary);
if (prefixedElement is ClassElement) {
TypeName typeName = astFactory.typeName(
astFactory.prefixedIdentifier(target, node.operator, methodName),
node.typeArguments);
ConstructorName constructorName =
astFactory.constructorName(typeName, null, null);
InstanceCreationExpression instanceCreationExpression =
astFactory.instanceCreationExpression(
null, constructorName, node.argumentList);
NodeReplacer.replace(node, instanceCreationExpression);
} else if (prefixedElement is ExtensionElement) {
PrefixedIdentifier extensionName =
astFactory.prefixedIdentifier(target, node.operator, methodName);
ExtensionOverride extensionOverride = astFactory.extensionOverride(
extensionName: extensionName,
typeArguments: node.typeArguments,
argumentList: node.argumentList);
NodeReplacer.replace(node, extensionOverride);
}
}
} else if (target is PrefixedIdentifier) {
// Possible case: p.C.n()
Element prefixElement = nameScope.lookup(target.prefix, definingLibrary);
target.prefix.staticElement = prefixElement;
if (prefixElement is PrefixElement) {
Element element = nameScope.lookup(target, definingLibrary);
if (element is ClassElement) {
var constructorElement = element.getNamedConstructor(methodName.name);
if (constructorElement != null) {
var typeArguments = node.typeArguments;
if (typeArguments != null) {
errorReporter.reportErrorForNode(
StaticTypeWarningCode
.WRONG_NUMBER_OF_TYPE_ARGUMENTS_CONSTRUCTOR,
typeArguments,
[element.name, constructorElement.name]);
}
TypeName typeName = astFactory.typeName(target, typeArguments);
ConstructorName constructorName =
astFactory.constructorName(typeName, node.operator, methodName);
InstanceCreationExpression instanceCreationExpression =
astFactory.instanceCreationExpression(
null, constructorName, node.argumentList);
NodeReplacer.replace(node, instanceCreationExpression);
}
}
}
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/sdk/patch.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:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/source/line_info.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:meta/meta.dart';
/**
* [SdkPatcher] applies patches to SDK [CompilationUnit].
*/
class SdkPatcher {
bool _allowNewPublicNames;
String _baseDesc;
String _patchDesc;
CompilationUnit _patchUnit;
/**
* Patch the given [unit] of a SDK [source] with the patches defined in
* [allPatchPaths]. Throw [ArgumentError] if a patch
* file cannot be read, or the contents violates rules for patch files.
*/
void patch(
ResourceProvider resourceProvider,
Map<String, List<String>> allPatchPaths,
AnalysisErrorListener errorListener,
Source source,
CompilationUnit unit) {
// Process URI.
String libraryUriStr;
bool isLibraryDefiningUnit;
{
Uri uri = source.uri;
if (uri.scheme != 'dart') {
throw new ArgumentError(
'The URI of the unit to patch must have the "dart" scheme: $uri');
}
List<String> uriSegments = uri.pathSegments;
String libraryName = uriSegments.first;
libraryUriStr = 'dart:$libraryName';
isLibraryDefiningUnit = uriSegments.length == 1;
_allowNewPublicNames = libraryName == '_internal';
}
// Prepare the patch files to apply.
List<String> patchPaths = allPatchPaths[libraryUriStr] ?? const <String>[];
for (String path in patchPaths) {
File patchFile = resourceProvider.getFile(path);
if (!patchFile.exists) {
throw new ArgumentError(
'The patch file ${patchFile.path} for $source does not exist.');
}
Source patchSource = patchFile.createSource();
CompilationUnit patchUnit =
parse(patchSource, errorListener, unit.featureSet);
// Prepare for reporting errors.
_baseDesc = source.toString();
_patchDesc = patchFile.path;
_patchUnit = patchUnit;
if (isLibraryDefiningUnit) {
_patchDirectives(source, unit, patchSource, patchUnit);
}
_patchTopLevelDeclarations(unit, patchUnit, isLibraryDefiningUnit);
}
}
void _failExternalKeyword(String name, int offset) {
throw new ArgumentError(
'The keyword "external" was expected for "$name" in $_baseDesc @ $offset.');
}
void _failIfPublicName(AstNode node, String name) {
if (_allowNewPublicNames) {
return;
}
if (!Identifier.isPrivateName(name)) {
_failInPatch('contains a public declaration "$name"', node.offset);
}
}
void _failInPatch(String message, int offset) {
String loc = _getLocationDesc3(_patchUnit, offset);
throw new ArgumentError(
'The patch file $_patchDesc for $_baseDesc $message at $loc.');
}
String _getLocationDesc3(CompilationUnit unit, int offset) {
CharacterLocation location = unit.lineInfo.getLocation(offset);
return 'the line ${location.lineNumber}';
}
void _matchParameterLists(FormalParameterList baseParameters,
FormalParameterList patchParameters, String context()) {
if (baseParameters == null && patchParameters == null) return;
if (baseParameters == null || patchParameters == null) {
throw new ArgumentError("${context()}, parameter lists don't match");
}
if (baseParameters.parameters.length != patchParameters.parameters.length) {
throw new ArgumentError(
'${context()}, parameter lists have different lengths');
}
for (var i = 0; i < baseParameters.parameters.length; i++) {
_matchParameters(baseParameters.parameters[i],
patchParameters.parameters[i], () => '${context()}, parameter $i');
}
}
void _matchParameters(FormalParameter baseParameter,
FormalParameter patchParameter, String whichParameter()) {
if (baseParameter.identifier.name != patchParameter.identifier.name) {
throw new ArgumentError('${whichParameter()} has different name');
}
NormalFormalParameter baseParameterWithoutDefault =
_withoutDefault(baseParameter);
NormalFormalParameter patchParameterWithoutDefault =
_withoutDefault(patchParameter);
if (baseParameterWithoutDefault is SimpleFormalParameter &&
patchParameterWithoutDefault is SimpleFormalParameter) {
_matchTypes(baseParameterWithoutDefault.type,
patchParameterWithoutDefault.type, () => '${whichParameter()} type');
} else if (baseParameterWithoutDefault is FunctionTypedFormalParameter &&
patchParameterWithoutDefault is FunctionTypedFormalParameter) {
_matchTypes(
baseParameterWithoutDefault.returnType,
patchParameterWithoutDefault.returnType,
() => '${whichParameter()} return type');
_matchParameterLists(
baseParameterWithoutDefault.parameters,
patchParameterWithoutDefault.parameters,
() => '${whichParameter()} parameters');
} else if (baseParameterWithoutDefault is FieldFormalParameter &&
patchParameter is FieldFormalParameter) {
throw new ArgumentError(
'${whichParameter()} cannot be patched (field formal parameters are not supported)');
} else {
throw new ArgumentError(
'${whichParameter()} mismatch (different parameter kinds)');
}
}
void _matchTypes(TypeName baseType, TypeName patchType, String whichType()) {
error() => new ArgumentError("${whichType()} doesn't match");
if (baseType == null && patchType == null) return;
if (baseType == null || patchType == null) throw error();
// Match up the types token by token; this is more restrictive than strictly
// necessary, but it's easy and sufficient for patching purposes.
Token baseToken = baseType.beginToken;
Token patchToken = patchType.beginToken;
while (true) {
if (baseToken.lexeme != patchToken.lexeme) throw error();
if (identical(baseToken, baseType.endToken) &&
identical(patchToken, patchType.endToken)) {
break;
}
if (identical(baseToken, baseType.endToken) ||
identical(patchToken, patchType.endToken)) {
throw error();
}
baseToken = baseToken.next;
patchToken = patchToken.next;
}
}
void _patchClassMembers(
ClassDeclaration baseClass, ClassDeclaration patchClass) {
String className = baseClass.name.name;
List<ClassMember> membersToAppend = [];
for (ClassMember patchMember in patchClass.members) {
if (patchMember is FieldDeclaration) {
if (_hasPatchAnnotation(patchMember.metadata)) {
_failInPatch('attempts to patch a field', patchMember.offset);
}
List<VariableDeclaration> fields = patchMember.fields.variables;
if (fields.length != 1) {
_failInPatch('contains a field declaration with more than one field',
patchMember.offset);
}
String name = fields[0].name.name;
if (!_allowNewPublicNames &&
!Identifier.isPrivateName(className) &&
!Identifier.isPrivateName(name)) {
_failInPatch('contains a public field', patchMember.offset);
}
membersToAppend.add(patchMember);
} else if (patchMember is MethodDeclaration) {
String name = patchMember.name.name;
if (_hasPatchAnnotation(patchMember.metadata)) {
for (ClassMember baseMember in baseClass.members) {
if (baseMember is MethodDeclaration &&
baseMember.name.name == name) {
// Remove the "external" keyword.
Token externalKeyword = baseMember.externalKeyword;
if (externalKeyword != null) {
baseMember.externalKeyword = null;
_removeToken(externalKeyword);
} else {
_failExternalKeyword(name, baseMember.offset);
}
_matchParameterLists(
baseMember.parameters,
patchMember.parameters,
() => 'While patching $className.$name');
_matchTypes(baseMember.returnType, patchMember.returnType,
() => 'While patching $className.$name, return type');
// Replace the body.
FunctionBody oldBody = baseMember.body;
FunctionBody newBody = patchMember.body;
_replaceNodeTokens(oldBody, newBody);
baseMember.body = newBody;
}
}
} else {
_failIfPublicName(patchMember, name);
membersToAppend.add(patchMember);
}
} else if (patchMember is ConstructorDeclaration) {
String name = patchMember.name?.name;
if (_hasPatchAnnotation(patchMember.metadata)) {
for (ClassMember baseMember in baseClass.members) {
if (baseMember is ConstructorDeclaration &&
baseMember.name?.name == name) {
// Remove the "external" keyword.
Token externalKeyword = baseMember.externalKeyword;
if (externalKeyword != null) {
baseMember.externalKeyword = null;
_removeToken(externalKeyword);
} else {
_failExternalKeyword(name, baseMember.offset);
}
// Factory vs. generative.
if (baseMember.factoryKeyword == null &&
patchMember.factoryKeyword != null) {
_failInPatch(
'attempts to replace generative constructor with a factory one',
patchMember.offset);
} else if (baseMember.factoryKeyword != null &&
patchMember.factoryKeyword == null) {
_failInPatch(
'attempts to replace factory constructor with a generative one',
patchMember.offset);
}
// The base constructor should not have initializers.
if (baseMember.initializers.isNotEmpty) {
throw new ArgumentError(
'Cannot patch external constructors with initializers '
'in $_baseDesc.');
}
_matchParameterLists(
baseMember.parameters, patchMember.parameters, () {
String nameSuffix = name == null ? '' : '.$name';
return 'While patching $className$nameSuffix';
});
// Prepare nodes.
FunctionBody baseBody = baseMember.body;
FunctionBody patchBody = patchMember.body;
NodeList<ConstructorInitializer> baseInitializers =
baseMember.initializers;
NodeList<ConstructorInitializer> patchInitializers =
patchMember.initializers;
// Replace initializers and link tokens.
if (patchInitializers.isNotEmpty) {
baseMember.parameters.endToken
.setNext(patchInitializers.beginToken.previous);
baseInitializers.addAll(patchInitializers);
patchBody.endToken.setNext(baseBody.endToken.next);
} else {
_replaceNodeTokens(baseBody, patchBody);
}
// Replace the body.
baseMember.body = patchBody;
}
}
} else {
if (name == null) {
if (!_allowNewPublicNames && !Identifier.isPrivateName(className)) {
_failInPatch(
'contains an unnamed public constructor', patchMember.offset);
}
} else {
_failIfPublicName(patchMember, name);
}
membersToAppend.add(patchMember);
}
} else {
String className = patchClass.name.name;
_failInPatch('contains an unsupported class member in $className',
patchMember.offset);
}
}
// Append new class members.
_appendToNodeList(
baseClass.members, membersToAppend, baseClass.leftBracket);
}
void _patchDirectives(Source baseSource, CompilationUnit baseUnit,
Source patchSource, CompilationUnit patchUnit) {
for (Directive patchDirective in patchUnit.directives) {
if (patchDirective is ImportDirective) {
baseUnit.directives.add(patchDirective);
} else {
_failInPatch('contains an unsupported "$patchDirective" directive',
patchDirective.offset);
}
}
}
void _patchTopLevelDeclarations(CompilationUnit baseUnit,
CompilationUnit patchUnit, bool appendNewTopLevelDeclarations) {
List<CompilationUnitMember> declarationsToAppend = [];
for (CompilationUnitMember patchDeclaration in patchUnit.declarations) {
if (patchDeclaration is FunctionDeclaration) {
String name = patchDeclaration.name.name;
if (_hasPatchAnnotation(patchDeclaration.metadata)) {
for (CompilationUnitMember baseDeclaration in baseUnit.declarations) {
if (patchDeclaration is FunctionDeclaration &&
baseDeclaration is FunctionDeclaration &&
baseDeclaration.name.name == name) {
// Remove the "external" keyword.
Token externalKeyword = baseDeclaration.externalKeyword;
if (externalKeyword != null) {
baseDeclaration.externalKeyword = null;
_removeToken(externalKeyword);
} else {
_failExternalKeyword(name, baseDeclaration.offset);
}
_matchParameterLists(
baseDeclaration.functionExpression.parameters,
patchDeclaration.functionExpression.parameters,
() => 'While patching $name');
_matchTypes(
baseDeclaration.returnType,
patchDeclaration.returnType,
() => 'While patching $name, return type');
// Replace the body.
FunctionExpression oldExpr = baseDeclaration.functionExpression;
FunctionBody newBody = patchDeclaration.functionExpression.body;
_replaceNodeTokens(oldExpr.body, newBody);
oldExpr.body = newBody;
}
}
} else if (appendNewTopLevelDeclarations) {
_failIfPublicName(patchDeclaration, name);
declarationsToAppend.add(patchDeclaration);
}
} else if (patchDeclaration is FunctionTypeAlias) {
if (patchDeclaration.metadata.isNotEmpty) {
_failInPatch('contains a function type alias with an annotation',
patchDeclaration.offset);
}
_failIfPublicName(patchDeclaration, patchDeclaration.name.name);
declarationsToAppend.add(patchDeclaration);
} else if (patchDeclaration is ClassDeclaration) {
if (_hasPatchAnnotation(patchDeclaration.metadata)) {
String name = patchDeclaration.name.name;
for (CompilationUnitMember baseDeclaration in baseUnit.declarations) {
if (baseDeclaration is ClassDeclaration &&
baseDeclaration.name.name == name) {
_patchClassMembers(baseDeclaration, patchDeclaration);
}
}
} else {
_failIfPublicName(patchDeclaration, patchDeclaration.name.name);
declarationsToAppend.add(patchDeclaration);
}
} else if (patchDeclaration is TopLevelVariableDeclaration &&
!_hasPatchAnnotation(patchDeclaration.metadata)) {
for (VariableDeclaration variable
in patchDeclaration.variables.variables) {
_failIfPublicName(patchDeclaration, variable.name.name);
}
declarationsToAppend.add(patchDeclaration);
} else {
_failInPatch('contains an unsupported top-level declaration',
patchDeclaration.offset);
}
}
// Append new top-level declarations.
if (appendNewTopLevelDeclarations) {
_appendToNodeList(baseUnit.declarations, declarationsToAppend,
baseUnit.endToken.previous);
}
}
NormalFormalParameter _withoutDefault(FormalParameter parameter) {
if (parameter is NormalFormalParameter) {
return parameter;
} else if (parameter is DefaultFormalParameter) {
return parameter.parameter;
} else {
// Should not happen.
assert(false);
return null;
}
}
/**
* Parse the given [source] into AST.
*/
@visibleForTesting
static CompilationUnit parse(Source source,
AnalysisErrorListener errorListener, FeatureSet featureSet) {
String code = source.contents.data;
CharSequenceReader reader = new CharSequenceReader(code);
Scanner scanner = new Scanner(source, reader, errorListener)
..configureFeatures(featureSet);
Token token = scanner.tokenize();
LineInfo lineInfo = new LineInfo(scanner.lineStarts);
Parser parser = new Parser(source, errorListener, featureSet: featureSet);
CompilationUnit unit = parser.parseCompilationUnit(token);
unit.lineInfo = lineInfo;
return unit;
}
/**
* Append [newNodes] to the given [nodes] and attach new tokens to the end
* token of the last [nodes] items, or, if it is empty, to [defaultPrevToken].
*/
static void _appendToNodeList(
NodeList<AstNode> nodes, List<AstNode> newNodes, Token defaultPrevToken) {
Token prevToken = nodes.endToken ?? defaultPrevToken;
for (AstNode newNode in newNodes) {
newNode.endToken.setNext(prevToken.next);
prevToken.setNext(newNode.beginToken);
nodes.add(newNode);
prevToken = newNode.endToken;
}
}
/**
* Return `true` if [metadata] has the `@patch` annotation.
*/
static bool _hasPatchAnnotation(List<Annotation> metadata) {
return metadata.any((annotation) {
Identifier name = annotation.name;
return annotation.constructorName == null &&
name is SimpleIdentifier &&
name.name == 'patch';
});
}
/**
* Remove the [token] from the stream.
*/
static void _removeToken(Token token) {
token.previous.setNext(token.next);
}
/**
* Replace tokens of the [oldNode] with tokens of the [newNode].
*/
static void _replaceNodeTokens(AstNode oldNode, AstNode newNode) {
oldNode.beginToken.previous.setNext(newNode.beginToken);
newNode.endToken.setNext(oldNode.endToken.next);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/sdk/sdk.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'dart:convert';
import 'dart:io' as io;
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/src/context/context.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/java_engine_io.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/summary/idl.dart' show PackageBundle;
import 'package:path/path.dart' as pathos;
import 'package:yaml/yaml.dart';
/**
* An abstract implementation of a Dart SDK in which the available libraries are
* stored in a library map. Subclasses are responsible for populating the
* library map.
*/
abstract class AbstractDartSdk implements DartSdk {
/**
* The resource provider used to access the file system.
*/
ResourceProvider resourceProvider;
/**
* A mapping from Dart library URI's to the library represented by that URI.
*/
LibraryMap libraryMap = new LibraryMap();
/**
* The [AnalysisOptions] to use to create the [context].
*/
AnalysisOptions _analysisOptions;
/**
* The flag that specifies whether an SDK summary should be used. This is a
* temporary flag until summaries are enabled by default.
*/
bool _useSummary = false;
/**
* The [AnalysisContext] which is used for all of the sources in this SDK.
*/
InternalAnalysisContext _analysisContext;
/**
* The mapping from Dart URI's to the corresponding sources.
*/
Map<String, Source> _uriToSourceMap = new HashMap<String, Source>();
PackageBundle _sdkBundle;
/**
* Return the analysis options for this SDK analysis context.
*/
AnalysisOptions get analysisOptions => _analysisOptions;
/**
* Set the [options] for this SDK analysis context. Throw [StateError] if the
* context has been already created.
*/
void set analysisOptions(AnalysisOptions options) {
if (_analysisContext != null) {
throw new StateError(
'Analysis options cannot be changed after context creation.');
}
_analysisOptions = options;
}
@override
AnalysisContext get context {
if (_analysisContext == null) {
_analysisContext = new SdkAnalysisContext(_analysisOptions);
SourceFactory factory = new SourceFactory([new DartUriResolver(this)]);
_analysisContext.sourceFactory = factory;
}
return _analysisContext;
}
@override
List<SdkLibrary> get sdkLibraries => libraryMap.sdkLibraries;
/**
* Return the path separator used by the resource provider.
*/
String get separator => resourceProvider.pathContext.separator;
@override
List<String> get uris => libraryMap.uris;
/**
* Return `true` if the SDK summary will be used when available.
*/
bool get useSummary => _useSummary;
/**
* Specify whether SDK summary should be used.
*/
void set useSummary(bool use) {
if (_analysisContext != null) {
throw new StateError(
'The "useSummary" flag cannot be changed after context creation.');
}
_useSummary = use;
}
/**
* Add the extensions from one or more sdk extension files to this sdk. The
* [extensions] should be a table mapping the names of extensions to the paths
* where those extensions can be found.
*/
void addExtensions(Map<String, String> extensions) {
extensions.forEach((String uri, String path) {
SdkLibraryImpl library = new SdkLibraryImpl(uri);
library.path = path;
libraryMap.setLibrary(uri, library);
});
}
/**
* Return info for debugging https://github.com/dart-lang/sdk/issues/35226.
*/
Map<String, Object> debugInfo() {
return <String, Object>{
'runtimeType': '$runtimeType',
'libraryMap': libraryMap.debugInfo(),
};
}
@override
Source fromFileUri(Uri uri) {
File file =
resourceProvider.getFile(resourceProvider.pathContext.fromUri(uri));
String path = _getPath(file);
if (path == null) {
return null;
}
try {
return file.createSource(Uri.parse(path));
} on FormatException catch (exception, stackTrace) {
AnalysisEngine.instance.logger.logInformation(
"Failed to create URI: $path",
new CaughtException(exception, stackTrace));
}
return null;
}
@override
PackageBundle getLinkedBundle() {
if (_useSummary) {
_sdkBundle ??= getSummarySdkBundle();
return _sdkBundle;
}
return null;
}
String getRelativePathFromFile(File file);
@override
SdkLibrary getSdkLibrary(String dartUri) => libraryMap.getLibrary(dartUri);
/**
* Return the [PackageBundle] for this SDK, if it exists, or `null` otherwise.
* This method should not be used outside of `analyzer` and `analyzer_cli`
* packages.
*/
PackageBundle getSummarySdkBundle();
Source internalMapDartUri(String dartUri) {
// TODO(brianwilkerson) Figure out how to unify the implementations in the
// two subclasses.
String libraryName;
String relativePath;
int index = dartUri.indexOf('/');
if (index >= 0) {
libraryName = dartUri.substring(0, index);
relativePath = dartUri.substring(index + 1);
} else {
libraryName = dartUri;
relativePath = "";
}
SdkLibrary library = getSdkLibrary(libraryName);
if (library == null) {
return null;
}
String srcPath;
if (relativePath.isEmpty) {
srcPath = library.path;
} else {
String libraryPath = library.path;
int index = libraryPath.lastIndexOf(separator);
if (index == -1) {
index = libraryPath.lastIndexOf('/');
if (index == -1) {
return null;
}
}
String prefix = libraryPath.substring(0, index + 1);
srcPath = '$prefix$relativePath';
}
String filePath = srcPath.replaceAll('/', separator);
try {
File file = resourceProvider.getFile(filePath);
return file.createSource(Uri.parse(dartUri));
} on FormatException {
return null;
}
}
@override
Source mapDartUri(String dartUri) {
Source source = _uriToSourceMap[dartUri];
if (source == null) {
source = internalMapDartUri(dartUri);
_uriToSourceMap[dartUri] = source;
}
return source;
}
String _getPath(File file) {
List<SdkLibrary> libraries = libraryMap.sdkLibraries;
int length = libraries.length;
List<String> paths = new List(length);
String filePath = getRelativePathFromFile(file);
if (filePath == null) {
return null;
}
for (int i = 0; i < length; i++) {
SdkLibrary library = libraries[i];
String libraryPath = library.path.replaceAll('/', separator);
if (filePath == libraryPath) {
return library.shortName;
}
paths[i] = libraryPath;
}
for (int i = 0; i < length; i++) {
SdkLibrary library = libraries[i];
String libraryPath = paths[i];
int index = libraryPath.lastIndexOf(separator);
if (index >= 0) {
String prefix = libraryPath.substring(0, index + 1);
if (filePath.startsWith(prefix)) {
String relPath =
filePath.substring(prefix.length).replaceAll(separator, '/');
return '${library.shortName}/$relPath';
}
}
}
return null;
}
}
/**
* An SDK backed by URI mappings derived from an `_embedder.yaml` file.
*/
class EmbedderSdk extends AbstractDartSdk {
static const String _DART_COLON_PREFIX = 'dart:';
static const String _EMBEDDED_LIB_MAP_KEY = 'embedded_libs';
final Map<String, String> _urlMappings = new HashMap<String, String>();
Folder _embedderYamlLibFolder;
EmbedderSdk(
ResourceProvider resourceProvider, Map<Folder, YamlMap> embedderYamls) {
this.resourceProvider = resourceProvider;
embedderYamls?.forEach(_processEmbedderYaml);
if (embedderYamls?.length == 1) {
_embedderYamlLibFolder = embedderYamls.keys.first;
}
}
@override
// TODO(danrubel) Determine SDK version
String get sdkVersion => '0';
/**
* The url mappings for this SDK.
*/
Map<String, String> get urlMappings => _urlMappings;
@override
String getRelativePathFromFile(File file) => file.path;
@override
PackageBundle getSummarySdkBundle() {
String name = 'strong.sum';
File file = _embedderYamlLibFolder.parent.getChildAssumingFile(name);
try {
if (file.exists) {
List<int> bytes = file.readAsBytesSync();
return new PackageBundle.fromBuffer(bytes);
}
} catch (exception, stackTrace) {
AnalysisEngine.instance.logger.logError(
'Failed to load SDK analysis summary from $file',
new CaughtException(exception, stackTrace));
}
return null;
}
@override
Source internalMapDartUri(String dartUri) {
String libraryName;
String relativePath;
int index = dartUri.indexOf('/');
if (index >= 0) {
libraryName = dartUri.substring(0, index);
relativePath = dartUri.substring(index + 1);
} else {
libraryName = dartUri;
relativePath = "";
}
SdkLibrary library = getSdkLibrary(libraryName);
if (library == null) {
return null;
}
String srcPath;
if (relativePath.isEmpty) {
srcPath = library.path;
} else {
String libraryPath = library.path;
int index = libraryPath.lastIndexOf(separator);
if (index == -1) {
index = libraryPath.lastIndexOf('/');
if (index == -1) {
return null;
}
}
String prefix = libraryPath.substring(0, index + 1);
srcPath = '$prefix$relativePath';
}
String filePath = srcPath.replaceAll('/', separator);
try {
File file = resourceProvider.getFile(filePath);
return file.createSource(Uri.parse(dartUri));
} on FormatException {
return null;
}
}
/**
* Install the mapping from [name] to [libDir]/[file].
*/
void _processEmbeddedLibs(String name, String file, Folder libDir) {
if (!name.startsWith(_DART_COLON_PREFIX)) {
// SDK libraries must begin with 'dart:'.
return;
}
String libPath = libDir.canonicalizePath(file);
_urlMappings[name] = libPath;
SdkLibraryImpl library = new SdkLibraryImpl(name);
library.path = libPath;
libraryMap.setLibrary(name, library);
}
/**
* Given the 'embedderYamls' from [EmbedderYamlLocator] check each one for the
* top level key 'embedded_libs'. Under the 'embedded_libs' key are key value
* pairs. Each key is a 'dart:' library uri and each value is a path
* (relative to the directory containing `_embedder.yaml`) to a dart script
* for the given library. For example:
*
* embedded_libs:
* 'dart:io': '../../sdk/io/io.dart'
*
* If a key doesn't begin with `dart:` it is ignored.
*/
void _processEmbedderYaml(Folder libDir, YamlMap map) {
YamlNode embedded_libs = map[_EMBEDDED_LIB_MAP_KEY];
if (embedded_libs is YamlMap) {
embedded_libs.forEach((k, v) => _processEmbeddedLibs(k, v, libDir));
}
}
}
/**
* A Dart SDK installed in a specified directory. Typical Dart SDK layout is
* something like...
*
* dart-sdk/
* bin/
* dart[.exe] <-- VM
* lib/
* core/
* core.dart
* ... other core library files ...
* ... other libraries ...
* util/
* ... Dart utilities ...
* Chromium/ <-- Dartium typically exists in a sibling directory
*/
class FolderBasedDartSdk extends AbstractDartSdk {
/**
* The name of the directory within the SDK directory that contains
* executables.
*/
static String _BIN_DIRECTORY_NAME = "bin";
/**
* The name of the directory within the SDK directory that contains
* documentation for the libraries.
*/
static String _DOCS_DIRECTORY_NAME = "docs";
/**
* The name of the directory within the SDK directory that contains the
* sdk_library_metadata directory.
*/
static String _INTERNAL_DIR = "_internal";
/**
* The name of the sdk_library_metadata directory that contains the package
* holding the libraries.dart file.
*/
static String _SDK_LIBRARY_METADATA_DIR = "sdk_library_metadata";
/**
* The name of the directory within the sdk_library_metadata that contains
* libraries.dart.
*/
static String _SDK_LIBRARY_METADATA_LIB_DIR = "lib";
/**
* The name of the directory within the SDK directory that contains the
* libraries.
*/
static String _LIB_DIRECTORY_NAME = "lib";
/**
* The name of the libraries file.
*/
static String _LIBRARIES_FILE = "libraries.dart";
/**
* The name of the pub executable on windows.
*/
static String _PUB_EXECUTABLE_NAME_WIN = "pub.bat";
/**
* The name of the pub executable on non-windows operating systems.
*/
static String _PUB_EXECUTABLE_NAME = "pub";
/**
* The name of the file within the SDK directory that contains the version
* number of the SDK.
*/
static String _VERSION_FILE_NAME = "version";
/**
* The directory containing the SDK.
*/
Folder _sdkDirectory;
/**
* The directory within the SDK directory that contains the libraries.
*/
Folder _libraryDirectory;
/**
* The revision number of this SDK, or `"0"` if the revision number cannot be
* discovered.
*/
String _sdkVersion;
/**
* The file containing the pub executable.
*/
File _pubExecutable;
/**
* Initialize a newly created SDK to represent the Dart SDK installed in the
* [sdkDirectory]. The flag [useDart2jsPaths] is `true` if the dart2js path
* should be used when it is available
*/
FolderBasedDartSdk(ResourceProvider resourceProvider, this._sdkDirectory,
[bool useDart2jsPaths = false]) {
this.resourceProvider = resourceProvider;
libraryMap = initialLibraryMap(useDart2jsPaths);
}
/**
* Return the directory containing the SDK.
*/
Folder get directory => _sdkDirectory;
/**
* Return the directory containing documentation for the SDK.
*/
Folder get docDirectory =>
_sdkDirectory.getChildAssumingFolder(_DOCS_DIRECTORY_NAME);
/**
* Return the directory within the SDK directory that contains the libraries.
*/
Folder get libraryDirectory {
if (_libraryDirectory == null) {
_libraryDirectory =
_sdkDirectory.getChildAssumingFolder(_LIB_DIRECTORY_NAME);
}
return _libraryDirectory;
}
/**
* Return the file containing the Pub executable, or `null` if it does not exist.
*/
File get pubExecutable {
if (_pubExecutable == null) {
_pubExecutable = _sdkDirectory
.getChildAssumingFolder(_BIN_DIRECTORY_NAME)
.getChildAssumingFile(OSUtilities.isWindows()
? _PUB_EXECUTABLE_NAME_WIN
: _PUB_EXECUTABLE_NAME);
}
return _pubExecutable;
}
/**
* Return the revision number of this SDK, or `"0"` if the revision number
* cannot be discovered.
*/
@override
String get sdkVersion {
if (_sdkVersion == null) {
_sdkVersion = DartSdk.DEFAULT_VERSION;
File revisionFile =
_sdkDirectory.getChildAssumingFile(_VERSION_FILE_NAME);
try {
String revision = revisionFile.readAsStringSync();
if (revision != null) {
_sdkVersion = revision.trim();
}
} on FileSystemException {
// Fall through to return the default.
}
}
return _sdkVersion;
}
/**
* Determine the search order for trying to locate the [_LIBRARIES_FILE].
*/
Iterable<File> get _libraryMapLocations sync* {
yield libraryDirectory
.getChildAssumingFolder(_INTERNAL_DIR)
.getChildAssumingFolder(_SDK_LIBRARY_METADATA_DIR)
.getChildAssumingFolder(_SDK_LIBRARY_METADATA_LIB_DIR)
.getChildAssumingFile(_LIBRARIES_FILE);
yield libraryDirectory
.getChildAssumingFolder(_INTERNAL_DIR)
.getChildAssumingFile(_LIBRARIES_FILE);
}
/**
* Return info for debugging https://github.com/dart-lang/sdk/issues/35226.
*/
@override
Map<String, Object> debugInfo() {
var result = super.debugInfo();
result['directory'] = _sdkDirectory.path;
return result;
}
@override
String getRelativePathFromFile(File file) {
String filePath = file.path;
String libPath = libraryDirectory.path;
if (!filePath.startsWith("$libPath$separator")) {
return null;
}
return filePath.substring(libPath.length + 1);
}
/**
* Return the [PackageBundle] for this SDK, if it exists, or `null` otherwise.
* This method should not be used outside of `analyzer` and `analyzer_cli`
* packages.
*/
PackageBundle getSummarySdkBundle() {
String rootPath = directory.path;
String name = 'strong.sum';
String path =
resourceProvider.pathContext.join(rootPath, 'lib', '_internal', name);
try {
File file = resourceProvider.getFile(path);
if (file.exists) {
List<int> bytes = file.readAsBytesSync();
return new PackageBundle.fromBuffer(bytes);
}
} catch (exception, stackTrace) {
AnalysisEngine.instance.logger.logError(
'Failed to load SDK analysis summary from $path',
new CaughtException(exception, stackTrace));
}
return null;
}
/**
* Read all of the configuration files to initialize the library maps. The
* flag [useDart2jsPaths] is `true` if the dart2js path should be used when it
* is available. Return the initialized library map.
*/
LibraryMap initialLibraryMap(bool useDart2jsPaths) {
List<String> searchedPaths = <String>[];
StackTrace lastStackTrace;
Object lastException;
for (File librariesFile in _libraryMapLocations) {
try {
String contents = librariesFile.readAsStringSync();
return new SdkLibrariesReader().readFromFile(librariesFile, contents);
} catch (exception, stackTrace) {
searchedPaths.add(librariesFile.path);
lastException = exception;
lastStackTrace = stackTrace;
}
}
StringBuffer buffer = new StringBuffer();
buffer.writeln('Could not initialize the library map from $searchedPaths');
if (resourceProvider is MemoryResourceProvider) {
(resourceProvider as MemoryResourceProvider).writeOn(buffer);
}
AnalysisEngine.instance.logger.logError(
buffer.toString(), new CaughtException(lastException, lastStackTrace));
return new LibraryMap();
}
@override
Source internalMapDartUri(String dartUri) {
String libraryName;
String relativePath;
int index = dartUri.indexOf('/');
if (index >= 0) {
libraryName = dartUri.substring(0, index);
relativePath = dartUri.substring(index + 1);
} else {
libraryName = dartUri;
relativePath = "";
}
SdkLibrary library = getSdkLibrary(libraryName);
if (library == null) {
return null;
}
try {
File file = libraryDirectory.getChildAssumingFile(library.path);
if (relativePath.isNotEmpty) {
File relativeFile = file.parent.getChildAssumingFile(relativePath);
if (relativeFile.path == file.path) {
// The relative file is the library, so return a Source for the
// library rather than the part format.
return file.createSource(Uri.parse(library.shortName));
}
file = relativeFile;
}
return file.createSource(Uri.parse(dartUri));
} on FormatException {
return null;
}
}
/**
* Return the default directory for the Dart SDK, or `null` if the directory
* cannot be determined (or does not exist). The default directory is provided
* by a system property named `com.google.dart.sdk`.
*/
static Folder defaultSdkDirectory(ResourceProvider resourceProvider) {
// TODO(brianwilkerson) This is currently only being used in the analysis
// server's Driver class to find the default SDK. The command-line analyzer
// uses cli_utils to find the SDK. Not sure why they're different.
String sdkProperty = getSdkProperty(resourceProvider);
if (sdkProperty == null) {
return null;
}
Folder sdkDirectory = resourceProvider.getFolder(sdkProperty);
if (!sdkDirectory.exists) {
return null;
}
return sdkDirectory;
}
static String getSdkProperty(ResourceProvider resourceProvider) {
String exec = io.Platform.resolvedExecutable;
if (exec.isEmpty) {
return null;
}
pathos.Context pathContext = resourceProvider.pathContext;
if (pathContext.style != pathos.context.style) {
// This will only happen when running tests.
if (exec.startsWith(new RegExp('[a-zA-Z]:'))) {
exec = exec.substring(2);
} else if (resourceProvider is MemoryResourceProvider) {
exec = resourceProvider.convertPath(exec);
}
exec = pathContext.fromUri(pathos.context.toUri(exec));
}
// Might be "xcodebuild/ReleaseIA32/dart" with "sdk" sibling
String outDir = pathContext.dirname(pathContext.dirname(exec));
String sdkPath = pathContext.join(pathContext.dirname(outDir), "sdk");
if (resourceProvider.getFolder(sdkPath).exists) {
// We are executing in the context of a test. sdkPath is the path to the
// *source* files for the SDK. But we want to test using the path to the
// *built* SDK if possible.
String builtSdkPath =
pathContext.join(pathContext.dirname(exec), 'dart-sdk');
if (resourceProvider.getFolder(builtSdkPath).exists) {
return builtSdkPath;
} else {
return sdkPath;
}
}
// probably be "dart-sdk/bin/dart"
return pathContext.dirname(pathContext.dirname(exec));
}
}
/**
* An object used to locate SDK extensions.
*
* Given a package map, it will check in each package's `lib` directory for the
* existence of a `_sdkext` file. This file must contain a JSON encoded map.
* Each key in the map is a `dart:` library name. Each value is a path (relative
* to the directory containing `_sdkext`) to a dart script for the given
* library. For example:
* ```
* {
* "dart:sky": "../sdk_ext/dart_sky.dart"
* }
* ```
* If a key doesn't begin with `dart:` it is ignored.
*/
class SdkExtensionFinder {
/**
* The name of the extension file.
*/
static const String SDK_EXT_NAME = '_sdkext';
/**
* The prefix required for all keys in an extension file that will not be
* ignored.
*/
static const String DART_COLON_PREFIX = 'dart:';
/**
* A table mapping the names of extensions to the paths where those extensions
* can be found.
*/
final Map<String, String> _urlMappings = <String, String>{};
/**
* The absolute paths of the extension files that contributed to the
* [_urlMappings].
*/
final List<String> extensionFilePaths = <String>[];
/**
* Initialize a newly created finder to look in the packages in the given
* [packageMap] for SDK extension files.
*/
SdkExtensionFinder(Map<String, List<Folder>> packageMap) {
if (packageMap == null) {
return;
}
packageMap.forEach(_processPackage);
}
/**
* Return a table mapping the names of extensions to the paths where those
* extensions can be found.
*/
Map<String, String> get urlMappings =>
new Map<String, String>.from(_urlMappings);
/**
* Given a package [name] and a list of folders ([libDirs]), add any found sdk
* extensions.
*/
void _processPackage(String name, List<Folder> libDirs) {
for (var libDir in libDirs) {
var sdkExt = _readDotSdkExt(libDir);
if (sdkExt != null) {
_processSdkExt(sdkExt, libDir);
}
}
}
/**
* Given the JSON for an SDK extension ([sdkExtJSON]) and a folder ([libDir]),
* setup the uri mapping.
*/
void _processSdkExt(String sdkExtJSON, Folder libDir) {
var sdkExt;
try {
sdkExt = json.decode(sdkExtJSON);
} catch (e) {
return;
}
if ((sdkExt == null) || (sdkExt is! Map)) {
return;
}
bool contributed = false;
sdkExt.forEach((k, v) {
if (k is String && v is String && _processSdkExtension(libDir, k, v)) {
contributed = true;
}
});
if (contributed) {
extensionFilePaths.add(libDir.getChild(SDK_EXT_NAME).path);
}
}
/**
* Install the mapping from [name] to [libDir]/[file].
*/
bool _processSdkExtension(Folder libDir, String name, String file) {
if (!name.startsWith(DART_COLON_PREFIX)) {
// SDK extensions must begin with 'dart:'.
return false;
}
_urlMappings[name] = libDir.canonicalizePath(file);
return true;
}
/**
* Read the contents of [libDir]/[SDK_EXT_NAME] as a string, or `null` if the
* file doesn't exist.
*/
String _readDotSdkExt(Folder libDir) {
File file = libDir.getChild(SDK_EXT_NAME);
try {
return file.readAsStringSync();
} on FileSystemException {
// File can't be read.
return null;
}
}
}
/**
* An object used to read and parse the libraries file
* (dart-sdk/lib/_internal/sdk_library_metadata/lib/libraries.dart) for information
* about the libraries in an SDK. The library information is represented as a
* Dart file containing a single top-level variable whose value is a const map.
* The keys of the map are the names of libraries defined in the SDK and the
* values in the map are info objects defining the library. For example, a
* subset of a typical SDK might have a libraries file that looks like the
* following:
*
* final Map<String, LibraryInfo> LIBRARIES = const <LibraryInfo> {
* // Used by VM applications
* "builtin" : const LibraryInfo(
* "builtin/builtin_runtime.dart",
* category: "Server",
* platforms: VM_PLATFORM),
*
* "compiler" : const LibraryInfo(
* "compiler/compiler.dart",
* category: "Tools",
* platforms: 0),
* };
*/
class SdkLibrariesReader {
SdkLibrariesReader([@deprecated bool useDart2jsPaths]);
/**
* Return the library map read from the given [file], given that the content
* of the file is already known to be [libraryFileContents].
*/
LibraryMap readFromFile(File file, String libraryFileContents) =>
readFromSource(file.createSource(), libraryFileContents);
/**
* Return the library map read from the given [source], given that the content
* of the file is already known to be [libraryFileContents].
*/
LibraryMap readFromSource(Source source, String libraryFileContents) {
BooleanErrorListener errorListener = new BooleanErrorListener();
// TODO(paulberry): initialize the feature set appropriately based on the
// version of the SDK we are reading, and enable flags.
var featureSet = FeatureSet.fromEnableFlags([]);
Scanner scanner = new Scanner(
source, new CharSequenceReader(libraryFileContents), errorListener)
..configureFeatures(featureSet);
Parser parser = new Parser(source, errorListener, featureSet: featureSet);
CompilationUnit unit = parser.parseCompilationUnit(scanner.tokenize());
SdkLibrariesReader_LibraryBuilder libraryBuilder =
new SdkLibrariesReader_LibraryBuilder(true);
// If any syntactic errors were found then don't try to visit the AST
// structure.
if (!errorListener.errorReported) {
unit.accept(libraryBuilder);
}
return libraryBuilder.librariesMap;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/constant/potentially_constant.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
/// Some [ConstructorElement]s can be temporary marked as "const" to check
/// if doing this is valid.
final temporaryConstConstructorElements = new Expando<bool>();
/// Check if the [node] and all its sub-nodes are potentially constant.
///
/// Return the list of nodes that are not potentially constant.
List<AstNode> getNotPotentiallyConstants(AstNode node) {
var collector = _Collector();
collector.collect(node);
return collector.nodes;
}
/// Return `true` if the [node] is a constant type expression.
bool isConstantTypeExpression(TypeAnnotation node) {
if (node is TypeName) {
if (_isConstantTypeName(node.name)) {
var arguments = node.typeArguments?.arguments;
if (arguments != null) {
for (var argument in arguments) {
if (!isConstantTypeExpression(argument)) {
return false;
}
}
}
return true;
}
if (node.type is DynamicTypeImpl) {
return true;
}
if (node.type is VoidType) {
return true;
}
return false;
}
if (node is GenericFunctionType) {
var returnType = node.returnType;
if (returnType != null) {
if (!isConstantTypeExpression(returnType)) {
return false;
}
}
var typeParameters = node.typeParameters?.typeParameters;
if (typeParameters != null) {
for (var parameter in typeParameters) {
var bound = parameter.bound;
if (bound != null && !isConstantTypeExpression(bound)) {
return false;
}
}
}
var formalParameters = node.parameters?.parameters;
if (formalParameters != null) {
for (var parameter in formalParameters) {
if (parameter is SimpleFormalParameter) {
if (!isConstantTypeExpression(parameter.type)) {
return false;
}
}
}
}
return true;
}
return false;
}
bool _isConstantTypeName(Identifier name) {
var element = name.staticElement;
if (element is ClassElement || element is GenericTypeAliasElement) {
if (name is PrefixedIdentifier) {
if (name.isDeferred) {
return false;
}
}
return true;
}
return false;
}
class _Collector {
final List<AstNode> nodes = [];
void collect(AstNode node) {
if (node is BooleanLiteral ||
node is DoubleLiteral ||
node is IntegerLiteral ||
node is NullLiteral ||
node is SimpleStringLiteral ||
node is SymbolLiteral) {
return;
}
if (node is AdjacentStrings) {
for (var string in node.strings) {
collect(string);
}
return;
}
if (node is StringInterpolation) {
for (var component in node.elements) {
if (component is InterpolationExpression) {
collect(component.expression);
}
}
return;
}
if (node is Identifier) {
return _identifier(node);
}
if (node is InstanceCreationExpression) {
if (!node.isConst) {
nodes.add(node);
}
return;
}
if (node is TypedLiteral) {
return _typeLiteral(node);
}
if (node is ParenthesizedExpression) {
collect(node.expression);
return;
}
if (node is MethodInvocation) {
return _methodInvocation(node);
}
if (node is NamedExpression) {
return collect(node.expression);
}
if (node is BinaryExpression) {
collect(node.leftOperand);
collect(node.rightOperand);
return;
}
if (node is PrefixExpression) {
var operator = node.operator.type;
if (operator == TokenType.BANG ||
operator == TokenType.MINUS ||
operator == TokenType.TILDE) {
collect(node.operand);
return;
}
nodes.add(node);
return;
}
if (node is ConditionalExpression) {
collect(node.condition);
collect(node.thenExpression);
collect(node.elseExpression);
return;
}
if (node is PropertyAccess) {
return _propertyAccess(node);
}
if (node is AsExpression) {
if (!isConstantTypeExpression(node.type)) {
nodes.add(node.type);
}
collect(node.expression);
return;
}
if (node is IsExpression) {
if (!isConstantTypeExpression(node.type)) {
nodes.add(node.type);
}
collect(node.expression);
return;
}
if (node is MapLiteralEntry) {
collect(node.key);
collect(node.value);
return;
}
if (node is SpreadElement) {
collect(node.expression);
return;
}
if (node is IfElement) {
collect(node.condition);
collect(node.thenElement);
if (node.elseElement != null) {
collect(node.elseElement);
}
return;
}
nodes.add(node);
}
void _identifier(Identifier node) {
var element = node.staticElement;
if (node is PrefixedIdentifier) {
if (node.isDeferred) {
nodes.add(node);
return;
}
if (node.identifier.name == 'length') {
collect(node.prefix);
return;
}
if (element is MethodElement && element.isStatic) {
if (!_isConstantTypeName(node.prefix)) {
nodes.add(node);
}
return;
}
}
if (element is ParameterElement) {
var enclosing = element.enclosingElement;
if (enclosing is ConstructorElement &&
isConstConstructorElement(enclosing)) {
if (node.thisOrAncestorOfType<ConstructorInitializer>() != null) {
return;
}
}
nodes.add(node);
return;
}
if (element is VariableElement) {
if (!element.isConst) {
nodes.add(node);
}
return;
}
if (element is PropertyAccessorElement && element.isGetter) {
var variable = element.variable;
if (!variable.isConst) {
nodes.add(node);
}
return;
}
if (_isConstantTypeName(node)) {
return;
}
if (element is FunctionElement) {
return;
}
if (element is MethodElement && element.isStatic) {
return;
}
nodes.add(node);
}
void _methodInvocation(MethodInvocation node) {
var arguments = node.argumentList?.arguments;
if (arguments?.length == 2 && node.methodName.name == 'identical') {
var library = node.methodName?.staticElement?.library;
if (library?.isDartCore == true) {
collect(arguments[0]);
collect(arguments[1]);
return;
}
}
nodes.add(node);
}
void _propertyAccess(PropertyAccess node) {
if (node.propertyName.name == 'length') {
collect(node.target);
return;
}
var target = node.target;
if (target is PrefixedIdentifier) {
if (target.isDeferred) {
nodes.add(node);
return;
}
var element = node.propertyName.staticElement;
if (element is PropertyAccessorElement && element.isGetter) {
var variable = element.variable;
if (!variable.isConst) {
nodes.add(node.propertyName);
}
return;
}
}
nodes.add(node);
}
void _typeLiteral(TypedLiteral node) {
if (!node.isConst) {
nodes.add(node);
return;
}
if (node is ListLiteral) {
var typeArguments = node.typeArguments?.arguments;
if (typeArguments?.length == 1) {
var elementType = typeArguments[0];
if (!isConstantTypeExpression(elementType)) {
nodes.add(elementType);
}
}
for (var element in node.elements) {
collect(element);
}
return;
}
if (node is SetOrMapLiteral) {
var typeArguments = node.typeArguments?.arguments;
if (typeArguments?.length == 1) {
var elementType = typeArguments[0];
if (!isConstantTypeExpression(elementType)) {
nodes.add(elementType);
}
}
if (typeArguments?.length == 2) {
var keyType = typeArguments[0];
var valueType = typeArguments[1];
if (!isConstantTypeExpression(keyType)) {
nodes.add(keyType);
}
if (!isConstantTypeExpression(valueType)) {
nodes.add(valueType);
}
}
for (var element in node.elements) {
collect(element);
}
}
}
static bool isConstConstructorElement(ConstructorElement element) {
if (element.isConst) return true;
return temporaryConstConstructorElements[element] ?? false;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/constant/compute.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/dart/analysis/declared_variables.dart';
import 'package:analyzer/src/dart/analysis/experiments.dart';
import 'package:analyzer/src/dart/constant/evaluation.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/generated/resolver.dart'
show TypeProvider, TypeSystem;
import 'package:analyzer/src/summary/link.dart' as graph
show DependencyWalker, Node;
/// Compute values of the given [constants] with correct ordering.
void computeConstants(
TypeProvider typeProvider,
TypeSystem typeSystem,
DeclaredVariables declaredVariables,
List<ConstantEvaluationTarget> constants,
ExperimentStatus experimentStatus) {
var evaluationEngine = ConstantEvaluationEngine(
typeProvider, declaredVariables,
typeSystem: typeSystem, experimentStatus: experimentStatus);
var nodes = <_ConstantNode>[];
var nodeMap = <ConstantEvaluationTarget, _ConstantNode>{};
for (var constant in constants) {
var node = _ConstantNode(evaluationEngine, nodeMap, constant);
nodes.add(node);
nodeMap[constant] = node;
}
for (var node in nodes) {
if (!node.isEvaluated) {
_ConstantWalker(evaluationEngine).walk(node);
}
}
}
/// [graph.Node] that is used to compute constants in dependency order.
class _ConstantNode extends graph.Node<_ConstantNode> {
final ConstantEvaluationEngine evaluationEngine;
final Map<ConstantEvaluationTarget, _ConstantNode> nodeMap;
final ConstantEvaluationTarget constant;
_ConstantNode(this.evaluationEngine, this.nodeMap, this.constant);
@override
bool get isEvaluated => constant.isConstantEvaluated;
@override
List<_ConstantNode> computeDependencies() {
var targets = <ConstantEvaluationTarget>[];
evaluationEngine.computeDependencies(constant, targets.add);
return targets.map(_getNode).toList();
}
_ConstantNode _getNode(ConstantEvaluationTarget constant) {
return nodeMap.putIfAbsent(
constant,
() => _ConstantNode(evaluationEngine, nodeMap, constant),
);
}
}
/// [graph.DependencyWalker] for computing constants and detecting cycles.
class _ConstantWalker extends graph.DependencyWalker<_ConstantNode> {
final ConstantEvaluationEngine evaluationEngine;
_ConstantWalker(this.evaluationEngine);
@override
void evaluate(_ConstantNode node) {
evaluationEngine.computeConstantValue(node.constant);
}
@override
void evaluateScc(List<_ConstantNode> scc) {
var constantsInCycle = scc.map((node) => node.constant);
for (var node in scc) {
var constant = node.constant;
if (constant is ConstructorElementImpl) {
constant.isCycleFree = false;
}
evaluationEngine.generateCycleError(constantsInCycle, constant);
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/constant/evaluation.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/standard_ast_factory.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/analysis/experiments.dart';
import 'package:analyzer/src/dart/constant/potentially_constant.dart';
import 'package:analyzer/src/dart/constant/utilities.dart';
import 'package:analyzer/src/dart/constant/value.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisEngine, RecordingErrorListener;
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/type_system.dart'
show Dart2TypeSystem, TypeSystem;
import 'package:analyzer/src/task/api/model.dart';
/// Helper class encapsulating the methods for evaluating constants and
/// constant instance creation expressions.
class ConstantEvaluationEngine {
/// Parameter to "fromEnvironment" methods that denotes the default value.
static String _DEFAULT_VALUE_PARAM = "defaultValue";
/// Source of RegExp matching declarable operator names.
/// From sdk/lib/internal/symbol.dart.
static String _OPERATOR_RE =
"(?:[\\-+*/%&|^]|\\[\\]=?|==|~/?|<[<=]?|>[>=]?|unary-)";
/// Source of RegExp matching Dart reserved words.
/// From sdk/lib/internal/symbol.dart.
static String _RESERVED_WORD_RE =
"(?:assert|break|c(?:a(?:se|tch)|lass|on(?:st|tinue))|"
"d(?:efault|o)|e(?:lse|num|xtends)|f(?:alse|inal(?:ly)?|or)|"
"i[fns]|n(?:ew|ull)|ret(?:hrow|urn)|s(?:uper|witch)|t(?:h(?:is|row)|"
"r(?:ue|y))|v(?:ar|oid)|w(?:hile|ith))";
/// Source of RegExp matching any public identifier.
/// From sdk/lib/internal/symbol.dart.
static String _PUBLIC_IDENTIFIER_RE =
"(?!$_RESERVED_WORD_RE\\b(?!\\\$))[a-zA-Z\$][\\w\$]*";
/// RegExp that validates a non-empty non-private symbol.
/// From sdk/lib/internal/symbol.dart.
static RegExp _PUBLIC_SYMBOL_PATTERN = new RegExp(
"^(?:$_OPERATOR_RE\$|$_PUBLIC_IDENTIFIER_RE(?:=?\$|[.](?!\$)))+?\$");
/// The type provider used to access the known types.
final TypeProvider typeProvider;
/// The type system. This is used to guess the types of constants when their
/// exact value is unknown.
final TypeSystem typeSystem;
/// The set of variables declared on the command line using '-D'.
final DeclaredVariables _declaredVariables;
/// Return the object representing the state of active experiments.
final ExperimentStatus experimentStatus;
/// Validator used to verify correct dependency analysis when running unit
/// tests.
final ConstantEvaluationValidator validator;
/// Initialize a newly created [ConstantEvaluationEngine]. The [typeProvider]
/// is used to access known types. [_declaredVariables] is the set of
/// variables declared on the command line using '-D'. The [validator], if
/// given, is used to verify correct dependency analysis when running unit
/// tests.
ConstantEvaluationEngine(TypeProvider typeProvider, this._declaredVariables,
{ConstantEvaluationValidator validator,
ExperimentStatus experimentStatus,
TypeSystem typeSystem,
// TODO(brianwilkerson) Remove the unused parameter `forAnalysisDriver`.
@deprecated bool forAnalysisDriver})
: typeProvider = typeProvider,
validator =
validator ?? new ConstantEvaluationValidator_ForProduction(),
typeSystem = typeSystem ?? new Dart2TypeSystem(typeProvider),
experimentStatus = experimentStatus ?? new ExperimentStatus();
/// Check that the arguments to a call to fromEnvironment() are correct. The
/// [arguments] are the AST nodes of the arguments. The [argumentValues] are
/// the values of the unnamed arguments. The [namedArgumentValues] are the
/// values of the named arguments. The [expectedDefaultValueType] is the
/// allowed type of the "defaultValue" parameter (if present). Note:
/// "defaultValue" is always allowed to be null. Return `true` if the
/// arguments are correct, `false` if there is an error.
bool checkFromEnvironmentArguments(
NodeList<Expression> arguments,
List<DartObjectImpl> argumentValues,
Map<String, DartObjectImpl> namedArgumentValues,
InterfaceType expectedDefaultValueType) {
int argumentCount = arguments.length;
if (argumentCount < 1 || argumentCount > 2) {
return false;
}
if (arguments[0] is NamedExpression) {
return false;
}
if (argumentValues[0].type != typeProvider.stringType) {
return false;
}
if (argumentCount == 2) {
Expression secondArgument = arguments[1];
if (secondArgument is NamedExpression) {
if (!(secondArgument.name.label.name == _DEFAULT_VALUE_PARAM)) {
return false;
}
ParameterizedType defaultValueType =
namedArgumentValues[_DEFAULT_VALUE_PARAM].type;
if (!(defaultValueType == expectedDefaultValueType ||
defaultValueType == typeProvider.nullType)) {
return false;
}
} else {
return false;
}
}
return true;
}
/// Check that the arguments to a call to Symbol() are correct. The
/// [arguments] are the AST nodes of the arguments. The [argumentValues] are
/// the values of the unnamed arguments. The [namedArgumentValues] are the
/// values of the named arguments. Return `true` if the arguments are correct,
/// `false` if there is an error.
bool checkSymbolArguments(
NodeList<Expression> arguments,
List<DartObjectImpl> argumentValues,
Map<String, DartObjectImpl> namedArgumentValues) {
if (arguments.length != 1) {
return false;
}
if (arguments[0] is NamedExpression) {
return false;
}
if (argumentValues[0].type != typeProvider.stringType) {
return false;
}
String name = argumentValues[0].toStringValue();
return isValidPublicSymbol(name);
}
/// Compute the constant value associated with the given [constant].
void computeConstantValue(ConstantEvaluationTarget constant) {
validator.beforeComputeValue(constant);
if (constant is ParameterElementImpl) {
if (constant.isOptional) {
Expression defaultValue = constant.constantInitializer;
if (defaultValue != null) {
RecordingErrorListener errorListener = new RecordingErrorListener();
ErrorReporter errorReporter =
new ErrorReporter(errorListener, constant.source);
DartObjectImpl dartObject =
defaultValue.accept(new ConstantVisitor(this, errorReporter));
constant.evaluationResult =
new EvaluationResultImpl(dartObject, errorListener.errors);
} else {
constant.evaluationResult =
EvaluationResultImpl(typeProvider.nullObject);
}
}
} else if (constant is VariableElementImpl) {
Expression constantInitializer = constant.constantInitializer;
if (constantInitializer != null) {
RecordingErrorListener errorListener = new RecordingErrorListener();
ErrorReporter errorReporter =
new ErrorReporter(errorListener, constant.source);
DartObjectImpl dartObject = constantInitializer
.accept(new ConstantVisitor(this, errorReporter));
// Only check the type for truly const declarations (don't check final
// fields with initializers, since their types may be generic. The type
// of the final field will be checked later, when the constructor is
// invoked).
if (dartObject != null && constant.isConst) {
if (!runtimeTypeMatch(dartObject, constant.type)) {
errorReporter.reportErrorForElement(
CheckedModeCompileTimeErrorCode.VARIABLE_TYPE_MISMATCH,
constant,
[dartObject.type, constant.type]);
}
}
constant.evaluationResult =
new EvaluationResultImpl(dartObject, errorListener.errors);
}
} else if (constant is ConstructorElementImpl) {
if (constant.isConst) {
// No evaluation needs to be done; constructor declarations are only in
// the dependency graph to ensure that any constants referred to in
// initializer lists and parameter defaults are evaluated before
// invocations of the constructor.
constant.isConstantEvaluated = true;
}
} else if (constant is ElementAnnotationImpl) {
Annotation constNode = constant.annotationAst;
Element element = constant.element;
if (element is PropertyAccessorElement &&
element.variable is VariableElementImpl) {
// The annotation is a reference to a compile-time constant variable.
// Just copy the evaluation result.
VariableElementImpl variableElement =
element.variable as VariableElementImpl;
if (variableElement.evaluationResult != null) {
constant.evaluationResult = variableElement.evaluationResult;
} else {
// This could happen in the event that the annotation refers to a
// non-constant. The error is detected elsewhere, so just silently
// ignore it here.
constant.evaluationResult = new EvaluationResultImpl(null);
}
} else if (element is ConstructorElement &&
element.isConst &&
constNode.arguments != null) {
RecordingErrorListener errorListener = new RecordingErrorListener();
ErrorReporter errorReporter =
new ErrorReporter(errorListener, constant.source);
ConstantVisitor constantVisitor =
new ConstantVisitor(this, errorReporter);
DartObjectImpl result = evaluateConstructorCall(
constNode,
constNode.arguments.arguments,
element,
constantVisitor,
errorReporter);
constant.evaluationResult =
new EvaluationResultImpl(result, errorListener.errors);
} else {
// This may happen for invalid code (e.g. failing to pass arguments
// to an annotation which references a const constructor). The error
// is detected elsewhere, so just silently ignore it here.
constant.evaluationResult = new EvaluationResultImpl(null);
}
} else if (constant is VariableElement) {
// constant is a VariableElement but not a VariableElementImpl. This can
// happen sometimes in the case of invalid user code (for example, a
// constant expression that refers to a non-static field inside a generic
// class will wind up referring to a FieldMember). The error is detected
// elsewhere, so just silently ignore it here.
} else {
// Should not happen.
assert(false);
AnalysisEngine.instance.logger
.logError("Constant value computer trying to compute "
"the value of a node of type ${constant.runtimeType}");
return;
}
}
/// Determine which constant elements need to have their values computed
/// prior to computing the value of [constant], and report them using
/// [callback].
void computeDependencies(
ConstantEvaluationTarget constant, ReferenceFinderCallback callback) {
ReferenceFinder referenceFinder = new ReferenceFinder(callback);
if (constant is ConstructorElement) {
constant = getConstructorImpl(constant);
}
if (constant is VariableElementImpl) {
Expression initializer = constant.constantInitializer;
if (initializer != null) {
initializer.accept(referenceFinder);
}
} else if (constant is ConstructorElementImpl) {
if (constant.isConst) {
ConstructorElement redirectedConstructor =
getConstRedirectedConstructor(constant);
if (redirectedConstructor != null) {
ConstructorElement redirectedConstructorBase =
getConstructorImpl(redirectedConstructor);
callback(redirectedConstructorBase);
return;
} else if (constant.isFactory) {
// Factory constructor, but getConstRedirectedConstructor returned
// null. This can happen if we're visiting one of the special
// external const factory constructors in the SDK, or if the code
// contains errors (such as delegating to a non-const constructor, or
// delegating to a constructor that can't be resolved). In any of
// these cases, we'll evaluate calls to this constructor without
// having to refer to any other constants. So we don't need to report
// any dependencies.
return;
}
bool defaultSuperInvocationNeeded = true;
List<ConstructorInitializer> initializers =
constant.constantInitializers;
if (initializers != null) {
for (ConstructorInitializer initializer in initializers) {
if (initializer is SuperConstructorInvocation ||
initializer is RedirectingConstructorInvocation) {
defaultSuperInvocationNeeded = false;
}
initializer.accept(referenceFinder);
}
}
if (defaultSuperInvocationNeeded) {
// No explicit superconstructor invocation found, so we need to
// manually insert a reference to the implicit superconstructor.
InterfaceType superclass =
(constant.returnType as InterfaceType).superclass;
if (superclass != null && !superclass.isObject) {
ConstructorElement unnamedConstructor =
getConstructorImpl(superclass.element.unnamedConstructor);
if (unnamedConstructor != null) {
callback(unnamedConstructor);
}
}
}
for (FieldElement field in constant.enclosingElement.fields) {
// Note: non-static const isn't allowed but we handle it anyway so
// that we won't be confused by incorrect code.
if ((field.isFinal || field.isConst) &&
!field.isStatic &&
field.initializer != null) {
callback(field);
}
}
for (ParameterElement parameterElement in constant.parameters) {
callback(parameterElement);
}
}
} else if (constant is ElementAnnotationImpl) {
Annotation constNode = constant.annotationAst;
Element element = constant.element;
if (element is PropertyAccessorElement &&
element.variable is VariableElementImpl) {
// The annotation is a reference to a compile-time constant variable,
// so it depends on the variable.
callback(element.variable);
} else if (element is ConstructorElementImpl) {
// The annotation is a constructor invocation, so it depends on the
// constructor.
callback(element);
} else {
// This could happen in the event of invalid code. The error will be
// reported at constant evaluation time.
}
if (constNode == null) {
// We cannot determine what element the annotation is on, nor the offset
// of the annotation, so there's not a lot of information in this
// message, but it's better than getting an exception.
// https://github.com/dart-lang/sdk/issues/26811
AnalysisEngine.instance.logger.logInformation(
'No annotationAst for $constant in ${constant.compilationUnit}');
} else if (constNode.arguments != null) {
constNode.arguments.accept(referenceFinder);
}
} else if (constant is VariableElement) {
// constant is a VariableElement but not a VariableElementImpl. This can
// happen sometimes in the case of invalid user code (for example, a
// constant expression that refers to a non-static field inside a generic
// class will wind up referring to a FieldMember). So just don't bother
// computing any dependencies.
} else {
// Should not happen.
assert(false);
AnalysisEngine.instance.logger
.logError("Constant value computer trying to compute "
"the value of a node of type ${constant.runtimeType}");
}
}
/// Evaluate a call to fromEnvironment() on the bool, int, or String class.
/// The [environmentValue] is the value fetched from the environment. The
/// [builtInDefaultValue] is the value that should be used as the default if
/// no "defaultValue" argument appears in [namedArgumentValues]. The
/// [namedArgumentValues] are the values of the named parameters passed to
/// fromEnvironment(). Return a [DartObjectImpl] object corresponding to the
/// evaluated result.
DartObjectImpl computeValueFromEnvironment(
DartObject environmentValue,
DartObjectImpl builtInDefaultValue,
Map<String, DartObjectImpl> namedArgumentValues) {
DartObjectImpl value = environmentValue as DartObjectImpl;
if (value.isUnknown || value.isNull) {
// The name either doesn't exist in the environment or we couldn't parse
// the corresponding value.
// If the code supplied an explicit default, use it.
if (namedArgumentValues.containsKey(_DEFAULT_VALUE_PARAM)) {
value = namedArgumentValues[_DEFAULT_VALUE_PARAM];
} else if (value.isNull) {
// The code didn't supply an explicit default.
// The name exists in the environment but we couldn't parse the
// corresponding value.
// So use the built-in default value, because this is what the VM does.
value = builtInDefaultValue;
} else {
// The code didn't supply an explicit default.
// The name doesn't exist in the environment.
// The VM would use the built-in default value, but we don't want to do
// that for analysis because it's likely to lead to cascading errors.
// So just leave [value] in the unknown state.
}
}
return value;
}
DartObjectImpl evaluateConstructorCall(
AstNode node,
List<Expression> arguments,
ConstructorElement constructor,
ConstantVisitor constantVisitor,
ErrorReporter errorReporter,
{ConstructorInvocation invocation}) {
if (!constructor.isConst) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_WITH_NON_CONST, node);
return null;
}
if (!getConstructorImpl(constructor).isCycleFree) {
// It's not safe to evaluate this constructor, so bail out.
// TODO(paulberry): ensure that a reasonable error message is produced
// in this case, as well as other cases involving constant expression
// circularities (e.g. "compile-time constant expression depends on
// itself")
return new DartObjectImpl.validWithUnknownValue(constructor.returnType);
}
int argumentCount = arguments.length;
var argumentValues = new List<DartObjectImpl>(argumentCount);
Map<String, NamedExpression> namedNodes;
Map<String, DartObjectImpl> namedValues;
for (int i = 0; i < argumentCount; i++) {
Expression argument = arguments[i];
if (argument is NamedExpression) {
namedNodes ??= new HashMap<String, NamedExpression>();
namedValues ??= new HashMap<String, DartObjectImpl>();
String name = argument.name.label.name;
namedNodes[name] = argument;
namedValues[name] = constantVisitor._valueOf(argument.expression);
} else {
var argumentValue = constantVisitor._valueOf(argument);
argumentValues[i] = argumentValue;
}
}
namedNodes ??= const {};
namedValues ??= const {};
if (invocation == null) {
invocation = new ConstructorInvocation(
constructor,
argumentValues,
namedValues,
);
}
constructor = followConstantRedirectionChain(constructor);
InterfaceType definingClass = constructor.returnType as InterfaceType;
if (constructor.isFactory) {
// We couldn't find a non-factory constructor.
// See if it's because we reached an external const factory constructor
// that we can emulate.
if (constructor.name == "fromEnvironment") {
if (!checkFromEnvironmentArguments(
arguments, argumentValues, namedValues, definingClass)) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
return null;
}
String variableName =
argumentCount < 1 ? null : argumentValues[0].toStringValue();
if (definingClass == typeProvider.boolType) {
DartObject valueFromEnvironment;
valueFromEnvironment =
_declaredVariables.getBool(typeProvider, variableName);
return computeValueFromEnvironment(
valueFromEnvironment,
new DartObjectImpl(typeProvider.boolType, BoolState.FALSE_STATE),
namedValues);
} else if (definingClass == typeProvider.intType) {
DartObject valueFromEnvironment;
valueFromEnvironment =
_declaredVariables.getInt(typeProvider, variableName);
return computeValueFromEnvironment(
valueFromEnvironment,
new DartObjectImpl(typeProvider.nullType, NullState.NULL_STATE),
namedValues);
} else if (definingClass == typeProvider.stringType) {
DartObject valueFromEnvironment;
valueFromEnvironment =
_declaredVariables.getString(typeProvider, variableName);
return computeValueFromEnvironment(
valueFromEnvironment,
new DartObjectImpl(typeProvider.nullType, NullState.NULL_STATE),
namedValues);
}
} else if (constructor.name == "" &&
definingClass == typeProvider.symbolType &&
argumentCount == 1) {
if (!checkSymbolArguments(arguments, argumentValues, namedValues)) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
return null;
}
String argumentValue = argumentValues[0].toStringValue();
return new DartObjectImpl(
definingClass, new SymbolState(argumentValue));
}
// Either it's an external const factory constructor that we can't
// emulate, or an error occurred (a cycle, or a const constructor trying
// to delegate to a non-const constructor).
// In the former case, the best we can do is consider it an unknown value.
// In the latter case, the error has already been reported, so considering
// it an unknown value will suppress further errors.
return new DartObjectImpl.validWithUnknownValue(definingClass);
}
ConstructorElementImpl constructorBase = getConstructorImpl(constructor);
validator.beforeGetConstantInitializers(constructorBase);
List<ConstructorInitializer> initializers =
constructorBase.constantInitializers;
if (initializers == null) {
// This can happen in some cases where there are compile errors in the
// code being analyzed (for example if the code is trying to create a
// const instance using a non-const constructor, or the node we're
// visiting is involved in a cycle). The error has already been reported,
// so consider it an unknown value to suppress further errors.
return new DartObjectImpl.validWithUnknownValue(definingClass);
}
var fieldMap = new HashMap<String, DartObjectImpl>();
// The errors reported while computing values for field initializers, or
// default values for the constructor parameters, cannot be reported
// into the current ErrorReporter, because they usually happen in a
// different source. But they still should cause a constant evaluation
// error for the current node.
var externalErrorListener = new BooleanErrorListener();
var externalErrorReporter =
new ErrorReporter(externalErrorListener, constructor.source);
// Start with final fields that are initialized at their declaration site.
List<FieldElement> fields = constructor.enclosingElement.fields;
for (int i = 0; i < fields.length; i++) {
FieldElement field = fields[i];
if ((field.isFinal || field.isConst) &&
!field.isStatic &&
field is ConstFieldElementImpl) {
validator.beforeGetFieldEvaluationResult(field);
DartObjectImpl fieldValue = field.evaluationResult?.value;
// It is possible that the evaluation result is null.
// This happens for example when we have duplicate fields.
// class Test {final x = 1; final x = 2; const Test();}
if (fieldValue == null) {
continue;
}
// Match the value and the type.
DartType fieldType =
FieldMember.from(field, constructor.returnType).type;
if (fieldValue != null && !runtimeTypeMatch(fieldValue, fieldType)) {
errorReporter.reportErrorForNode(
CheckedModeCompileTimeErrorCode
.CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH,
node,
[fieldValue.type, field.name, fieldType]);
}
fieldMap[field.name] = fieldValue;
}
}
// Now evaluate the constructor declaration.
Map<String, DartObjectImpl> parameterMap =
new HashMap<String, DartObjectImpl>();
List<ParameterElement> parameters = constructor.parameters;
int parameterCount = parameters.length;
for (int i = 0; i < parameterCount; i++) {
ParameterElement parameter = parameters[i];
ParameterElement baseParameter = parameter;
while (baseParameter is ParameterMember) {
baseParameter = (baseParameter as ParameterMember).baseElement;
}
DartObjectImpl argumentValue;
AstNode errorTarget;
if (baseParameter.isNamed) {
argumentValue = namedValues[baseParameter.name];
errorTarget = namedNodes[baseParameter.name];
} else if (i < argumentCount) {
argumentValue = argumentValues[i];
errorTarget = arguments[i];
}
if (errorTarget == null) {
// No argument node that we can direct error messages to, because we
// are handling an optional parameter that wasn't specified. So just
// direct error messages to the constructor call.
errorTarget = node;
}
if (argumentValue == null && baseParameter is ParameterElementImpl) {
// The parameter is an optional positional parameter for which no value
// was provided, so use the default value.
validator.beforeGetParameterDefault(baseParameter);
EvaluationResultImpl evaluationResult = baseParameter.evaluationResult;
if (evaluationResult == null) {
// No default was provided, so the default value is null.
argumentValue = typeProvider.nullObject;
} else if (evaluationResult.value != null) {
argumentValue = evaluationResult.value;
}
}
if (argumentValue != null) {
if (!runtimeTypeMatch(argumentValue, parameter.type)) {
errorReporter.reportErrorForNode(
CheckedModeCompileTimeErrorCode
.CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH,
errorTarget,
[argumentValue.type, parameter.type]);
}
if (baseParameter.isInitializingFormal) {
FieldElement field = (parameter as FieldFormalParameterElement).field;
if (field != null) {
DartType fieldType = field.type;
if (fieldType != parameter.type) {
// We've already checked that the argument can be assigned to the
// parameter; we also need to check that it can be assigned to
// the field.
if (!runtimeTypeMatch(argumentValue, fieldType)) {
errorReporter.reportErrorForNode(
CheckedModeCompileTimeErrorCode
.CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH,
errorTarget,
[argumentValue.type, fieldType]);
}
}
String fieldName = field.name;
if (fieldMap.containsKey(fieldName)) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
}
fieldMap[fieldName] = argumentValue;
}
}
String name = baseParameter.name;
parameterMap[name] = argumentValue;
}
}
ConstantVisitor initializerVisitor = new ConstantVisitor(
this, externalErrorReporter,
lexicalEnvironment: parameterMap);
String superName;
NodeList<Expression> superArguments;
for (var i = 0; i < initializers.length; i++) {
var initializer = initializers[i];
if (initializer is ConstructorFieldInitializer) {
Expression initializerExpression = initializer.expression;
DartObjectImpl evaluationResult =
initializerExpression?.accept(initializerVisitor);
if (evaluationResult != null) {
String fieldName = initializer.fieldName.name;
if (fieldMap.containsKey(fieldName)) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
}
fieldMap[fieldName] = evaluationResult;
PropertyAccessorElement getter = definingClass.getGetter(fieldName);
if (getter != null) {
PropertyInducingElement field = getter.variable;
if (!runtimeTypeMatch(evaluationResult, field.type)) {
errorReporter.reportErrorForNode(
CheckedModeCompileTimeErrorCode
.CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH,
node,
[evaluationResult.type, fieldName, field.type]);
}
}
} else {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
}
} else if (initializer is SuperConstructorInvocation) {
SimpleIdentifier name = initializer.constructorName;
if (name != null) {
superName = name.name;
}
superArguments = initializer.argumentList.arguments;
} else if (initializer is RedirectingConstructorInvocation) {
// This is a redirecting constructor, so just evaluate the constructor
// it redirects to.
ConstructorElement constructor = initializer.staticElement;
if (constructor != null && constructor.isConst) {
// Instantiate the constructor with the in-scope type arguments.
constructor = ConstructorMember.from(constructor, definingClass);
DartObjectImpl result = evaluateConstructorCall(
node,
initializer.argumentList.arguments,
constructor,
initializerVisitor,
externalErrorReporter,
invocation: invocation);
if (externalErrorListener.errorReported) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
}
return result;
}
} else if (initializer is AssertInitializer) {
Expression condition = initializer.condition;
if (condition == null) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
}
DartObjectImpl evaluationResult = condition.accept(initializerVisitor);
if (evaluationResult == null ||
!evaluationResult.isBool ||
evaluationResult.toBoolValue() == false) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
return null;
}
}
}
// Evaluate explicit or implicit call to super().
InterfaceType superclass = definingClass.superclass;
if (superclass != null && !superclass.isObject) {
ConstructorElement superConstructor =
superclass.lookUpConstructor(superName, constructor.library);
if (superConstructor != null) {
if (superArguments == null) {
superArguments = astFactory.nodeList<Expression>(null);
}
evaluateSuperConstructorCall(node, fieldMap, superConstructor,
superArguments, initializerVisitor, externalErrorReporter);
}
}
if (externalErrorListener.errorReported) {
errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, node);
}
return new DartObjectImpl(
definingClass, new GenericState(fieldMap, invocation: invocation));
}
void evaluateSuperConstructorCall(
AstNode node,
Map<String, DartObjectImpl> fieldMap,
ConstructorElement superConstructor,
List<Expression> superArguments,
ConstantVisitor initializerVisitor,
ErrorReporter errorReporter) {
if (superConstructor != null && superConstructor.isConst) {
DartObjectImpl evaluationResult = evaluateConstructorCall(node,
superArguments, superConstructor, initializerVisitor, errorReporter);
if (evaluationResult != null) {
fieldMap[GenericState.SUPERCLASS_FIELD] = evaluationResult;
}
}
}
/// Attempt to follow the chain of factory redirections until a constructor is
/// reached which is not a const factory constructor. Return the constant
/// constructor which terminates the chain of factory redirections, if the
/// chain terminates. If there is a problem (e.g. a redirection can't be
/// found, or a cycle is encountered), the chain will be followed as far as
/// possible and then a const factory constructor will be returned.
ConstructorElement followConstantRedirectionChain(
ConstructorElement constructor) {
HashSet<ConstructorElement> constructorsVisited =
new HashSet<ConstructorElement>();
while (true) {
ConstructorElement redirectedConstructor =
getConstRedirectedConstructor(constructor);
if (redirectedConstructor == null) {
break;
} else {
ConstructorElement constructorBase = getConstructorImpl(constructor);
constructorsVisited.add(constructorBase);
ConstructorElement redirectedConstructorBase =
getConstructorImpl(redirectedConstructor);
if (constructorsVisited.contains(redirectedConstructorBase)) {
// Cycle in redirecting factory constructors--this is not allowed
// and is checked elsewhere--see
// [ErrorVerifier.checkForRecursiveFactoryRedirect()]).
break;
}
}
constructor = redirectedConstructor;
}
return constructor;
}
/// Generate an error indicating that the given [constant] is not a valid
/// compile-time constant because it references at least one of the constants
/// in the given [cycle], each of which directly or indirectly references the
/// constant.
void generateCycleError(Iterable<ConstantEvaluationTarget> cycle,
ConstantEvaluationTarget constant) {
if (constant is VariableElement) {
RecordingErrorListener errorListener = new RecordingErrorListener();
ErrorReporter errorReporter =
new ErrorReporter(errorListener, constant.source);
// TODO(paulberry): It would be really nice if we could extract enough
// information from the 'cycle' argument to provide the user with a
// description of the cycle.
errorReporter.reportErrorForElement(
CompileTimeErrorCode.RECURSIVE_COMPILE_TIME_CONSTANT, constant, []);
(constant as VariableElementImpl).evaluationResult =
new EvaluationResultImpl(null, errorListener.errors);
} else if (constant is ConstructorElement) {
// We don't report cycle errors on constructor declarations since there
// is nowhere to put the error information.
} else {
// Should not happen. Formal parameter defaults and annotations should
// never appear as part of a cycle because they can't be referred to.
assert(false);
AnalysisEngine.instance.logger
.logError("Constant value computer trying to report a cycle error "
"for a node of type ${constant.runtimeType}");
}
}
/// If [constructor] redirects to another const constructor, return the
/// const constructor it redirects to. Otherwise return `null`.
ConstructorElement getConstRedirectedConstructor(
ConstructorElement constructor) {
if (!constructor.isFactory) {
return null;
}
if (constructor.enclosingElement == typeProvider.symbolElement) {
// The dart:core.Symbol has a const factory constructor that redirects
// to dart:_internal.Symbol. That in turn redirects to an external
// const constructor, which we won't be able to evaluate.
// So stop following the chain of redirections at dart:core.Symbol, and
// let [evaluateInstanceCreationExpression] handle it specially.
return null;
}
ConstructorElement redirectedConstructor =
constructor.redirectedConstructor;
if (redirectedConstructor == null) {
// This can happen if constructor is an external factory constructor.
return null;
}
if (!redirectedConstructor.isConst) {
// Delegating to a non-const constructor--this is not allowed (and
// is checked elsewhere--see
// [ErrorVerifier.checkForRedirectToNonConstConstructor()]).
return null;
}
return redirectedConstructor;
}
/// Check if the object [obj] matches the type [type] according to runtime
/// type checking rules.
bool runtimeTypeMatch(DartObjectImpl obj, DartType type) {
if (obj.isNull) {
return true;
}
var objType = obj.type;
if (objType.isDartCoreInt && type.isDartCoreDouble) {
// Work around dartbug.com/35993 by allowing `int` to be used in a place
// where `double` is expected.
//
// Note that this is not technically correct, because it allows code like
// this:
// const Object x = 1;
// const double y = x;
//
// TODO(paulberry): remove this workaround once dartbug.com/33441 is
// fixed.
return true;
}
return typeSystem.isSubtypeOf(objType, type);
}
/// Determine whether the given string is a valid name for a public symbol
/// (i.e. whether it is allowed for a call to the Symbol constructor).
static bool isValidPublicSymbol(String name) =>
name.isEmpty || name == "void" || _PUBLIC_SYMBOL_PATTERN.hasMatch(name);
}
/// Interface for [AnalysisTarget]s for which constant evaluation can be
/// performed.
abstract class ConstantEvaluationTarget extends AnalysisTarget {
/// Return the [AnalysisContext] which should be used to evaluate this
/// constant.
AnalysisContext get context;
/// Return whether this constant is evaluated.
bool get isConstantEvaluated;
}
/// Interface used by unit tests to verify correct dependency analysis during
/// constant evaluation.
abstract class ConstantEvaluationValidator {
/// This method is called just before computing the constant value associated
/// with [constant]. Unit tests will override this method to introduce
/// additional error checking.
void beforeComputeValue(ConstantEvaluationTarget constant);
/// This method is called just before getting the constant initializers
/// associated with the [constructor]. Unit tests will override this method to
/// introduce additional error checking.
void beforeGetConstantInitializers(ConstructorElement constructor);
/// This method is called just before retrieving an evaluation result from an
/// element. Unit tests will override it to introduce additional error
/// checking.
void beforeGetEvaluationResult(ConstantEvaluationTarget constant);
/// This method is called just before getting the constant value of a field
/// with an initializer. Unit tests will override this method to introduce
/// additional error checking.
void beforeGetFieldEvaluationResult(FieldElementImpl field);
/// This method is called just before getting a parameter's default value.
/// Unit tests will override this method to introduce additional error
/// checking.
void beforeGetParameterDefault(ParameterElement parameter);
}
/// Implementation of [ConstantEvaluationValidator] used in production; does no
/// validation.
class ConstantEvaluationValidator_ForProduction
implements ConstantEvaluationValidator {
@override
void beforeComputeValue(ConstantEvaluationTarget constant) {}
@override
void beforeGetConstantInitializers(ConstructorElement constructor) {}
@override
void beforeGetEvaluationResult(ConstantEvaluationTarget constant) {}
@override
void beforeGetFieldEvaluationResult(FieldElementImpl field) {}
@override
void beforeGetParameterDefault(ParameterElement parameter) {}
}
/// A visitor used to evaluate constant expressions to produce their
/// compile-time value.
class ConstantVisitor extends UnifyingAstVisitor<DartObjectImpl> {
/// The evaluation engine used to access the feature set, type system, and
/// type provider.
final ConstantEvaluationEngine evaluationEngine;
final Map<String, DartObjectImpl> _lexicalEnvironment;
/// Error reporter that we use to report errors accumulated while computing
/// the constant.
final ErrorReporter _errorReporter;
/// Helper class used to compute constant values.
DartObjectComputer _dartObjectComputer;
/// Initialize a newly created constant visitor. The [evaluationEngine] is
/// used to evaluate instance creation expressions. The [lexicalEnvironment]
/// is a map containing values which should override identifiers, or `null` if
/// no overriding is necessary. The [_errorReporter] is used to report errors
/// found during evaluation. The [validator] is used by unit tests to verify
/// correct dependency analysis.
ConstantVisitor(this.evaluationEngine, this._errorReporter,
{Map<String, DartObjectImpl> lexicalEnvironment})
: _lexicalEnvironment = lexicalEnvironment {
this._dartObjectComputer =
new DartObjectComputer(_errorReporter, evaluationEngine);
}
/// Return the object representing the state of active experiments.
ExperimentStatus get experimentStatus => evaluationEngine.experimentStatus;
/// Convenience getter to gain access to the [evaluationEngine]'s type system.
TypeSystem get typeSystem => evaluationEngine.typeSystem;
/// Convenience getter to gain access to the [evaluationEngine]'s type
/// provider.
TypeProvider get _typeProvider => evaluationEngine.typeProvider;
/// Given a [type] that may contain free type variables, evaluate them against
/// the current lexical environment and return the substituted type.
DartType evaluateType(DartType type) {
if (type is TypeParameterType) {
return null;
}
if (type is ParameterizedType) {
List<DartType> typeArguments;
for (int i = 0; i < type.typeArguments.length; i++) {
DartType ta = type.typeArguments[i];
DartType t = evaluateType(ta);
if (!identical(t, ta)) {
if (typeArguments == null) {
typeArguments = type.typeArguments.toList(growable: false);
}
typeArguments[i] = t;
}
}
if (typeArguments == null) return type;
return type.substitute2(typeArguments, type.typeArguments);
}
return type;
}
/// Given a [type], returns the constant value that contains that type value.
DartObjectImpl typeConstant(DartType type) {
return new DartObjectImpl(_typeProvider.typeType, new TypeState(type));
}
@override
DartObjectImpl visitAdjacentStrings(AdjacentStrings node) {
DartObjectImpl result;
for (StringLiteral string in node.strings) {
if (result == null) {
result = string.accept(this);
} else {
result =
_dartObjectComputer.concatenate(node, result, string.accept(this));
}
}
return result;
}
@override
DartObjectImpl visitAsExpression(AsExpression node) {
if (experimentStatus.constant_update_2018) {
DartObjectImpl expressionResult = node.expression.accept(this);
DartObjectImpl typeResult = node.type.accept(this);
return _dartObjectComputer.castToType(node, expressionResult, typeResult);
}
// TODO(brianwilkerson) Figure out which error to report.
_error(node, null);
return null;
}
@override
DartObjectImpl visitBinaryExpression(BinaryExpression node) {
TokenType operatorType = node.operator.type;
DartObjectImpl leftResult = node.leftOperand.accept(this);
// evaluate lazy operators
if (operatorType == TokenType.AMPERSAND_AMPERSAND) {
return _dartObjectComputer.lazyAnd(
node, leftResult, () => node.rightOperand.accept(this));
} else if (operatorType == TokenType.BAR_BAR) {
return _dartObjectComputer.lazyOr(
node, leftResult, () => node.rightOperand.accept(this));
} else if (operatorType == TokenType.QUESTION_QUESTION) {
if (experimentStatus.constant_update_2018) {
return _dartObjectComputer.lazyQuestionQuestion(
node, leftResult, () => node.rightOperand.accept(this));
} else {
return _dartObjectComputer.eagerQuestionQuestion(
node, leftResult, node.rightOperand.accept(this));
}
}
// evaluate eager operators
DartObjectImpl rightResult = node.rightOperand.accept(this);
if (operatorType == TokenType.AMPERSAND) {
return _dartObjectComputer.eagerAnd(
node, leftResult, rightResult, experimentStatus.constant_update_2018);
} else if (operatorType == TokenType.BANG_EQ) {
return _dartObjectComputer.notEqual(node, leftResult, rightResult);
} else if (operatorType == TokenType.BAR) {
return _dartObjectComputer.eagerOr(
node, leftResult, rightResult, experimentStatus.constant_update_2018);
} else if (operatorType == TokenType.CARET) {
return _dartObjectComputer.eagerXor(
node, leftResult, rightResult, experimentStatus.constant_update_2018);
} else if (operatorType == TokenType.EQ_EQ) {
if (experimentStatus.constant_update_2018) {
return _dartObjectComputer.lazyEqualEqual(
node, leftResult, rightResult);
}
return _dartObjectComputer.equalEqual(node, leftResult, rightResult);
} else if (operatorType == TokenType.GT) {
return _dartObjectComputer.greaterThan(node, leftResult, rightResult);
} else if (operatorType == TokenType.GT_EQ) {
return _dartObjectComputer.greaterThanOrEqual(
node, leftResult, rightResult);
} else if (operatorType == TokenType.GT_GT) {
return _dartObjectComputer.shiftRight(node, leftResult, rightResult);
} else if (operatorType == TokenType.GT_GT_GT) {
return _dartObjectComputer.logicalShiftRight(
node, leftResult, rightResult);
} else if (operatorType == TokenType.LT) {
return _dartObjectComputer.lessThan(node, leftResult, rightResult);
} else if (operatorType == TokenType.LT_EQ) {
return _dartObjectComputer.lessThanOrEqual(node, leftResult, rightResult);
} else if (operatorType == TokenType.LT_LT) {
return _dartObjectComputer.shiftLeft(node, leftResult, rightResult);
} else if (operatorType == TokenType.MINUS) {
return _dartObjectComputer.minus(node, leftResult, rightResult);
} else if (operatorType == TokenType.PERCENT) {
return _dartObjectComputer.remainder(node, leftResult, rightResult);
} else if (operatorType == TokenType.PLUS) {
return _dartObjectComputer.add(node, leftResult, rightResult);
} else if (operatorType == TokenType.STAR) {
return _dartObjectComputer.times(node, leftResult, rightResult);
} else if (operatorType == TokenType.SLASH) {
return _dartObjectComputer.divide(node, leftResult, rightResult);
} else if (operatorType == TokenType.TILDE_SLASH) {
return _dartObjectComputer.integerDivide(node, leftResult, rightResult);
} else {
// TODO(brianwilkerson) Figure out which error to report.
_error(node, null);
return null;
}
}
@override
DartObjectImpl visitBooleanLiteral(BooleanLiteral node) =>
new DartObjectImpl(_typeProvider.boolType, BoolState.from(node.value));
@override
DartObjectImpl visitConditionalExpression(ConditionalExpression node) {
Expression condition = node.condition;
DartObjectImpl conditionResult = condition.accept(this);
if (experimentStatus.constant_update_2018) {
if (conditionResult == null) {
return conditionResult;
} else if (!conditionResult.isBool) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL, condition);
return null;
}
conditionResult = _dartObjectComputer.applyBooleanConversion(
condition, conditionResult);
if (conditionResult == null) {
return conditionResult;
}
if (conditionResult.toBoolValue() == true) {
_reportNotPotentialConstants(node.elseExpression);
return node.thenExpression.accept(this);
} else if (conditionResult.toBoolValue() == false) {
_reportNotPotentialConstants(node.thenExpression);
return node.elseExpression.accept(this);
}
// We used to return an object with a known type and an unknown value, but
// we can't do that without evaluating both the 'then' and 'else'
// expressions, and we're not suppose to do that under lazy semantics. I'm
// not sure which failure mode is worse.
return null;
}
DartObjectImpl thenResult = node.thenExpression.accept(this);
DartObjectImpl elseResult = node.elseExpression.accept(this);
if (conditionResult == null) {
return conditionResult;
} else if (!conditionResult.isBool) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL, condition);
return null;
} else if (thenResult == null) {
return thenResult;
} else if (elseResult == null) {
return elseResult;
}
conditionResult =
_dartObjectComputer.applyBooleanConversion(condition, conditionResult);
if (conditionResult == null) {
return conditionResult;
}
if (conditionResult.toBoolValue() == true) {
return thenResult;
} else if (conditionResult.toBoolValue() == false) {
return elseResult;
}
ParameterizedType thenType = thenResult.type;
ParameterizedType elseType = elseResult.type;
return new DartObjectImpl.validWithUnknownValue(
typeSystem.getLeastUpperBound(thenType, elseType) as ParameterizedType);
}
@override
DartObjectImpl visitDoubleLiteral(DoubleLiteral node) =>
new DartObjectImpl(_typeProvider.doubleType, new DoubleState(node.value));
@override
DartObjectImpl visitInstanceCreationExpression(
InstanceCreationExpression node) {
if (!node.isConst) {
// TODO(brianwilkerson) Figure out which error to report.
_error(node, null);
return null;
}
ConstructorElement constructor = node.staticElement;
if (constructor == null) {
// Couldn't resolve the constructor so we can't compute a value. No
// problem - the error has already been reported.
return null;
}
return evaluationEngine.evaluateConstructorCall(
node, node.argumentList.arguments, constructor, this, _errorReporter);
}
@override
DartObjectImpl visitIntegerLiteral(IntegerLiteral node) {
if (node.staticType == _typeProvider.doubleType) {
return new DartObjectImpl(
_typeProvider.doubleType, new DoubleState(node.value?.toDouble()));
}
return new DartObjectImpl(_typeProvider.intType, new IntState(node.value));
}
@override
DartObjectImpl visitInterpolationExpression(InterpolationExpression node) {
DartObjectImpl result = node.expression.accept(this);
if (result != null && !result.isBoolNumStringOrNull) {
_error(node, CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING);
return null;
}
return _dartObjectComputer.performToString(node, result);
}
@override
DartObjectImpl visitInterpolationString(InterpolationString node) =>
new DartObjectImpl(_typeProvider.stringType, new StringState(node.value));
@override
DartObjectImpl visitIsExpression(IsExpression node) {
if (experimentStatus.constant_update_2018) {
DartObjectImpl expressionResult = node.expression.accept(this);
DartObjectImpl typeResult = node.type.accept(this);
return _dartObjectComputer.typeTest(node, expressionResult, typeResult);
}
// TODO(brianwilkerson) Figure out which error to report.
_error(node, null);
return null;
}
@override
DartObjectImpl visitListLiteral(ListLiteral node) {
if (!node.isConst) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.MISSING_CONST_IN_LIST_LITERAL, node);
return null;
}
bool errorOccurred = false;
List<DartObjectImpl> list = [];
for (CollectionElement element in node.elements) {
errorOccurred = errorOccurred | _addElementsToList(list, element);
}
if (errorOccurred) {
return null;
}
DartType nodeType = node.staticType;
DartType elementType =
nodeType is InterfaceType && nodeType.typeArguments.isNotEmpty
? nodeType.typeArguments[0]
: _typeProvider.dynamicType;
InterfaceType listType = _typeProvider.listType2(elementType);
return new DartObjectImpl(listType, new ListState(list));
}
@override
DartObjectImpl visitMethodInvocation(MethodInvocation node) {
Element element = node.methodName.staticElement;
if (element is FunctionElement) {
if (element.name == "identical") {
NodeList<Expression> arguments = node.argumentList.arguments;
if (arguments.length == 2) {
Element enclosingElement = element.enclosingElement;
if (enclosingElement is CompilationUnitElement) {
LibraryElement library = enclosingElement.library;
if (library.isDartCore) {
DartObjectImpl leftArgument = arguments[0].accept(this);
DartObjectImpl rightArgument = arguments[1].accept(this);
return _dartObjectComputer.isIdentical(
node, leftArgument, rightArgument);
}
}
}
}
}
// TODO(brianwilkerson) Figure out which error to report.
_error(node, null);
return null;
}
@override
DartObjectImpl visitNamedExpression(NamedExpression node) =>
node.expression.accept(this);
@override
DartObjectImpl visitNode(AstNode node) {
// TODO(brianwilkerson) Figure out which error to report.
_error(node, null);
return null;
}
@override
DartObjectImpl visitNullLiteral(NullLiteral node) => _typeProvider.nullObject;
@override
DartObjectImpl visitParenthesizedExpression(ParenthesizedExpression node) =>
node.expression.accept(this);
@override
DartObjectImpl visitPrefixedIdentifier(PrefixedIdentifier node) {
SimpleIdentifier prefixNode = node.prefix;
Element prefixElement = prefixNode.staticElement;
// String.length
if (prefixElement is! PrefixElement && prefixElement is! ClassElement) {
DartObjectImpl prefixResult = node.prefix.accept(this);
if (_isStringLength(prefixResult, node.identifier)) {
return prefixResult.stringLength(_typeProvider);
}
}
// importPrefix.CONST
if (prefixElement is! PrefixElement) {
DartObjectImpl prefixResult = prefixNode.accept(this);
if (prefixResult == null) {
// The error has already been reported.
return null;
}
}
// validate prefixed identifier
return _getConstantValue(node, node.staticElement);
}
@override
DartObjectImpl visitPrefixExpression(PrefixExpression node) {
DartObjectImpl operand = node.operand.accept(this);
if (operand != null && operand.isNull) {
_error(node, CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
return null;
}
if (node.operator.type == TokenType.BANG) {
return _dartObjectComputer.logicalNot(node, operand);
} else if (node.operator.type == TokenType.TILDE) {
return _dartObjectComputer.bitNot(node, operand);
} else if (node.operator.type == TokenType.MINUS) {
return _dartObjectComputer.negated(node, operand);
} else {
// TODO(brianwilkerson) Figure out which error to report.
_error(node, null);
return null;
}
}
@override
DartObjectImpl visitPropertyAccess(PropertyAccess node) {
if (node.target != null) {
DartObjectImpl prefixResult = node.target.accept(this);
if (_isStringLength(prefixResult, node.propertyName)) {
return prefixResult.stringLength(_typeProvider);
}
}
return _getConstantValue(node, node.propertyName.staticElement);
}
@override
DartObjectImpl visitSetOrMapLiteral(SetOrMapLiteral node) {
// Note: due to dartbug.com/33441, it's possible that a set/map literal
// resynthesized from a summary will have neither its `isSet` or `isMap`
// boolean set to `true`. We work around the problem by assuming such
// literals are maps.
// TODO(paulberry): when dartbug.com/33441 is fixed, add an assertion here
// to verify that `node.isSet == !node.isMap`.
bool isMap = !node.isSet;
if (isMap) {
if (!node.isConst) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.MISSING_CONST_IN_MAP_LITERAL, node);
return null;
}
bool errorOccurred = false;
Map<DartObjectImpl, DartObjectImpl> map = {};
for (CollectionElement element in node.elements) {
errorOccurred = errorOccurred | _addElementsToMap(map, element);
}
if (errorOccurred) {
return null;
}
DartType keyType = _typeProvider.dynamicType;
DartType valueType = _typeProvider.dynamicType;
DartType nodeType = node.staticType;
if (nodeType is InterfaceType) {
var typeArguments = nodeType.typeArguments;
if (typeArguments.length >= 2) {
keyType = typeArguments[0];
valueType = typeArguments[1];
}
}
InterfaceType mapType = _typeProvider.mapType2(keyType, valueType);
return new DartObjectImpl(mapType, new MapState(map));
} else {
if (!node.isConst) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.MISSING_CONST_IN_SET_LITERAL, node);
return null;
}
bool errorOccurred = false;
Set<DartObjectImpl> set = new Set<DartObjectImpl>();
for (CollectionElement element in node.elements) {
errorOccurred = errorOccurred | _addElementsToSet(set, element);
}
if (errorOccurred) {
return null;
}
DartType nodeType = node.staticType;
DartType elementType =
nodeType is InterfaceType && nodeType.typeArguments.isNotEmpty
? nodeType.typeArguments[0]
: _typeProvider.dynamicType;
InterfaceType setType = _typeProvider.setType2(elementType);
return new DartObjectImpl(setType, new SetState(set));
}
}
@override
DartObjectImpl visitSimpleIdentifier(SimpleIdentifier node) {
if (_lexicalEnvironment != null &&
_lexicalEnvironment.containsKey(node.name)) {
return _lexicalEnvironment[node.name];
}
return _getConstantValue(node, node.staticElement);
}
@override
DartObjectImpl visitSimpleStringLiteral(SimpleStringLiteral node) =>
new DartObjectImpl(_typeProvider.stringType, new StringState(node.value));
@override
DartObjectImpl visitStringInterpolation(StringInterpolation node) {
DartObjectImpl result;
bool first = true;
for (InterpolationElement element in node.elements) {
if (first) {
result = element.accept(this);
first = false;
} else {
result =
_dartObjectComputer.concatenate(node, result, element.accept(this));
}
}
return result;
}
@override
DartObjectImpl visitSymbolLiteral(SymbolLiteral node) {
StringBuffer buffer = new StringBuffer();
List<Token> components = node.components;
for (int i = 0; i < components.length; i++) {
if (i > 0) {
buffer.writeCharCode(0x2E);
}
buffer.write(components[i].lexeme);
}
return new DartObjectImpl(
_typeProvider.symbolType, new SymbolState(buffer.toString()));
}
DartObjectImpl visitTypeAnnotation(TypeAnnotation node) {
DartType type = evaluateType(node.type);
if (type == null) {
return super.visitTypeName(node);
}
return typeConstant(type);
}
@override
DartObjectImpl visitTypeName(TypeName node) => visitTypeAnnotation(node);
/// Add the entries produced by evaluating the given collection [element] to
/// the given [list]. Return `true` if the evaluation of one or more of the
/// elements failed.
bool _addElementsToList(List<DartObject> list, CollectionElement element) {
if (element is IfElement) {
bool conditionValue = _evaluateCondition(element.condition);
if (conditionValue == null) {
return true;
} else if (conditionValue) {
return _addElementsToList(list, element.thenElement);
} else if (element.elseElement != null) {
return _addElementsToList(list, element.elseElement);
}
return false;
} else if (element is Expression) {
DartObjectImpl value = element.accept(this);
if (value == null) {
return true;
}
list.add(value);
return false;
} else if (element is SpreadElement) {
DartObjectImpl elementResult = element.expression.accept(this);
List<DartObject> value = elementResult?.toListValue();
if (value == null) {
return true;
}
list.addAll(value);
return false;
}
// This error should have been reported elsewhere.
return true;
}
/// Add the entries produced by evaluating the given map [element] to the
/// given [map]. Return `true` if the evaluation of one or more of the entries
/// failed.
bool _addElementsToMap(
Map<DartObjectImpl, DartObjectImpl> map, CollectionElement element) {
if (element is IfElement) {
bool conditionValue = _evaluateCondition(element.condition);
if (conditionValue == null) {
return true;
} else if (conditionValue) {
return _addElementsToMap(map, element.thenElement);
} else if (element.elseElement != null) {
return _addElementsToMap(map, element.elseElement);
}
return false;
} else if (element is MapLiteralEntry) {
DartObjectImpl keyResult = element.key.accept(this);
DartObjectImpl valueResult = element.value.accept(this);
if (keyResult == null || valueResult == null) {
return true;
}
map[keyResult] = valueResult;
return false;
} else if (element is SpreadElement) {
DartObjectImpl elementResult = element.expression.accept(this);
Map<DartObject, DartObject> value = elementResult?.toMapValue();
if (value == null) {
return true;
}
map.addAll(value);
return false;
}
// This error should have been reported elsewhere.
return true;
}
/// Add the entries produced by evaluating the given collection [element] to
/// the given [set]. Return `true` if the evaluation of one or more of the
/// elements failed.
bool _addElementsToSet(Set<DartObject> set, CollectionElement element) {
if (element is IfElement) {
bool conditionValue = _evaluateCondition(element.condition);
if (conditionValue == null) {
return true;
} else if (conditionValue) {
return _addElementsToSet(set, element.thenElement);
} else if (element.elseElement != null) {
return _addElementsToSet(set, element.elseElement);
}
return false;
} else if (element is Expression) {
DartObjectImpl value = element.accept(this);
if (value == null) {
return true;
}
set.add(value);
return false;
} else if (element is SpreadElement) {
DartObjectImpl elementResult = element.expression.accept(this);
Set<DartObject> value = elementResult?.toSetValue();
if (value == null) {
return true;
}
set.addAll(value);
return false;
}
// This error should have been reported elsewhere.
return true;
}
/// Create an error associated with the given [node]. The error will have the
/// given error [code].
void _error(AstNode node, ErrorCode code) {
if (code == null) {
var parent = node?.parent;
var parent2 = parent?.parent;
if (parent is ArgumentList &&
parent2 is InstanceCreationExpression &&
parent2.isConst) {
code = CompileTimeErrorCode.CONST_WITH_NON_CONSTANT_ARGUMENT;
} else {
code = CompileTimeErrorCode.INVALID_CONSTANT;
}
}
_errorReporter.reportErrorForNode(
code ?? CompileTimeErrorCode.INVALID_CONSTANT, node);
}
/// Evaluate the given [condition] with the assumption that it must be a
/// `bool`.
bool _evaluateCondition(Expression condition) {
DartObjectImpl conditionResult = condition.accept(this);
bool conditionValue = conditionResult?.toBoolValue();
if (conditionValue == null) {
if (conditionResult?.type != _typeProvider.boolType) {
// TODO(brianwilkerson) Figure out why the static type is sometimes null.
DartType staticType = condition.staticType;
if (staticType == null ||
typeSystem.isAssignableTo(staticType, _typeProvider.boolType)) {
// If the static type is not assignable, then we will have already
// reported this error.
// TODO(mfairhurst) get the FeatureSet to suppress this for nnbd too.
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION, condition);
}
}
}
return conditionValue;
}
/// Return the constant value of the static constant represented by the given
/// [element]. The [node] is the node to be used if an error needs to be
/// reported.
DartObjectImpl _getConstantValue(Expression node, Element element) {
Element variableElement =
element is PropertyAccessorElement ? element.variable : element;
if (variableElement is VariableElementImpl) {
// We access values of constant variables here in two cases: when we
// compute values of other constant variables, or when we compute values
// and errors for other constant expressions. In either case we have
// already computed values of all dependencies first (or detect a cycle),
// so the value has already been computed and we can just return it.
EvaluationResultImpl value = variableElement.evaluationResult;
if (variableElement.isConst && value != null) {
return value.value;
}
} else if (variableElement is ExecutableElement) {
ExecutableElement function = element;
if (function.isStatic) {
var functionType = node.staticType;
return DartObjectImpl(functionType, FunctionState(function));
}
} else if (variableElement is ClassElement) {
var type = variableElement.instantiate(
typeArguments: variableElement.typeParameters
.map((t) => _typeProvider.dynamicType)
.toList(),
nullabilitySuffix: NullabilitySuffix.star,
);
return DartObjectImpl(_typeProvider.typeType, TypeState(type));
} else if (variableElement is DynamicElementImpl) {
return DartObjectImpl(
_typeProvider.typeType,
TypeState(_typeProvider.dynamicType),
);
} else if (variableElement is FunctionTypeAliasElement) {
var type = variableElement.instantiate2(
typeArguments: variableElement.typeParameters
.map((t) => _typeProvider.dynamicType)
.toList(),
nullabilitySuffix: NullabilitySuffix.star,
);
return DartObjectImpl(_typeProvider.typeType, TypeState(type));
} else if (variableElement is NeverElementImpl) {
return DartObjectImpl(
_typeProvider.typeType,
TypeState(_typeProvider.neverType),
);
} else if (variableElement is TypeParameterElement) {
// Constants may not refer to type parameters.
}
// TODO(brianwilkerson) Figure out which error to report.
_error(node, null);
return null;
}
/// Return `true` if the given [targetResult] represents a string and the
/// [identifier] is "length".
bool _isStringLength(
DartObjectImpl targetResult, SimpleIdentifier identifier) {
if (targetResult == null || targetResult.type != _typeProvider.stringType) {
return false;
}
return identifier.name == 'length';
}
void _reportNotPotentialConstants(AstNode node) {
var notPotentiallyConstants = getNotPotentiallyConstants(node);
if (notPotentiallyConstants.isEmpty) return;
for (var notConst in notPotentiallyConstants) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.INVALID_CONSTANT,
notConst,
);
}
}
/// Return the value of the given [expression], or a representation of 'null'
/// if the expression cannot be evaluated.
DartObjectImpl _valueOf(Expression expression) {
DartObjectImpl expressionValue = expression.accept(this);
if (expressionValue != null) {
return expressionValue;
}
return _typeProvider.nullObject;
}
}
/// A utility class that contains methods for manipulating instances of a Dart
/// class and for collecting errors during evaluation.
class DartObjectComputer {
/// The error reporter that we are using to collect errors.
final ErrorReporter _errorReporter;
/// The evaluation engine used to access the type system, and type provider.
final ConstantEvaluationEngine _evaluationEngine;
DartObjectComputer(this._errorReporter, this._evaluationEngine);
/// Convenience getter to gain access to the [evaluationEngine]'s type
/// provider.
TypeProvider get _typeProvider => _evaluationEngine.typeProvider;
/// Convenience getter to gain access to the [evaluationEngine]'s type system.
TypeSystem get _typeSystem => _evaluationEngine.typeSystem;
DartObjectImpl add(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.add(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
return null;
}
}
return null;
}
/// Return the result of applying boolean conversion to the
/// [evaluationResult]. The [node] is the node against which errors should be
/// reported.
DartObjectImpl applyBooleanConversion(
AstNode node, DartObjectImpl evaluationResult) {
if (evaluationResult != null) {
try {
return evaluationResult.convertToBool(_typeProvider);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl bitNot(Expression node, DartObjectImpl evaluationResult) {
if (evaluationResult != null) {
try {
return evaluationResult.bitNot(_typeProvider);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl castToType(
AsExpression node, DartObjectImpl expression, DartObjectImpl type) {
if (expression != null && type != null) {
try {
return expression.castToType(_typeProvider, _typeSystem, type);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl concatenate(Expression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.concatenate(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl divide(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.divide(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl eagerAnd(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand, bool allowBool) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.eagerAnd(_typeProvider, rightOperand, allowBool);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl eagerOr(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand, bool allowBool) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.eagerOr(_typeProvider, rightOperand, allowBool);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl eagerQuestionQuestion(Expression node,
DartObjectImpl leftOperand, DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
if (leftOperand.isNull) {
return rightOperand;
}
return leftOperand;
}
return null;
}
DartObjectImpl eagerXor(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand, bool allowBool) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.eagerXor(_typeProvider, rightOperand, allowBool);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl equalEqual(Expression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.equalEqual(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl greaterThan(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.greaterThan(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl greaterThanOrEqual(BinaryExpression node,
DartObjectImpl leftOperand, DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.greaterThanOrEqual(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl integerDivide(BinaryExpression node,
DartObjectImpl leftOperand, DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.integerDivide(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl isIdentical(Expression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.isIdentical(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl lazyAnd(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperandComputer()) {
if (leftOperand != null) {
try {
return leftOperand.lazyAnd(_typeProvider, rightOperandComputer);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl lazyEqualEqual(Expression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.lazyEqualEqual(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl lazyOr(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperandComputer()) {
if (leftOperand != null) {
try {
return leftOperand.lazyOr(_typeProvider, rightOperandComputer);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl lazyQuestionQuestion(Expression node,
DartObjectImpl leftOperand, DartObjectImpl rightOperandComputer()) {
if (leftOperand != null) {
if (leftOperand.isNull) {
return rightOperandComputer();
}
return leftOperand;
}
return null;
}
DartObjectImpl lessThan(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.lessThan(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl lessThanOrEqual(BinaryExpression node,
DartObjectImpl leftOperand, DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.lessThanOrEqual(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl logicalNot(Expression node, DartObjectImpl evaluationResult) {
if (evaluationResult != null) {
try {
return evaluationResult.logicalNot(_typeProvider);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl logicalShiftRight(BinaryExpression node,
DartObjectImpl leftOperand, DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.logicalShiftRight(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl minus(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.minus(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl negated(Expression node, DartObjectImpl evaluationResult) {
if (evaluationResult != null) {
try {
return evaluationResult.negated(_typeProvider);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl notEqual(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.notEqual(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl performToString(
AstNode node, DartObjectImpl evaluationResult) {
if (evaluationResult != null) {
try {
return evaluationResult.performToString(_typeProvider);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl remainder(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.remainder(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl shiftLeft(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.shiftLeft(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl shiftRight(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.shiftRight(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
/// Return the result of invoking the 'length' getter on the
/// [evaluationResult]. The [node] is the node against which errors should be
/// reported.
EvaluationResultImpl stringLength(
Expression node, EvaluationResultImpl evaluationResult) {
if (evaluationResult.value != null) {
try {
return new EvaluationResultImpl(
evaluationResult.value.stringLength(_typeProvider));
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return new EvaluationResultImpl(null);
}
DartObjectImpl times(BinaryExpression node, DartObjectImpl leftOperand,
DartObjectImpl rightOperand) {
if (leftOperand != null && rightOperand != null) {
try {
return leftOperand.times(_typeProvider, rightOperand);
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
DartObjectImpl typeTest(
IsExpression node, DartObjectImpl expression, DartObjectImpl type) {
if (expression != null && type != null) {
try {
DartObjectImpl result =
expression.hasType(_typeProvider, _typeSystem, type);
if (node.notOperator != null) {
return result.logicalNot(_typeProvider);
}
return result;
} on EvaluationException catch (exception) {
_errorReporter.reportErrorForNode(exception.errorCode, node);
}
}
return null;
}
}
/// The result of attempting to evaluate an expression.
class EvaluationResult {
// TODO(brianwilkerson) Merge with EvaluationResultImpl
/// The value of the expression.
final DartObject value;
/// The errors that should be reported for the expression(s) that were
/// evaluated.
final List<AnalysisError> _errors;
/// Initialize a newly created result object with the given [value] and set of
/// [_errors]. Clients should use one of the factory methods: [forErrors] and
/// [forValue].
EvaluationResult(this.value, this._errors);
/// Return a list containing the errors that should be reported for the
/// expression(s) that were evaluated. If there are no such errors, the list
/// will be empty. The list can be empty even if the expression is not a valid
/// compile time constant if the errors would have been reported by other
/// parts of the analysis engine.
List<AnalysisError> get errors => _errors ?? AnalysisError.NO_ERRORS;
/// Return `true` if the expression is a compile-time constant expression that
/// would not throw an exception when evaluated.
bool get isValid => _errors == null;
/// Return an evaluation result representing the result of evaluating an
/// expression that is not a compile-time constant because of the given
/// [errors].
static EvaluationResult forErrors(List<AnalysisError> errors) =>
new EvaluationResult(null, errors);
/// Return an evaluation result representing the result of evaluating an
/// expression that is a compile-time constant that evaluates to the given
/// [value].
static EvaluationResult forValue(DartObject value) =>
new EvaluationResult(value, null);
}
/// The result of attempting to evaluate a expression.
class EvaluationResultImpl {
/// The errors encountered while trying to evaluate the compile time constant.
/// These errors may or may not have prevented the expression from being a
/// valid compile time constant.
List<AnalysisError> _errors;
/// The value of the expression, or `null` if the value couldn't be computed
/// due to errors.
final DartObjectImpl value;
EvaluationResultImpl(this.value, [List<AnalysisError> errors]) {
this._errors = errors ?? <AnalysisError>[];
}
List<AnalysisError> get errors => _errors;
bool equalValues(TypeProvider typeProvider, EvaluationResultImpl result) {
if (this.value != null) {
if (result.value == null) {
return false;
}
return value == result.value;
} else {
return false;
}
}
@override
String toString() {
if (value == null) {
return "error";
}
return value.toString();
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/constant/constant_verifier.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/dart/analysis/declared_variables.dart';
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/constant/evaluation.dart';
import 'package:analyzer/src/dart/constant/potentially_constant.dart';
import 'package:analyzer/src/dart/constant/value.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/diagnostic/diagnostic_factory.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
/// Instances of the class `ConstantVerifier` traverse an AST structure looking
/// for additional errors and warnings not covered by the parser and resolver.
/// In particular, it looks for errors and warnings related to constant
/// expressions.
class ConstantVerifier extends RecursiveAstVisitor<void> {
/// The error reporter by which errors will be reported.
final ErrorReporter _errorReporter;
/// The type provider used to access the known types.
final TypeProvider _typeProvider;
/// The set of variables declared using '-D' on the command line.
final DeclaredVariables declaredVariables;
/// The type representing the type 'int'.
final InterfaceType _intType;
/// The current library that is being analyzed.
final LibraryElement _currentLibrary;
final bool _constantUpdate2018Enabled;
final ConstantEvaluationEngine _evaluationEngine;
final DiagnosticFactory _diagnosticFactory = DiagnosticFactory();
/// Initialize a newly created constant verifier.
ConstantVerifier(ErrorReporter errorReporter, LibraryElement currentLibrary,
TypeProvider typeProvider, DeclaredVariables declaredVariables,
// TODO(brianwilkerson) Remove the unused parameter `forAnalysisDriver`.
{bool forAnalysisDriver,
// TODO(paulberry): make [featureSet] a required parameter.
FeatureSet featureSet})
: this._(
errorReporter,
currentLibrary,
typeProvider,
declaredVariables,
currentLibrary.context.typeSystem,
featureSet ??
(currentLibrary.context.analysisOptions as AnalysisOptionsImpl)
.contextFeatures);
ConstantVerifier._(
this._errorReporter,
this._currentLibrary,
this._typeProvider,
this.declaredVariables,
TypeSystem typeSystem,
FeatureSet featureSet)
: _constantUpdate2018Enabled =
featureSet.isEnabled(Feature.constant_update_2018),
_intType = _typeProvider.intType,
_evaluationEngine = new ConstantEvaluationEngine(
_typeProvider, declaredVariables,
typeSystem: typeSystem, experimentStatus: featureSet);
@override
void visitAnnotation(Annotation node) {
super.visitAnnotation(node);
// check annotation creation
Element element = node.element;
if (element is ConstructorElement) {
// should be 'const' constructor
if (!element.isConst) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.NON_CONSTANT_ANNOTATION_CONSTRUCTOR, node);
return;
}
// should have arguments
ArgumentList argumentList = node.arguments;
if (argumentList == null) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS, node);
return;
}
// arguments should be constants
_validateConstantArguments(argumentList);
}
}
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
if (node.constKeyword != null) {
_validateConstructorInitializers(node);
_validateFieldInitializers(node.parent, node);
}
_validateDefaultValues(node.parameters);
super.visitConstructorDeclaration(node);
}
@override
void visitFunctionExpression(FunctionExpression node) {
super.visitFunctionExpression(node);
_validateDefaultValues(node.parameters);
}
@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
if (node.isConst) {
TypeName typeName = node.constructorName.type;
_checkForConstWithTypeParameters(typeName);
// We need to evaluate the constant to see if any errors occur during its
// evaluation.
ConstructorElement constructor = node.staticElement;
if (constructor != null) {
ConstantVisitor constantVisitor =
new ConstantVisitor(_evaluationEngine, _errorReporter);
_evaluationEngine.evaluateConstructorCall(
node,
node.argumentList.arguments,
constructor,
constantVisitor,
_errorReporter);
}
} else {
super.visitInstanceCreationExpression(node);
}
}
@override
void visitListLiteral(ListLiteral node) {
super.visitListLiteral(node);
if (node.isConst) {
InterfaceType nodeType = node.staticType;
DartType elementType = nodeType.typeArguments[0];
var verifier = _ConstLiteralVerifier(
this,
errorCode: CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT,
forList: true,
listElementType: elementType,
);
for (CollectionElement element in node.elements) {
verifier.verify(element);
}
}
}
@override
void visitMethodDeclaration(MethodDeclaration node) {
super.visitMethodDeclaration(node);
_validateDefaultValues(node.parameters);
}
@override
void visitSetOrMapLiteral(SetOrMapLiteral node) {
super.visitSetOrMapLiteral(node);
if (node.isSet) {
if (node.isConst) {
InterfaceType nodeType = node.staticType;
var elementType = nodeType.typeArguments[0];
var duplicateElements = <Expression, Expression>{};
var verifier = _ConstLiteralVerifier(
this,
errorCode: CompileTimeErrorCode.NON_CONSTANT_SET_ELEMENT,
forSet: true,
setElementType: elementType,
setUniqueValues: <DartObject, Expression>{},
setDuplicateExpressions: duplicateElements,
);
for (CollectionElement element in node.elements) {
verifier.verify(element);
}
for (var duplicateElement in duplicateElements.keys) {
_errorReporter.reportError(_diagnosticFactory.equalElementsInConstSet(
_errorReporter.source,
duplicateElement,
duplicateElements[duplicateElement]));
}
}
} else if (node.isMap) {
if (node.isConst) {
InterfaceType nodeType = node.staticType;
var keyType = nodeType.typeArguments[0];
var valueType = nodeType.typeArguments[1];
bool reportEqualKeys = true;
var duplicateKeyElements = <Expression, Expression>{};
var verifier = _ConstLiteralVerifier(
this,
errorCode: CompileTimeErrorCode.NON_CONSTANT_MAP_ELEMENT,
forMap: true,
mapKeyType: keyType,
mapValueType: valueType,
mapUniqueKeys: <DartObject, Expression>{},
mapDuplicateKeyExpressions: duplicateKeyElements,
);
for (CollectionElement entry in node.elements) {
verifier.verify(entry);
}
if (reportEqualKeys) {
for (var duplicateKeyElement in duplicateKeyElements.keys) {
_errorReporter.reportError(_diagnosticFactory.equalKeysInConstMap(
_errorReporter.source,
duplicateKeyElement,
duplicateKeyElements[duplicateKeyElement]));
}
}
}
}
}
@override
void visitSwitchStatement(SwitchStatement node) {
// TODO(paulberry): to minimize error messages, it would be nice to
// compare all types with the most popular type rather than the first
// type.
NodeList<SwitchMember> switchMembers = node.members;
bool foundError = false;
DartType firstType;
for (SwitchMember switchMember in switchMembers) {
if (switchMember is SwitchCase) {
Expression expression = switchMember.expression;
DartObjectImpl caseResult = _validate(
expression, CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION);
if (caseResult != null) {
_reportErrorIfFromDeferredLibrary(
expression,
CompileTimeErrorCode
.NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY);
DartObject value = caseResult;
if (firstType == null) {
firstType = value.type;
} else {
DartType nType = value.type;
if (firstType != nType) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.INCONSISTENT_CASE_EXPRESSION_TYPES,
expression,
[expression.toSource(), firstType.displayName]);
foundError = true;
}
}
}
}
}
if (!foundError) {
_checkForCaseExpressionTypeImplementsEquals(node, firstType);
}
super.visitSwitchStatement(node);
}
@override
void visitVariableDeclaration(VariableDeclaration node) {
super.visitVariableDeclaration(node);
Expression initializer = node.initializer;
if (initializer != null && (node.isConst || node.isFinal)) {
VariableElementImpl element = node.declaredElement as VariableElementImpl;
EvaluationResultImpl result = element.evaluationResult;
if (result == null) {
// Variables marked "const" should have had their values computed by
// ConstantValueComputer. Other variables will only have had their
// values computed if the value was needed (e.g. final variables in a
// class containing const constructors).
assert(!node.isConst);
return;
}
if (node.isConst) {
_reportErrors(result.errors,
CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE);
} else {
_reportErrors(result.errors, null);
}
_reportErrorIfFromDeferredLibrary(
initializer,
CompileTimeErrorCode
.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY);
}
}
/// This verifies that the passed switch statement does not have a case
/// expression with the operator '==' overridden.
///
/// @param node the switch statement to evaluate
/// @param type the common type of all 'case' expressions
/// @return `true` if and only if an error code is generated on the passed
/// node.
/// See [CompileTimeErrorCode.CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS].
bool _checkForCaseExpressionTypeImplementsEquals(
SwitchStatement node, DartType type) {
if (!_implementsEqualsWhenNotAllowed(type)) {
return false;
}
// report error
_errorReporter.reportErrorForToken(
CompileTimeErrorCode.CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
node.switchKeyword,
[type.displayName]);
return true;
}
/// Verify that the given [type] does not reference any type parameters.
///
/// See [CompileTimeErrorCode.CONST_WITH_TYPE_PARAMETERS].
void _checkForConstWithTypeParameters(TypeAnnotation type) {
// something wrong with AST
if (type is! TypeName) {
return;
}
TypeName typeName = type;
Identifier name = typeName.name;
if (name == null) {
return;
}
// should not be a type parameter
if (name.staticElement is TypeParameterElement) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_WITH_TYPE_PARAMETERS, name);
}
// check type arguments
TypeArgumentList typeArguments = typeName.typeArguments;
if (typeArguments != null) {
for (TypeAnnotation argument in typeArguments.arguments) {
_checkForConstWithTypeParameters(argument);
}
}
}
/// @return `true` if given [Type] implements operator <i>==</i>, and it is
/// not <i>int</i> or <i>String</i>.
bool _implementsEqualsWhenNotAllowed(DartType type) {
// ignore int or String
if (type == null || type == _intType || type == _typeProvider.stringType) {
return false;
} else if (type == _typeProvider.doubleType) {
return true;
}
// prepare ClassElement
Element element = type.element;
if (element is ClassElement) {
// lookup for ==
MethodElement method =
element.lookUpConcreteMethod("==", _currentLibrary);
if (method == null ||
(method.enclosingElement as ClassElement).isDartCoreObject) {
return false;
}
// there is == that we don't like
return true;
}
return false;
}
/// Given some computed [Expression], this method generates the passed
/// [ErrorCode] on the node if its' value consists of information from a
/// deferred library.
///
/// @param expression the expression to be tested for a deferred library
/// reference
/// @param errorCode the error code to be used if the expression is or
/// consists of a reference to a deferred library
void _reportErrorIfFromDeferredLibrary(
Expression expression, ErrorCode errorCode) {
DeferredLibraryReferenceDetector referenceDetector =
new DeferredLibraryReferenceDetector();
expression.accept(referenceDetector);
if (referenceDetector.result) {
_errorReporter.reportErrorForNode(errorCode, expression);
}
}
/// Report any errors in the given list. Except for special cases, use the
/// given error code rather than the one reported in the error.
///
/// @param errors the errors that need to be reported
/// @param errorCode the error code to be used
void _reportErrors(List<AnalysisError> errors, ErrorCode errorCode) {
int length = errors.length;
for (int i = 0; i < length; i++) {
AnalysisError data = errors[i];
ErrorCode dataErrorCode = data.errorCode;
if (identical(dataErrorCode,
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION) ||
identical(
dataErrorCode, CompileTimeErrorCode.CONST_EVAL_THROWS_IDBZE) ||
identical(dataErrorCode,
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING) ||
identical(dataErrorCode, CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL) ||
identical(
dataErrorCode, CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_INT) ||
identical(dataErrorCode, CompileTimeErrorCode.CONST_EVAL_TYPE_INT) ||
identical(dataErrorCode, CompileTimeErrorCode.CONST_EVAL_TYPE_NUM) ||
identical(dataErrorCode,
CompileTimeErrorCode.RECURSIVE_COMPILE_TIME_CONSTANT) ||
identical(
dataErrorCode,
CheckedModeCompileTimeErrorCode
.CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH) ||
identical(
dataErrorCode,
CheckedModeCompileTimeErrorCode
.CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH) ||
identical(dataErrorCode,
CheckedModeCompileTimeErrorCode.VARIABLE_TYPE_MISMATCH)) {
_errorReporter.reportError(data);
} else if (errorCode != null) {
_errorReporter.reportError(new AnalysisError(
data.source, data.offset, data.length, errorCode));
}
}
}
void _reportNotPotentialConstants(AstNode node) {
var notPotentiallyConstants = getNotPotentiallyConstants(node);
if (notPotentiallyConstants.isEmpty) return;
for (var notConst in notPotentiallyConstants) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode.INVALID_CONSTANT,
notConst,
);
}
}
/// Validates that all arguments in the [argumentList] are potentially
/// constant expressions.
void _reportNotPotentialConstantsArguments(ArgumentList argumentList) {
if (argumentList == null) {
return;
}
for (Expression argument in argumentList.arguments) {
_reportNotPotentialConstants(argument);
}
}
/// Validate that the given expression is a compile time constant. Return the
/// value of the compile time constant, or `null` if the expression is not a
/// compile time constant.
///
/// @param expression the expression to be validated
/// @param errorCode the error code to be used if the expression is not a
/// compile time constant
/// @return the value of the compile time constant
DartObjectImpl _validate(Expression expression, ErrorCode errorCode) {
RecordingErrorListener errorListener = new RecordingErrorListener();
ErrorReporter subErrorReporter =
new ErrorReporter(errorListener, _errorReporter.source);
DartObjectImpl result = expression
.accept(new ConstantVisitor(_evaluationEngine, subErrorReporter));
_reportErrors(errorListener.errors, errorCode);
return result;
}
/// Validate that if the passed arguments are constant expressions.
///
/// @param argumentList the argument list to evaluate
void _validateConstantArguments(ArgumentList argumentList) {
for (Expression argument in argumentList.arguments) {
Expression realArgument =
argument is NamedExpression ? argument.expression : argument;
_validate(
realArgument, CompileTimeErrorCode.CONST_WITH_NON_CONSTANT_ARGUMENT);
}
}
/// Validates that the expressions of the initializers of the given constant
/// [constructor] are all compile time constants.
void _validateConstructorInitializers(ConstructorDeclaration constructor) {
NodeList<ConstructorInitializer> initializers = constructor.initializers;
for (ConstructorInitializer initializer in initializers) {
if (initializer is AssertInitializer) {
_reportNotPotentialConstants(initializer.condition);
Expression message = initializer.message;
if (message != null) {
_reportNotPotentialConstants(message);
}
} else if (initializer is ConstructorFieldInitializer) {
_reportNotPotentialConstants(initializer.expression);
} else if (initializer is RedirectingConstructorInvocation) {
_reportNotPotentialConstantsArguments(initializer.argumentList);
} else if (initializer is SuperConstructorInvocation) {
_reportNotPotentialConstantsArguments(initializer.argumentList);
}
}
}
/// Validate that the default value associated with each of the parameters in
/// the given list is a compile time constant.
///
/// @param parameters the list of parameters to be validated
void _validateDefaultValues(FormalParameterList parameters) {
if (parameters == null) {
return;
}
for (FormalParameter parameter in parameters.parameters) {
if (parameter is DefaultFormalParameter) {
Expression defaultValue = parameter.defaultValue;
DartObjectImpl result;
if (defaultValue == null) {
result =
new DartObjectImpl(_typeProvider.nullType, NullState.NULL_STATE);
} else {
result = _validate(
defaultValue, CompileTimeErrorCode.NON_CONSTANT_DEFAULT_VALUE);
if (result != null) {
_reportErrorIfFromDeferredLibrary(
defaultValue,
CompileTimeErrorCode
.NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY);
}
}
VariableElementImpl element =
parameter.declaredElement as VariableElementImpl;
element.evaluationResult = new EvaluationResultImpl(result);
}
}
}
/// Validates that the expressions of any field initializers in the class
/// declaration are all compile time constants. Since this is only required if
/// the class has a constant constructor, the error is reported at the
/// constructor site.
///
/// @param classDeclaration the class which should be validated
/// @param errorSite the site at which errors should be reported.
void _validateFieldInitializers(ClassOrMixinDeclaration classDeclaration,
ConstructorDeclaration errorSite) {
NodeList<ClassMember> members = classDeclaration.members;
for (ClassMember member in members) {
if (member is FieldDeclaration && !member.isStatic) {
for (VariableDeclaration variableDeclaration
in member.fields.variables) {
Expression initializer = variableDeclaration.initializer;
if (initializer != null) {
// Ignore any errors produced during validation--if the constant
// can't be evaluated we'll just report a single error.
AnalysisErrorListener errorListener =
AnalysisErrorListener.NULL_LISTENER;
ErrorReporter subErrorReporter =
new ErrorReporter(errorListener, _errorReporter.source);
DartObjectImpl result = initializer.accept(
new ConstantVisitor(_evaluationEngine, subErrorReporter));
if (result == null) {
_errorReporter.reportErrorForNode(
CompileTimeErrorCode
.CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST,
errorSite,
[variableDeclaration.name.name]);
}
}
}
}
}
}
}
class _ConstLiteralVerifier {
final ConstantVerifier verifier;
final Map<DartObject, Expression> mapUniqueKeys;
final Map<Expression, Expression> mapDuplicateKeyExpressions;
final ErrorCode errorCode;
final DartType listElementType;
final DartType mapKeyType;
final DartType mapValueType;
final DartType setElementType;
final Map<DartObject, Expression> setUniqueValues;
final Map<Expression, Expression> setDuplicateExpressions;
final bool forList;
final bool forMap;
final bool forSet;
_ConstLiteralVerifier(
this.verifier, {
this.mapUniqueKeys,
this.mapDuplicateKeyExpressions,
this.errorCode,
this.listElementType,
this.mapKeyType,
this.mapValueType,
this.setElementType,
this.setUniqueValues,
this.setDuplicateExpressions,
this.forList = false,
this.forMap = false,
this.forSet = false,
});
ErrorCode get _fromDeferredErrorCode {
if (forList) {
return CompileTimeErrorCode
.NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY;
} else if (forSet) {
return CompileTimeErrorCode.SET_ELEMENT_FROM_DEFERRED_LIBRARY;
}
return null;
}
bool verify(CollectionElement element) {
if (element is Expression) {
var value = verifier._validate(element, errorCode);
if (value == null) return false;
if (_fromDeferredErrorCode != null) {
verifier._reportErrorIfFromDeferredLibrary(
element, _fromDeferredErrorCode);
}
if (forList) {
return _validateListExpression(element, value);
}
if (forSet) {
return _validateSetExpression(element, value);
}
return true;
} else if (element is ForElement) {
verifier._errorReporter.reportErrorForNode(errorCode, element);
return false;
} else if (element is IfElement) {
if (!verifier._constantUpdate2018Enabled) {
verifier._errorReporter.reportErrorForNode(errorCode, element);
return false;
}
var conditionValue = verifier._validate(element.condition, errorCode);
var conditionBool = conditionValue?.toBoolValue();
// The errors have already been reported.
if (conditionBool == null) return false;
verifier._reportErrorIfFromDeferredLibrary(element.condition,
CompileTimeErrorCode.IF_ELEMENT_CONDITION_FROM_DEFERRED_LIBRARY);
var thenValid = true;
var elseValid = true;
if (conditionBool) {
thenValid = verify(element.thenElement);
if (element.elseElement != null) {
elseValid = _reportNotPotentialConstants(element.elseElement);
}
} else {
thenValid = _reportNotPotentialConstants(element.thenElement);
if (element.elseElement != null) {
elseValid = verify(element.elseElement);
}
}
return thenValid && elseValid;
} else if (element is MapLiteralEntry) {
return _validateMapLiteralEntry(element);
} else if (element is SpreadElement) {
if (!verifier._constantUpdate2018Enabled) {
verifier._errorReporter.reportErrorForNode(errorCode, element);
return false;
}
var value = verifier._validate(element.expression, errorCode);
if (value == null) return false;
verifier._reportErrorIfFromDeferredLibrary(element.expression,
CompileTimeErrorCode.SPREAD_EXPRESSION_FROM_DEFERRED_LIBRARY);
if (forList || forSet) {
return _validateListOrSetSpread(element, value);
}
if (forMap) {
return _validateMapSpread(element, value);
}
return true;
}
throw new UnsupportedError(
'Unhandled type of collection element: ${element.runtimeType}',
);
}
/// Return `true` if the [node] is a potential constant.
bool _reportNotPotentialConstants(AstNode node) {
var notPotentiallyConstants = getNotPotentiallyConstants(node);
if (notPotentiallyConstants.isEmpty) return true;
for (var notConst in notPotentiallyConstants) {
CompileTimeErrorCode errorCode;
if (forList) {
errorCode = CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT;
} else if (forMap) {
errorCode = CompileTimeErrorCode.NON_CONSTANT_MAP_ELEMENT;
for (var parent = notConst; parent != null; parent = parent.parent) {
if (parent is MapLiteralEntry) {
if (parent.key == notConst) {
errorCode = CompileTimeErrorCode.NON_CONSTANT_MAP_KEY;
} else {
errorCode = CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE;
}
break;
}
}
} else if (forSet) {
errorCode = CompileTimeErrorCode.NON_CONSTANT_SET_ELEMENT;
}
verifier._errorReporter.reportErrorForNode(errorCode, notConst);
}
return false;
}
bool _validateListExpression(Expression expression, DartObjectImpl value) {
if (!verifier._evaluationEngine.runtimeTypeMatch(value, listElementType)) {
verifier._errorReporter.reportErrorForNode(
StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,
expression,
[value.type, listElementType],
);
return false;
}
verifier._reportErrorIfFromDeferredLibrary(
expression,
CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY,
);
return true;
}
bool _validateListOrSetSpread(SpreadElement element, DartObjectImpl value) {
var listValue = value.toListValue();
var setValue = value.toSetValue();
if (listValue == null && setValue == null) {
if (value.isNull && _isNullableSpread(element)) {
return true;
}
verifier._errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_SPREAD_EXPECTED_LIST_OR_SET,
element.expression,
);
return false;
}
if (listValue != null) {
var elementType = value.type.typeArguments[0];
if (verifier._implementsEqualsWhenNotAllowed(elementType)) {
verifier._errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_SET_ELEMENT_TYPE_IMPLEMENTS_EQUALS,
element,
[elementType],
);
return false;
}
}
if (forSet) {
var iterableValue = listValue ?? setValue;
for (var item in iterableValue) {
Expression expression = element.expression;
if (setUniqueValues.containsKey(item)) {
setDuplicateExpressions[expression] = setUniqueValues[item];
} else {
setUniqueValues[item] = expression;
}
}
}
return true;
}
bool _validateMapLiteralEntry(MapLiteralEntry entry) {
if (!forMap) return false;
var keyExpression = entry.key;
var valueExpression = entry.value;
var keyValue = verifier._validate(
keyExpression,
CompileTimeErrorCode.NON_CONSTANT_MAP_KEY,
);
var valueValue = verifier._validate(
valueExpression,
CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE,
);
if (keyValue != null) {
var keyType = keyValue.type;
if (!verifier._evaluationEngine.runtimeTypeMatch(keyValue, mapKeyType)) {
verifier._errorReporter.reportErrorForNode(
StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE,
keyExpression,
[keyType, mapKeyType],
);
}
if (verifier._implementsEqualsWhenNotAllowed(keyType)) {
verifier._errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
keyExpression,
[keyType],
);
}
verifier._reportErrorIfFromDeferredLibrary(
keyExpression,
CompileTimeErrorCode.NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY,
);
if (mapUniqueKeys.containsKey(keyValue)) {
mapDuplicateKeyExpressions[keyExpression] = mapUniqueKeys[keyValue];
} else {
mapUniqueKeys[keyValue] = keyExpression;
}
}
if (valueValue != null) {
if (!verifier._evaluationEngine
.runtimeTypeMatch(valueValue, mapValueType)) {
verifier._errorReporter.reportErrorForNode(
StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE,
valueExpression,
[valueValue.type, mapValueType],
);
}
verifier._reportErrorIfFromDeferredLibrary(
valueExpression,
CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY,
);
}
return true;
}
bool _validateMapSpread(SpreadElement element, DartObjectImpl value) {
if (value.isNull && _isNullableSpread(element)) {
return true;
}
Map<DartObject, DartObject> map = value.toMapValue();
if (map != null) {
// TODO(brianwilkerson) Figure out how to improve the error messages. They
// currently point to the whole spread expression, but the key and/or
// value being referenced might not be located there (if it's referenced
// through a const variable).
for (var entry in map.entries) {
DartObjectImpl keyValue = entry.key;
if (keyValue != null) {
if (mapUniqueKeys.containsKey(keyValue)) {
mapDuplicateKeyExpressions[element.expression] =
mapUniqueKeys[keyValue];
} else {
mapUniqueKeys[keyValue] = element.expression;
}
}
}
return true;
}
verifier._errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_SPREAD_EXPECTED_MAP,
element.expression,
);
return false;
}
bool _validateSetExpression(Expression expression, DartObjectImpl value) {
if (!verifier._evaluationEngine.runtimeTypeMatch(value, setElementType)) {
verifier._errorReporter.reportErrorForNode(
StaticWarningCode.SET_ELEMENT_TYPE_NOT_ASSIGNABLE,
expression,
[value.type, setElementType],
);
return false;
}
if (verifier._implementsEqualsWhenNotAllowed(value.type)) {
verifier._errorReporter.reportErrorForNode(
CompileTimeErrorCode.CONST_SET_ELEMENT_TYPE_IMPLEMENTS_EQUALS,
expression,
[value.type],
);
return false;
}
verifier._reportErrorIfFromDeferredLibrary(
expression,
CompileTimeErrorCode.SET_ELEMENT_FROM_DEFERRED_LIBRARY,
);
if (setUniqueValues.containsKey(value)) {
setDuplicateExpressions[expression] = setUniqueValues[value];
} else {
setUniqueValues[value] = expression;
}
return true;
}
static bool _isNullableSpread(SpreadElement element) {
return element.spreadOperator.type ==
TokenType.PERIOD_PERIOD_PERIOD_QUESTION;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/constant/utilities.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/constant/evaluation.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/handle.dart'
show ConstructorElementHandle;
import 'package:analyzer/src/dart/element/member.dart';
ConstructorElementImpl getConstructorImpl(ConstructorElement constructor) {
while (constructor is ConstructorMember) {
constructor = (constructor as ConstructorMember).baseElement;
}
if (constructor is ConstructorElementHandle) {
constructor = (constructor as ConstructorElementHandle).actualElement;
}
return constructor;
}
/// Callback used by [ReferenceFinder] to report that a dependency was found.
typedef void ReferenceFinderCallback(ConstantEvaluationTarget dependency);
/// An [AstCloner] that copies the necessary information from the AST to allow
/// constants to be evaluated.
class ConstantAstCloner extends AstCloner {
ConstantAstCloner() : super(true);
@override
Annotation visitAnnotation(Annotation node) {
Annotation annotation = super.visitAnnotation(node);
annotation.element = node.element;
return annotation;
}
@override
ConstructorName visitConstructorName(ConstructorName node) {
ConstructorName name = super.visitConstructorName(node);
name.staticElement = node.staticElement;
return name;
}
@override
FunctionExpression visitFunctionExpression(FunctionExpression node) {
FunctionExpressionImpl expression = super.visitFunctionExpression(node);
expression.declaredElement = node.declaredElement;
return expression;
}
@override
InstanceCreationExpression visitInstanceCreationExpression(
InstanceCreationExpression node) {
InstanceCreationExpression expression =
super.visitInstanceCreationExpression(node);
if (node.keyword == null) {
if (node.isConst) {
expression.keyword = new KeywordToken(Keyword.CONST, node.offset);
} else {
expression.keyword = new KeywordToken(Keyword.NEW, node.offset);
}
}
expression.staticElement = node.staticElement;
return expression;
}
@override
IntegerLiteral visitIntegerLiteral(IntegerLiteral node) {
IntegerLiteral integer = super.visitIntegerLiteral(node);
integer.staticType = node.staticType;
return integer;
}
@override
ListLiteral visitListLiteral(ListLiteral node) {
ListLiteral literal = super.visitListLiteral(node);
literal.staticType = node.staticType;
if (node.constKeyword == null && node.isConst) {
literal.constKeyword = new KeywordToken(Keyword.CONST, node.offset);
}
return literal;
}
@override
PrefixedIdentifier visitPrefixedIdentifier(PrefixedIdentifier node) {
PrefixedIdentifierImpl copy = super.visitPrefixedIdentifier(node);
copy.staticType = node.staticType;
return copy;
}
@override
PropertyAccess visitPropertyAccess(PropertyAccess node) {
PropertyAccessImpl copy = super.visitPropertyAccess(node);
copy.staticType = node.staticType;
return copy;
}
@override
RedirectingConstructorInvocation visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
RedirectingConstructorInvocation invocation =
super.visitRedirectingConstructorInvocation(node);
invocation.staticElement = node.staticElement;
return invocation;
}
@override
SetOrMapLiteral visitSetOrMapLiteral(SetOrMapLiteral node) {
SetOrMapLiteral literal = super.visitSetOrMapLiteral(node);
literal.staticType = node.staticType;
if (node.constKeyword == null && node.isConst) {
literal.constKeyword = new KeywordToken(Keyword.CONST, node.offset);
}
return literal;
}
@override
SimpleIdentifier visitSimpleIdentifier(SimpleIdentifier node) {
SimpleIdentifierImpl copy = super.visitSimpleIdentifier(node);
copy.staticElement = node.staticElement;
copy.staticType = node.staticType;
copy.tearOffTypeArgumentTypes = node.tearOffTypeArgumentTypes;
return copy;
}
@override
SuperConstructorInvocation visitSuperConstructorInvocation(
SuperConstructorInvocation node) {
SuperConstructorInvocation invocation =
super.visitSuperConstructorInvocation(node);
invocation.staticElement = node.staticElement;
return invocation;
}
@override
TypeName visitTypeName(TypeName node) {
TypeName typeName = super.visitTypeName(node);
typeName.type = node.type;
return typeName;
}
}
/// A visitor used to traverse the AST structures of all of the compilation
/// units being resolved and build the full set of dependencies for all constant
/// expressions.
class ConstantExpressionsDependenciesFinder extends RecursiveAstVisitor {
/// The constants whose values need to be computed.
HashSet<ConstantEvaluationTarget> dependencies =
new HashSet<ConstantEvaluationTarget>();
@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
if (node.isConst) {
_find(node);
} else {
super.visitInstanceCreationExpression(node);
}
}
@override
void visitListLiteral(ListLiteral node) {
if (node.isConst) {
_find(node);
} else {
super.visitListLiteral(node);
}
}
@override
void visitSetOrMapLiteral(SetOrMapLiteral node) {
if (node.isConst) {
_find(node);
} else {
if (node.isMap) {
// Values of keys are computed to check that they are unique.
for (var entry in node.elements) {
// TODO(mfairhurst): How do if/for loops/spreads affect this?
_find(entry);
}
} else if (node.isSet) {
// values of sets are computed to check that they are unique.
for (var entry in node.elements) {
_find(entry);
}
}
super.visitSetOrMapLiteral(node);
}
}
@override
void visitSwitchCase(SwitchCase node) {
_find(node.expression);
node.statements.accept(this);
}
/// Add dependencies of a [CollectionElement] or [Expression] (which is a type
/// of [CollectionElement]).
void _find(CollectionElement node) {
if (node != null) {
ReferenceFinder referenceFinder = new ReferenceFinder(dependencies.add);
node.accept(referenceFinder);
}
}
}
/// A visitor used to traverse the AST structures of all of the compilation
/// units being resolved and build tables of the constant variables, constant
/// constructors, constant constructor invocations, and annotations found in
/// those compilation units.
class ConstantFinder extends RecursiveAstVisitor<void> {
/// The elements and AST nodes whose constant values need to be computed.
List<ConstantEvaluationTarget> constantsToCompute =
<ConstantEvaluationTarget>[];
/// A flag indicating whether instance variables marked as "final" should be
/// treated as "const".
bool treatFinalInstanceVarAsConst = false;
@override
void visitAnnotation(Annotation node) {
super.visitAnnotation(node);
ElementAnnotation elementAnnotation = node.elementAnnotation;
if (elementAnnotation == null) {
// Analyzer ignores annotations on "part of" directives and on enum
// constant declarations.
assert(node.parent is PartOfDirective ||
node.parent is EnumConstantDeclaration);
} else {
constantsToCompute.add(elementAnnotation);
}
}
@override
void visitClassDeclaration(ClassDeclaration node) {
bool prevTreatFinalInstanceVarAsConst = treatFinalInstanceVarAsConst;
if (node.declaredElement.constructors
.any((ConstructorElement e) => e.isConst)) {
// Instance vars marked "final" need to be included in the dependency
// graph, since constant constructors implicitly use the values in their
// initializers.
treatFinalInstanceVarAsConst = true;
}
try {
super.visitClassDeclaration(node);
} finally {
treatFinalInstanceVarAsConst = prevTreatFinalInstanceVarAsConst;
}
}
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
super.visitConstructorDeclaration(node);
if (node.constKeyword != null) {
ConstructorElement element = node.declaredElement;
if (element != null) {
constantsToCompute.add(element);
constantsToCompute.addAll(element.parameters);
}
}
}
@override
void visitDefaultFormalParameter(DefaultFormalParameter node) {
super.visitDefaultFormalParameter(node);
Expression defaultValue = node.defaultValue;
if (defaultValue != null && node.declaredElement != null) {
constantsToCompute.add(node.declaredElement);
}
}
@override
void visitVariableDeclaration(VariableDeclaration node) {
super.visitVariableDeclaration(node);
Expression initializer = node.initializer;
VariableElement element = node.declaredElement;
if (initializer != null &&
(node.isConst ||
treatFinalInstanceVarAsConst &&
element is FieldElement &&
node.isFinal &&
!element.isStatic)) {
if (element != null) {
constantsToCompute.add(element);
}
}
}
}
/// An object used to add reference information for a given variable to the
/// bi-directional mapping used to order the evaluation of constants.
class ReferenceFinder extends RecursiveAstVisitor<void> {
/// The callback which should be used to report any dependencies that were
/// found.
final ReferenceFinderCallback _callback;
/// Initialize a newly created reference finder to find references from a
/// given variable to other variables and to add those references to the given
/// graph. The [_callback] will be invoked for every dependency found.
ReferenceFinder(this._callback);
@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
if (node.isConst) {
ConstructorElement constructor = getConstructorImpl(node.staticElement);
if (constructor != null) {
_callback(constructor);
}
}
super.visitInstanceCreationExpression(node);
}
@override
void visitLabel(Label node) {
// We are visiting the "label" part of a named expression in a function
// call (presumably a constructor call), e.g. "const C(label: ...)". We
// don't want to visit the SimpleIdentifier for the label because that's a
// reference to a function parameter that needs to be filled in; it's not a
// constant whose value we depend on.
}
@override
void visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
super.visitRedirectingConstructorInvocation(node);
ConstructorElement target = getConstructorImpl(node.staticElement);
if (target != null) {
_callback(target);
}
}
@override
void visitSimpleIdentifier(SimpleIdentifier node) {
Element staticElement = node.staticElement;
Element element = staticElement is PropertyAccessorElement
? staticElement.variable
: staticElement;
if (element is VariableElement && element.isConst) {
_callback(element);
}
}
@override
void visitSuperConstructorInvocation(SuperConstructorInvocation node) {
super.visitSuperConstructorInvocation(node);
ConstructorElement constructor = getConstructorImpl(node.staticElement);
if (constructor != null) {
_callback(constructor);
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/constant/value.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.
/// The implementation of the class [DartObject].
import 'dart:collection';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/type_system.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
/// The state of an object representing a boolean value.
class BoolState extends InstanceState {
/// An instance representing the boolean value 'false'.
static BoolState FALSE_STATE = new BoolState(false);
/// An instance representing the boolean value 'true'.
static BoolState TRUE_STATE = new BoolState(true);
/// A state that can be used to represent a boolean whose value is not known.
static BoolState UNKNOWN_VALUE = new BoolState(null);
/// The value of this instance.
final bool value;
/// Initialize a newly created state to represent the given [value].
BoolState(this.value);
@override
int get hashCode => value == null ? 0 : (value ? 2 : 3);
@override
bool get isBool => true;
@override
bool get isBoolNumStringOrNull => true;
@override
bool get isUnknown => value == null;
@override
String get typeName => "bool";
@override
bool operator ==(Object object) =>
object is BoolState && identical(value, object.value);
@override
BoolState convertToBool() => this;
@override
StringState convertToString() {
if (value == null) {
return StringState.UNKNOWN_VALUE;
}
return new StringState(value ? "true" : "false");
}
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is BoolState) {
bool rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return BoolState.from(identical(value, rightValue));
}
return FALSE_STATE;
}
@override
BoolState lazyAnd(InstanceState rightOperandComputer()) {
if (value == false) {
return FALSE_STATE;
}
InstanceState rightOperand = rightOperandComputer();
assertBool(rightOperand);
return value == null ? UNKNOWN_VALUE : rightOperand.convertToBool();
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
BoolState lazyOr(InstanceState rightOperandComputer()) {
if (value == true) {
return TRUE_STATE;
}
InstanceState rightOperand = rightOperandComputer();
assertBool(rightOperand);
return value == null ? UNKNOWN_VALUE : rightOperand.convertToBool();
}
@override
BoolState logicalNot() {
if (value == null) {
return UNKNOWN_VALUE;
}
return value ? FALSE_STATE : TRUE_STATE;
}
@override
String toString() => value == null ? "-unknown-" : (value ? "true" : "false");
/// Return the boolean state representing the given boolean [value].
static BoolState from(bool value) =>
value ? BoolState.TRUE_STATE : BoolState.FALSE_STATE;
}
/// Information about a const constructor invocation.
class ConstructorInvocation {
/// The constructor that was called.
final ConstructorElement constructor;
/// Values of specified arguments, actual values for positional, and `null`
/// for named (which are provided as [namedArguments]).
final List<DartObjectImpl> _argumentValues;
/// The named arguments passed to the constructor.
final Map<String, DartObjectImpl> namedArguments;
ConstructorInvocation(
this.constructor, this._argumentValues, this.namedArguments);
/// The positional arguments passed to the constructor.
List<DartObjectImpl> get positionalArguments {
return _argumentValues.takeWhile((v) => v != null).toList();
}
}
/// A representation of an instance of a Dart class.
class DartObjectImpl implements DartObject {
/// When `true`, `operator==` only compares constant values, ignoring types.
///
/// This is a temporary hack to work around dartbug.com/35908.
// TODO(paulberry): when #35908 is fixed, remove this hack.
static bool _ignoreTypesInEqualityComparison = false;
@override
final ParameterizedType type;
/// The state of the object.
final InstanceState _state;
/// Initialize a newly created object to have the given [type] and [_state].
DartObjectImpl(this.type, this._state);
/// Create an object to represent an unknown value.
factory DartObjectImpl.validWithUnknownValue(ParameterizedType type) {
if (type.element.library.isDartCore) {
String typeName = type.name;
if (typeName == "bool") {
return new DartObjectImpl(type, BoolState.UNKNOWN_VALUE);
} else if (typeName == "double") {
return new DartObjectImpl(type, DoubleState.UNKNOWN_VALUE);
} else if (typeName == "int") {
return new DartObjectImpl(type, IntState.UNKNOWN_VALUE);
} else if (typeName == "String") {
return new DartObjectImpl(type, StringState.UNKNOWN_VALUE);
}
}
return new DartObjectImpl(type, GenericState.UNKNOWN_VALUE);
}
Map<String, DartObjectImpl> get fields => _state.fields;
@override
int get hashCode => JenkinsSmiHash.hash2(type.hashCode, _state.hashCode);
@override
bool get hasKnownValue => !_state.isUnknown;
/// Return `true` if this object represents an object whose type is 'bool'.
bool get isBool => _state.isBool;
/// Return `true` if this object represents an object whose type is either
/// 'bool', 'num', 'String', or 'Null'.
bool get isBoolNumStringOrNull => _state.isBoolNumStringOrNull;
/// Return `true` if this object represents an object whose type is 'int'.
bool get isInt => _state.isInt;
@override
bool get isNull => _state is NullState;
/// Return `true` if this object represents an unknown value.
bool get isUnknown => _state.isUnknown;
/// Return `true` if this object represents an instance of a user-defined
/// class.
bool get isUserDefinedObject => _state is GenericState;
@override
bool operator ==(Object object) {
if (object is DartObjectImpl) {
return (_ignoreTypesInEqualityComparison || type == object.type) &&
_state == object._state;
}
return false;
}
/// Return the result of invoking the '+' operator on this object with the
/// given [rightOperand]. The [typeProvider] is the type provider used to find
/// known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl add(TypeProvider typeProvider, DartObjectImpl rightOperand) {
InstanceState result = _state.add(rightOperand._state);
if (result is IntState) {
return new DartObjectImpl(typeProvider.intType, result);
} else if (result is DoubleState) {
return new DartObjectImpl(typeProvider.doubleType, result);
} else if (result is StringState) {
return new DartObjectImpl(typeProvider.stringType, result);
}
// We should never get here.
throw new StateError("add returned a ${result.runtimeType}");
}
/// Return the result of invoking the '~' operator on this object. The
/// [typeProvider] is the type provider used to find known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl bitNot(TypeProvider typeProvider) =>
new DartObjectImpl(typeProvider.intType, _state.bitNot());
/// Return the result of casting this object to the given [castType].
DartObjectImpl castToType(TypeProvider typeProvider, TypeSystem typeSystem,
DartObjectImpl castType) {
_assertType(castType);
if (isNull) {
return this;
}
if (!typeSystem.isSubtypeOf(type, (castType._state as TypeState)._type)) {
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
return this;
}
/// Return the result of invoking the ' ' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl concatenate(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(
typeProvider.stringType, _state.concatenate(rightOperand._state));
/// Return the result of applying boolean conversion to this object. The
/// [typeProvider] is the type provider used to find known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl convertToBool(TypeProvider typeProvider) {
InterfaceType boolType = typeProvider.boolType;
if (identical(type, boolType)) {
return this;
}
return new DartObjectImpl(boolType, _state.convertToBool());
}
/// Return the result of invoking the '/' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for
/// an object of this kind.
DartObjectImpl divide(
TypeProvider typeProvider, DartObjectImpl rightOperand) {
InstanceState result = _state.divide(rightOperand._state);
if (result is IntState) {
return new DartObjectImpl(typeProvider.intType, result);
} else if (result is DoubleState) {
return new DartObjectImpl(typeProvider.doubleType, result);
}
// We should never get here.
throw new StateError("divide returned a ${result.runtimeType}");
}
/// Return the result of invoking the '&' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl eagerAnd(
TypeProvider typeProvider, DartObjectImpl rightOperand, bool allowBool) {
if (allowBool && isBool && rightOperand.isBool) {
return new DartObjectImpl(
typeProvider.boolType, _state.logicalAnd(rightOperand._state));
} else if (isInt && rightOperand.isInt) {
return new DartObjectImpl(
typeProvider.intType, _state.bitAnd(rightOperand._state));
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_INT);
}
/// Return the result of invoking the '|' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl eagerOr(
TypeProvider typeProvider, DartObjectImpl rightOperand, bool allowBool) {
if (allowBool && isBool && rightOperand.isBool) {
return new DartObjectImpl(
typeProvider.boolType, _state.logicalOr(rightOperand._state));
} else if (isInt && rightOperand.isInt) {
return new DartObjectImpl(
typeProvider.intType, _state.bitOr(rightOperand._state));
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_INT);
}
/// Return the result of invoking the '^' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl eagerXor(
TypeProvider typeProvider, DartObjectImpl rightOperand, bool allowBool) {
if (allowBool && isBool && rightOperand.isBool) {
return new DartObjectImpl(
typeProvider.boolType, _state.logicalXor(rightOperand._state));
} else if (isInt && rightOperand.isInt) {
return new DartObjectImpl(
typeProvider.intType, _state.bitXor(rightOperand._state));
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_INT);
}
/// Return the result of invoking the '==' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl equalEqual(
TypeProvider typeProvider, DartObjectImpl rightOperand) {
if (isNull || rightOperand.isNull) {
return new DartObjectImpl(
typeProvider.boolType,
isNull && rightOperand.isNull
? BoolState.TRUE_STATE
: BoolState.FALSE_STATE);
}
if (isBoolNumStringOrNull) {
return new DartObjectImpl(
typeProvider.boolType, _state.equalEqual(rightOperand._state));
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING);
}
@override
DartObject getField(String name) {
InstanceState state = _state;
if (state is GenericState) {
return state.fields[name];
}
return null;
}
/// Gets the constructor that was called to create this value, if this is a
/// const constructor invocation. Otherwise returns null.
ConstructorInvocation getInvocation() {
InstanceState state = _state;
if (state is GenericState) {
return state.invocation;
}
return null;
}
/// Return the result of invoking the '>' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl greaterThan(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(
typeProvider.boolType, _state.greaterThan(rightOperand._state));
/// Return the result of invoking the '>=' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl greaterThanOrEqual(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(typeProvider.boolType,
_state.greaterThanOrEqual(rightOperand._state));
/// Return the result of testing whether this object has the given
/// [testedType].
DartObjectImpl hasType(TypeProvider typeProvider, TypeSystem typeSystem,
DartObjectImpl testedType) {
_assertType(testedType);
DartType typeType = (testedType._state as TypeState)._type;
BoolState state;
if (isNull) {
if (typeType == typeProvider.objectType ||
typeType == typeProvider.dynamicType ||
typeType == typeProvider.nullType) {
state = BoolState.TRUE_STATE;
} else {
state = BoolState.FALSE_STATE;
}
} else {
state = BoolState.from(typeSystem.isSubtypeOf(type, typeType));
}
return new DartObjectImpl(typeProvider.boolType, state);
}
/// Return the result of invoking the '~/' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl integerDivide(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(
typeProvider.intType, _state.integerDivide(rightOperand._state));
/// Indicates whether `this` is equal to [other], ignoring types both in this
/// object and sub-objects.
///
/// This is a temporary hack to work around dartbug.com/35908.
// TODO(paulberry): when #35908 is fixed, remove this hack.
bool isEqualIgnoringTypesRecursively(Object other) {
bool oldIgnoreTypesInEqualityComparison = _ignoreTypesInEqualityComparison;
_ignoreTypesInEqualityComparison = true;
try {
return this == other;
} finally {
_ignoreTypesInEqualityComparison = oldIgnoreTypesInEqualityComparison;
}
}
/// Return the result of invoking the identical function on this object with
/// the [rightOperand]. The [typeProvider] is the type provider used to find
/// known types.
DartObjectImpl isIdentical(
TypeProvider typeProvider, DartObjectImpl rightOperand) {
return new DartObjectImpl(
typeProvider.boolType, _state.isIdentical(rightOperand._state));
}
/// Return the result of invoking the '&&' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl lazyAnd(
TypeProvider typeProvider, DartObjectImpl rightOperandComputer()) =>
new DartObjectImpl(typeProvider.boolType,
_state.lazyAnd(() => rightOperandComputer()?._state));
/// Return the result of invoking the '==' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl lazyEqualEqual(
TypeProvider typeProvider, DartObjectImpl rightOperand) {
if (isNull || rightOperand.isNull) {
return new DartObjectImpl(
typeProvider.boolType,
isNull && rightOperand.isNull
? BoolState.TRUE_STATE
: BoolState.FALSE_STATE);
}
if (isBoolNumStringOrNull) {
return new DartObjectImpl(
typeProvider.boolType, _state.lazyEqualEqual(rightOperand._state));
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING);
}
/// Return the result of invoking the '||' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl lazyOr(
TypeProvider typeProvider, DartObjectImpl rightOperandComputer()) =>
new DartObjectImpl(typeProvider.boolType,
_state.lazyOr(() => rightOperandComputer()?._state));
/// Return the result of invoking the '<' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl lessThan(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(
typeProvider.boolType, _state.lessThan(rightOperand._state));
/// Return the result of invoking the '<=' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl lessThanOrEqual(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(
typeProvider.boolType, _state.lessThanOrEqual(rightOperand._state));
/// Return the result of invoking the '!' operator on this object. The
/// [typeProvider] is the type provider used to find known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl logicalNot(TypeProvider typeProvider) =>
new DartObjectImpl(typeProvider.boolType, _state.logicalNot());
/// Return the result of invoking the '>>>' operator on this object
/// with the [rightOperand]. The [typeProvider] is the type provider used to
/// find known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl logicalShiftRight(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(
typeProvider.intType, _state.logicalShiftRight(rightOperand._state));
/// Return the result of invoking the '-' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl minus(TypeProvider typeProvider, DartObjectImpl rightOperand) {
InstanceState result = _state.minus(rightOperand._state);
if (result is IntState) {
return new DartObjectImpl(typeProvider.intType, result);
} else if (result is DoubleState) {
return new DartObjectImpl(typeProvider.doubleType, result);
}
// We should never get here.
throw new StateError("minus returned a ${result.runtimeType}");
}
/// Return the result of invoking the '-' operator on this object. The
/// [typeProvider] is the type provider used to find known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl negated(TypeProvider typeProvider) {
InstanceState result = _state.negated();
if (result is IntState) {
return new DartObjectImpl(typeProvider.intType, result);
} else if (result is DoubleState) {
return new DartObjectImpl(typeProvider.doubleType, result);
}
// We should never get here.
throw new StateError("negated returned a ${result.runtimeType}");
}
/// Return the result of invoking the '!=' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl notEqual(
TypeProvider typeProvider, DartObjectImpl rightOperand) {
return equalEqual(typeProvider, rightOperand).logicalNot(typeProvider);
}
/// Return the result of converting this object to a 'String'. The
/// [typeProvider] is the type provider used to find known types.
///
/// Throws an [EvaluationException] if the object cannot be converted to a
/// 'String'.
DartObjectImpl performToString(TypeProvider typeProvider) {
InterfaceType stringType = typeProvider.stringType;
if (identical(type, stringType)) {
return this;
}
return new DartObjectImpl(stringType, _state.convertToString());
}
/// Return the result of invoking the '%' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl remainder(
TypeProvider typeProvider, DartObjectImpl rightOperand) {
InstanceState result = _state.remainder(rightOperand._state);
if (result is IntState) {
return new DartObjectImpl(typeProvider.intType, result);
} else if (result is DoubleState) {
return new DartObjectImpl(typeProvider.doubleType, result);
}
// We should never get here.
throw new StateError("remainder returned a ${result.runtimeType}");
}
/// Return the result of invoking the '<<' operator on this object with
/// the [rightOperand]. The [typeProvider] is the type provider used to find
/// known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl shiftLeft(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(
typeProvider.intType, _state.shiftLeft(rightOperand._state));
/// Return the result of invoking the '>>' operator on this object with
/// the [rightOperand]. The [typeProvider] is the type provider used to find
/// known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl shiftRight(
TypeProvider typeProvider, DartObjectImpl rightOperand) =>
new DartObjectImpl(
typeProvider.intType, _state.shiftRight(rightOperand._state));
/// Return the result of invoking the 'length' getter on this object. The
/// [typeProvider] is the type provider used to find known types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl stringLength(TypeProvider typeProvider) =>
new DartObjectImpl(typeProvider.intType, _state.stringLength());
/// Return the result of invoking the '*' operator on this object with the
/// [rightOperand]. The [typeProvider] is the type provider used to find known
/// types.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
DartObjectImpl times(TypeProvider typeProvider, DartObjectImpl rightOperand) {
InstanceState result = _state.times(rightOperand._state);
if (result is IntState) {
return new DartObjectImpl(typeProvider.intType, result);
} else if (result is DoubleState) {
return new DartObjectImpl(typeProvider.doubleType, result);
}
// We should never get here.
throw new StateError("times returned a ${result.runtimeType}");
}
@override
bool toBoolValue() {
InstanceState state = _state;
if (state is BoolState) {
return state.value;
}
return null;
}
@override
double toDoubleValue() {
InstanceState state = _state;
if (state is DoubleState) {
return state.value;
}
return null;
}
@override
ExecutableElement toFunctionValue() {
InstanceState state = _state;
return state is FunctionState ? state._element : null;
}
@override
int toIntValue() {
InstanceState state = _state;
if (state is IntState) {
return state.value;
}
return null;
}
@override
List<DartObject> toListValue() {
InstanceState state = _state;
if (state is ListState) {
return state._elements;
}
return null;
}
@override
Map<DartObject, DartObject> toMapValue() {
InstanceState state = _state;
if (state is MapState) {
return state._entries;
}
return null;
}
@override
Set<DartObject> toSetValue() {
InstanceState state = _state;
if (state is SetState) {
return state._elements;
}
return null;
}
@override
String toString() => "${type.displayName} ($_state)";
@override
String toStringValue() {
InstanceState state = _state;
if (state is StringState) {
return state.value;
}
return null;
}
@override
String toSymbolValue() {
InstanceState state = _state;
if (state is SymbolState) {
return state.value;
}
return null;
}
@override
DartType toTypeValue() {
InstanceState state = _state;
if (state is TypeState) {
return state._type;
}
return null;
}
/// Throw an exception if the given [object]'s state does not represent a Type
/// value.
void _assertType(DartObjectImpl object) {
if (object._state is! TypeState) {
throw new EvaluationException(CompileTimeErrorCode.CONST_EVAL_TYPE_TYPE);
}
}
}
/// The state of an object representing a double.
class DoubleState extends NumState {
/// A state that can be used to represent a double whose value is not known.
static DoubleState UNKNOWN_VALUE = new DoubleState(null);
/// The value of this instance.
final double value;
/// Initialize a newly created state to represent a double with the given
/// [value].
DoubleState(this.value);
@override
int get hashCode => value == null ? 0 : value.hashCode;
@override
bool get isUnknown => value == null;
@override
String get typeName => "double";
@override
bool operator ==(Object object) =>
object is DoubleState && (value == object.value);
@override
NumState add(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value + rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value + rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
StringState convertToString() {
if (value == null) {
return StringState.UNKNOWN_VALUE;
}
return new StringState(value.toString());
}
@override
NumState divide(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value / rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value / rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
BoolState greaterThan(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value > rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value > rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
BoolState greaterThanOrEqual(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value >= rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value >= rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
IntState integerDivide(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return IntState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return IntState.UNKNOWN_VALUE;
}
double result = value / rightValue.toDouble();
return new IntState(result.toInt());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return IntState.UNKNOWN_VALUE;
}
double result = value / rightValue;
return new IntState(result.toInt());
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value == rightValue);
} else if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value == rightValue.toDouble());
}
return BoolState.FALSE_STATE;
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
BoolState lessThan(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value < rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value < rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
BoolState lessThanOrEqual(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value <= rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value <= rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
NumState minus(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value - rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value - rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
NumState negated() {
if (value == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(-(value));
}
@override
NumState remainder(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value % rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value % rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
NumState times(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value * rightValue.toDouble());
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new DoubleState(value * rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
String toString() => value == null ? "-unknown-" : value.toString();
}
/// Exception that would be thrown during the evaluation of Dart code.
class EvaluationException {
/// The error code associated with the exception.
final ErrorCode errorCode;
/// Initialize a newly created exception to have the given [errorCode].
EvaluationException(this.errorCode);
}
/// The state of an object representing a function.
class FunctionState extends InstanceState {
/// The element representing the function being modeled.
final ExecutableElement _element;
/// Initialize a newly created state to represent the function with the given
/// [element].
FunctionState(this._element);
@override
int get hashCode => _element == null ? 0 : _element.hashCode;
@override
String get typeName => "Function";
@override
bool operator ==(Object object) =>
object is FunctionState && (_element == object._element);
@override
StringState convertToString() {
if (_element == null) {
return StringState.UNKNOWN_VALUE;
}
return new StringState(_element.name);
}
@override
BoolState equalEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
if (_element == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is FunctionState) {
ExecutableElement rightElement = rightOperand._element;
if (rightElement == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(_element == rightElement);
}
return BoolState.FALSE_STATE;
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
String toString() => _element == null ? "-unknown-" : _element.name;
}
/// The state of an object representing a Dart object for which there is no more
/// specific state.
class GenericState extends InstanceState {
/// Pseudo-field that we use to represent fields in the superclass.
static String SUPERCLASS_FIELD = "(super)";
/// A state that can be used to represent an object whose state is not known.
static GenericState UNKNOWN_VALUE =
new GenericState(new HashMap<String, DartObjectImpl>());
/// The values of the fields of this instance.
final Map<String, DartObjectImpl> _fieldMap;
/// Information about the constructor invoked to generate this instance.
final ConstructorInvocation invocation;
/// Initialize a newly created state to represent a newly created object. The
/// [fieldMap] contains the values of the fields of the instance.
GenericState(this._fieldMap, {this.invocation});
@override
Map<String, DartObjectImpl> get fields => _fieldMap;
@override
int get hashCode {
int hashCode = 0;
for (DartObjectImpl value in _fieldMap.values) {
hashCode += value.hashCode;
}
return hashCode;
}
@override
bool get isUnknown => identical(this, UNKNOWN_VALUE);
@override
String get typeName => "user defined type";
@override
bool operator ==(Object object) {
if (object is GenericState) {
HashSet<String> otherFields =
new HashSet<String>.from(object._fieldMap.keys.toSet());
for (String fieldName in _fieldMap.keys.toSet()) {
if (_fieldMap[fieldName] != object._fieldMap[fieldName]) {
return false;
}
otherFields.remove(fieldName);
}
for (String fieldName in otherFields) {
if (object._fieldMap[fieldName] != _fieldMap[fieldName]) {
return false;
}
}
return true;
}
return false;
}
@override
StringState convertToString() => StringState.UNKNOWN_VALUE;
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
return BoolState.from(this == rightOperand);
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
List<String> fieldNames = _fieldMap.keys.toList();
fieldNames.sort();
bool first = true;
for (String fieldName in fieldNames) {
if (first) {
first = false;
} else {
buffer.write('; ');
}
buffer.write(fieldName);
buffer.write(' = ');
buffer.write(_fieldMap[fieldName]);
}
return buffer.toString();
}
}
/// The state of an object representing a Dart object.
abstract class InstanceState {
/// If this represents a generic dart object, return a map from its field
/// names to their values. Otherwise return null.
Map<String, DartObjectImpl> get fields => null;
/// Return `true` if this object represents an object whose type is 'bool'.
bool get isBool => false;
/// Return `true` if this object represents an object whose type is either
/// 'bool', 'num', 'String', or 'Null'.
bool get isBoolNumStringOrNull => false;
/// Return `true` if this object represents an object whose type is 'int'.
bool get isInt => false;
/// Return `true` if this object represents the value 'null'.
bool get isNull => false;
/// Return `true` if this object represents an unknown value.
bool get isUnknown => false;
/// Return the name of the type of this value.
String get typeName;
/// Return the result of invoking the '+' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
InstanceState add(InstanceState rightOperand) {
if (this is StringState && rightOperand is StringState) {
return concatenate(rightOperand);
}
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Throw an exception if the given [state] does not represent a boolean value.
void assertBool(InstanceState state) {
if (state is! BoolState) {
throw new EvaluationException(CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL);
}
}
/// Throw an exception if the given [state] does not represent a boolean,
/// numeric, string or null value.
void assertBoolNumStringOrNull(InstanceState state) {
if (!(state is BoolState ||
state is NumState ||
state is StringState ||
state is NullState)) {
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING);
}
}
/// Throw an exception if the given [state] does not represent an integer or
/// null value.
void assertIntOrNull(InstanceState state) {
if (!(state is IntState || state is NullState)) {
throw new EvaluationException(CompileTimeErrorCode.CONST_EVAL_TYPE_INT);
}
}
/// Throw an exception if the given [state] does not represent a boolean,
/// numeric, string or null value.
void assertNumOrNull(InstanceState state) {
if (!(state is NumState || state is NullState)) {
throw new EvaluationException(CompileTimeErrorCode.CONST_EVAL_TYPE_NUM);
}
}
/// Throw an exception if the given [state] does not represent a String value.
void assertString(InstanceState state) {
if (state is! StringState) {
throw new EvaluationException(CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL);
}
}
/// Return the result of invoking the '&' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState bitAnd(InstanceState rightOperand) {
assertIntOrNull(this);
assertIntOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '~' operator on this object.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState bitNot() {
assertIntOrNull(this);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '|' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState bitOr(InstanceState rightOperand) {
assertIntOrNull(this);
assertIntOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '^' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState bitXor(InstanceState rightOperand) {
assertIntOrNull(this);
assertIntOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the ' ' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
StringState concatenate(InstanceState rightOperand) {
assertString(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of applying boolean conversion to this object.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState convertToBool() => BoolState.FALSE_STATE;
/// Return the result of converting this object to a String.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
StringState convertToString();
/// Return the result of invoking the '/' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
NumState divide(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '==' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState equalEqual(InstanceState rightOperand);
/// Return the result of invoking the '>' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState greaterThan(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '>=' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState greaterThanOrEqual(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '~/' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState integerDivide(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the identical function on this object with
/// the [rightOperand].
BoolState isIdentical(InstanceState rightOperand);
/// Return the result of invoking the '&&' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState lazyAnd(InstanceState rightOperandComputer()) {
assertBool(this);
if (convertToBool() == BoolState.FALSE_STATE) {
return this;
}
InstanceState rightOperand = rightOperandComputer();
assertBool(rightOperand);
return rightOperand.convertToBool();
}
/// Return the result of invoking the '==' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState lazyEqualEqual(InstanceState rightOperand);
/// Return the result of invoking the '||' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState lazyOr(InstanceState rightOperandComputer()) {
assertBool(this);
if (convertToBool() == BoolState.TRUE_STATE) {
return this;
}
InstanceState rightOperand = rightOperandComputer();
assertBool(rightOperand);
return rightOperand.convertToBool();
}
/// Return the result of invoking the '<' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState lessThan(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '<=' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState lessThanOrEqual(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '&' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState logicalAnd(InstanceState rightOperand) {
assertBool(this);
assertBool(rightOperand);
bool leftValue = convertToBool().value;
bool rightValue = rightOperand.convertToBool().value;
if (leftValue == null || rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(leftValue & rightValue);
}
/// Return the result of invoking the '!' operator on this object.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState logicalNot() {
assertBool(this);
return BoolState.TRUE_STATE;
}
/// Return the result of invoking the '|' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState logicalOr(InstanceState rightOperand) {
assertBool(this);
assertBool(rightOperand);
bool leftValue = convertToBool().value;
bool rightValue = rightOperand.convertToBool().value;
if (leftValue == null || rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(leftValue | rightValue);
}
/// Return the result of invoking the '>>' operator on this object with
/// the [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState logicalShiftRight(InstanceState rightOperand) {
assertIntOrNull(this);
assertIntOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '^' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
BoolState logicalXor(InstanceState rightOperand) {
assertBool(this);
assertBool(rightOperand);
bool leftValue = convertToBool().value;
bool rightValue = rightOperand.convertToBool().value;
if (leftValue == null || rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(leftValue ^ rightValue);
}
/// Return the result of invoking the '-' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
NumState minus(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '-' operator on this object.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
NumState negated() {
assertNumOrNull(this);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '%' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
NumState remainder(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '<<' operator on this object with
/// the [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState shiftLeft(InstanceState rightOperand) {
assertIntOrNull(this);
assertIntOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '>>' operator on this object with
/// the [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState shiftRight(InstanceState rightOperand) {
assertIntOrNull(this);
assertIntOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the 'length' getter on this object.
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
IntState stringLength() {
assertString(this);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
/// Return the result of invoking the '*' operator on this object with the
/// [rightOperand].
///
/// Throws an [EvaluationException] if the operator is not appropriate for an
/// object of this kind.
NumState times(InstanceState rightOperand) {
assertNumOrNull(this);
assertNumOrNull(rightOperand);
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
}
/// The state of an object representing an int.
class IntState extends NumState {
/// A state that can be used to represent an int whose value is not known.
static IntState UNKNOWN_VALUE = new IntState(null);
/// The value of this instance.
final int value;
/// Initialize a newly created state to represent an int with the given
/// [value].
IntState(this.value);
@override
int get hashCode => value == null ? 0 : value.hashCode;
@override
bool get isInt => true;
@override
bool get isUnknown => value == null;
@override
String get typeName => "int";
@override
bool operator ==(Object object) =>
object is IntState && (value == object.value);
@override
NumState add(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
if (rightOperand is DoubleState) {
return DoubleState.UNKNOWN_VALUE;
}
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new IntState(value + rightValue);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return DoubleState.UNKNOWN_VALUE;
}
return new DoubleState(value.toDouble() + rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
IntState bitAnd(InstanceState rightOperand) {
assertIntOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new IntState(value & rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
IntState bitNot() {
if (value == null) {
return UNKNOWN_VALUE;
}
return new IntState(~value);
}
@override
IntState bitOr(InstanceState rightOperand) {
assertIntOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new IntState(value | rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
IntState bitXor(InstanceState rightOperand) {
assertIntOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new IntState(value ^ rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
StringState convertToString() {
if (value == null) {
return StringState.UNKNOWN_VALUE;
}
return new StringState(value.toString());
}
@override
NumState divide(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return DoubleState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return DoubleState.UNKNOWN_VALUE;
} else {
return new DoubleState(value.toDouble() / rightValue.toDouble());
}
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return DoubleState.UNKNOWN_VALUE;
}
return new DoubleState(value.toDouble() / rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
BoolState greaterThan(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value.compareTo(rightValue) > 0);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value.toDouble() > rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
BoolState greaterThanOrEqual(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value.compareTo(rightValue) >= 0);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value.toDouble() >= rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
IntState integerDivide(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
} else if (rightValue == 0) {
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_IDBZE);
}
return new IntState(value ~/ rightValue);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
double result = value.toDouble() / rightValue;
return new IntState(result.toInt());
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value == rightValue);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(rightValue == value.toDouble());
}
return BoolState.FALSE_STATE;
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
BoolState lessThan(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value.compareTo(rightValue) < 0);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value.toDouble() < rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
BoolState lessThanOrEqual(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value.compareTo(rightValue) <= 0);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value.toDouble() <= rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
IntState logicalShiftRight(InstanceState rightOperand) {
assertIntOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
} else if (rightValue.bitLength > 31) {
return UNKNOWN_VALUE;
}
if (rightValue >= 0) {
// TODO(brianwilkerson) After the analyzer package has a minimum SDK
// constraint that includes support for the real operator, consider
// changing the line below to
// return new IntState(value >>> rightValue);
int divisor = 1 << rightValue;
if (divisor == 0) {
// The `rightValue` is large enough to cause all of the non-zero bits
// in the left operand to be shifted out of the value.
return new IntState(0);
}
return new IntState(value ~/ divisor);
}
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
NumState minus(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
if (rightOperand is DoubleState) {
return DoubleState.UNKNOWN_VALUE;
}
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new IntState(value - rightValue);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return DoubleState.UNKNOWN_VALUE;
}
return new DoubleState(value.toDouble() - rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
NumState negated() {
if (value == null) {
return UNKNOWN_VALUE;
}
return new IntState(-value);
}
@override
NumState remainder(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
if (rightOperand is DoubleState) {
return DoubleState.UNKNOWN_VALUE;
}
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
if (rightValue != 0) {
return new IntState(value % rightValue);
}
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return DoubleState.UNKNOWN_VALUE;
}
return new DoubleState(value.toDouble() % rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
IntState shiftLeft(InstanceState rightOperand) {
assertIntOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
} else if (rightValue.bitLength > 31) {
return UNKNOWN_VALUE;
}
if (rightValue >= 0) {
return new IntState(value << rightValue);
}
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
IntState shiftRight(InstanceState rightOperand) {
assertIntOrNull(rightOperand);
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
} else if (rightValue.bitLength > 31) {
return UNKNOWN_VALUE;
}
if (rightValue >= 0) {
return new IntState(value >> rightValue);
}
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
NumState times(InstanceState rightOperand) {
assertNumOrNull(rightOperand);
if (value == null) {
if (rightOperand is DoubleState) {
return DoubleState.UNKNOWN_VALUE;
}
return UNKNOWN_VALUE;
}
if (rightOperand is IntState) {
int rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new IntState(value * rightValue);
} else if (rightOperand is DoubleState) {
double rightValue = rightOperand.value;
if (rightValue == null) {
return DoubleState.UNKNOWN_VALUE;
}
return new DoubleState(value.toDouble() * rightValue);
}
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
String toString() => value == null ? "-unknown-" : value.toString();
}
/// The state of an object representing a list.
class ListState extends InstanceState {
/// The elements of the list.
final List<DartObjectImpl> _elements;
/// Initialize a newly created state to represent a list with the given
/// [elements].
ListState(this._elements);
@override
int get hashCode {
int value = 0;
int count = _elements.length;
for (int i = 0; i < count; i++) {
value = (value << 3) ^ _elements[i].hashCode;
}
return value;
}
@override
String get typeName => "List";
@override
bool operator ==(Object object) {
if (object is ListState) {
List<DartObjectImpl> otherElements = object._elements;
int count = _elements.length;
if (otherElements.length != count) {
return false;
} else if (count == 0) {
return true;
}
for (int i = 0; i < count; i++) {
if (_elements[i] != otherElements[i]) {
return false;
}
}
return true;
}
return false;
}
@override
StringState convertToString() => StringState.UNKNOWN_VALUE;
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
return BoolState.from(this == rightOperand);
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
buffer.write('[');
bool first = true;
_elements.forEach((DartObjectImpl element) {
if (first) {
first = false;
} else {
buffer.write(', ');
}
buffer.write(element);
});
buffer.write(']');
return buffer.toString();
}
}
/// The state of an object representing a map.
class MapState extends InstanceState {
/// The entries in the map.
final Map<DartObjectImpl, DartObjectImpl> _entries;
/// Initialize a newly created state to represent a map with the given
/// [entries].
MapState(this._entries);
@override
int get hashCode {
int value = 0;
for (DartObjectImpl key in _entries.keys.toSet()) {
value = (value << 3) ^ key.hashCode;
}
return value;
}
@override
String get typeName => "Map";
@override
bool operator ==(Object object) {
if (object is MapState) {
Map<DartObjectImpl, DartObjectImpl> otherElements = object._entries;
int count = _entries.length;
if (otherElements.length != count) {
return false;
} else if (count == 0) {
return true;
}
for (DartObjectImpl key in _entries.keys) {
DartObjectImpl value = _entries[key];
DartObjectImpl otherValue = otherElements[key];
if (value != otherValue) {
return false;
}
}
return true;
}
return false;
}
@override
StringState convertToString() => StringState.UNKNOWN_VALUE;
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
return BoolState.from(this == rightOperand);
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
buffer.write('{');
bool first = true;
_entries.forEach((DartObjectImpl key, DartObjectImpl value) {
if (first) {
first = false;
} else {
buffer.write(', ');
}
buffer.write(key);
buffer.write(' = ');
buffer.write(value);
});
buffer.write('}');
return buffer.toString();
}
}
/// The state of an object representing the value 'null'.
class NullState extends InstanceState {
/// An instance representing the boolean value 'null'.
static NullState NULL_STATE = new NullState();
@override
int get hashCode => 0;
@override
bool get isBoolNumStringOrNull => true;
@override
bool get isNull => true;
@override
String get typeName => "Null";
@override
bool operator ==(Object object) => object is NullState;
@override
BoolState convertToBool() {
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
StringState convertToString() => new StringState("null");
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
return BoolState.from(rightOperand is NullState);
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
BoolState logicalNot() {
throw new EvaluationException(
CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION);
}
@override
String toString() => "null";
}
/// The state of an object representing a number.
abstract class NumState extends InstanceState {
@override
bool get isBoolNumStringOrNull => true;
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
}
/// The state of an object representing a set.
class SetState extends InstanceState {
/// The elements of the set.
final Set<DartObjectImpl> _elements;
/// Initialize a newly created state to represent a set with the given
/// [elements].
SetState(this._elements);
@override
int get hashCode {
int value = 0;
for (DartObjectImpl element in _elements) {
value = (value << 3) ^ element.hashCode;
}
return value;
}
@override
String get typeName => "Set";
@override
bool operator ==(Object object) {
if (object is SetState) {
List<DartObjectImpl> elements = _elements.toList();
List<DartObjectImpl> otherElements = object._elements.toList();
int count = elements.length;
if (otherElements.length != count) {
return false;
} else if (count == 0) {
return true;
}
for (int i = 0; i < count; i++) {
if (elements[i] != otherElements[i]) {
return false;
}
}
return true;
}
return false;
}
@override
StringState convertToString() => StringState.UNKNOWN_VALUE;
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
return BoolState.from(this == rightOperand);
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
buffer.write('{');
bool first = true;
_elements.forEach((DartObjectImpl element) {
if (first) {
first = false;
} else {
buffer.write(', ');
}
buffer.write(element);
});
buffer.write('}');
return buffer.toString();
}
}
/// The state of an object representing a string.
class StringState extends InstanceState {
/// A state that can be used to represent a double whose value is not known.
static StringState UNKNOWN_VALUE = new StringState(null);
/// The value of this instance.
final String value;
/// Initialize a newly created state to represent the given [value].
StringState(this.value);
@override
int get hashCode => value == null ? 0 : value.hashCode;
@override
bool get isBoolNumStringOrNull => true;
@override
bool get isUnknown => value == null;
@override
String get typeName => "String";
@override
bool operator ==(Object object) =>
object is StringState && (value == object.value);
@override
StringState concatenate(InstanceState rightOperand) {
if (value == null) {
return UNKNOWN_VALUE;
}
if (rightOperand is StringState) {
String rightValue = rightOperand.value;
if (rightValue == null) {
return UNKNOWN_VALUE;
}
return new StringState("$value$rightValue");
}
return super.concatenate(rightOperand);
}
@override
StringState convertToString() => this;
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is StringState) {
String rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value == rightValue);
}
return BoolState.FALSE_STATE;
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
IntState stringLength() {
if (value == null) {
return IntState.UNKNOWN_VALUE;
}
return new IntState(value.length);
}
@override
String toString() => value == null ? "-unknown-" : "'$value'";
}
/// The state of an object representing a symbol.
class SymbolState extends InstanceState {
/// The value of this instance.
final String value;
/// Initialize a newly created state to represent the given [value].
SymbolState(this.value);
@override
int get hashCode => value == null ? 0 : value.hashCode;
@override
String get typeName => "Symbol";
@override
bool operator ==(Object object) =>
object is SymbolState && (value == object.value);
@override
StringState convertToString() {
if (value == null) {
return StringState.UNKNOWN_VALUE;
}
return new StringState(value);
}
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
if (value == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is SymbolState) {
String rightValue = rightOperand.value;
if (rightValue == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(value == rightValue);
}
return BoolState.FALSE_STATE;
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
String toString() => value == null ? "-unknown-" : "#$value";
}
/// The state of an object representing a type.
class TypeState extends InstanceState {
/// The element representing the type being modeled.
final DartType _type;
/// Initialize a newly created state to represent the given [value].
TypeState(this._type);
@override
int get hashCode => _type?.hashCode ?? 0;
@override
String get typeName => "Type";
@override
bool operator ==(Object object) =>
object is TypeState && (_type == object._type);
@override
StringState convertToString() {
if (_type == null) {
return StringState.UNKNOWN_VALUE;
}
return new StringState(_type.displayName);
}
@override
BoolState equalEqual(InstanceState rightOperand) {
assertBoolNumStringOrNull(rightOperand);
return isIdentical(rightOperand);
}
@override
BoolState isIdentical(InstanceState rightOperand) {
if (_type == null) {
return BoolState.UNKNOWN_VALUE;
}
if (rightOperand is TypeState) {
DartType rightType = rightOperand._type;
if (rightType == null) {
return BoolState.UNKNOWN_VALUE;
}
return BoolState.from(_type == rightType);
}
return BoolState.FALSE_STATE;
}
@override
BoolState lazyEqualEqual(InstanceState rightOperand) {
return isIdentical(rightOperand);
}
@override
String toString() => _type?.toString() ?? "-unknown-";
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/ast/ast.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'dart:math' as math;
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/precedence.dart';
import 'package:analyzer/dart/ast/syntactic_entity.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/fasta/token_utils.dart' as util show findPrevious;
import 'package:analyzer/src/generated/engine.dart' show AnalysisEngine;
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart' show LineInfo, Source;
import 'package:analyzer/src/generated/utilities_dart.dart';
/// Two or more string literals that are implicitly concatenated because of
/// being adjacent (separated only by whitespace).
///
/// While the grammar only allows adjacent strings when all of the strings are
/// of the same kind (single line or multi-line), this class doesn't enforce
/// that restriction.
///
/// adjacentStrings ::=
/// [StringLiteral] [StringLiteral]+
class AdjacentStringsImpl extends StringLiteralImpl implements AdjacentStrings {
/// The strings that are implicitly concatenated.
NodeList<StringLiteral> _strings;
/// Initialize a newly created list of adjacent strings. To be syntactically
/// valid, the list of [strings] must contain at least two elements.
AdjacentStringsImpl(List<StringLiteral> strings) {
_strings = new NodeListImpl<StringLiteral>(this, strings);
}
@override
Token get beginToken => _strings.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..addAll(_strings);
@override
Token get endToken => _strings.endToken;
@override
NodeList<StringLiteral> get strings => _strings;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitAdjacentStrings(this);
@override
void visitChildren(AstVisitor visitor) {
_strings.accept(visitor);
}
@override
void _appendStringValue(StringBuffer buffer) {
int length = strings.length;
for (int i = 0; i < length; i++) {
StringLiteralImpl stringLiteral = strings[i];
stringLiteral._appendStringValue(buffer);
}
}
}
/// An AST node that can be annotated with both a documentation comment and a
/// list of annotations.
abstract class AnnotatedNodeImpl extends AstNodeImpl implements AnnotatedNode {
/// The documentation comment associated with this node, or `null` if this
/// node does not have a documentation comment associated with it.
CommentImpl _comment;
/// The annotations associated with this node.
NodeList<Annotation> _metadata;
/// Initialize a newly created annotated node. Either or both of the [comment]
/// and [metadata] can be `null` if the node does not have the corresponding
/// attribute.
AnnotatedNodeImpl(CommentImpl comment, List<Annotation> metadata) {
_comment = _becomeParentOf(comment);
_metadata = new NodeListImpl<Annotation>(this, metadata);
}
@override
Token get beginToken {
if (_comment == null) {
if (_metadata.isEmpty) {
return firstTokenAfterCommentAndMetadata;
}
return _metadata.beginToken;
} else if (_metadata.isEmpty) {
return _comment.beginToken;
}
Token commentToken = _comment.beginToken;
Token metadataToken = _metadata.beginToken;
if (commentToken.offset < metadataToken.offset) {
return commentToken;
}
return metadataToken;
}
@override
Comment get documentationComment => _comment;
@override
void set documentationComment(Comment comment) {
_comment = _becomeParentOf(comment as CommentImpl);
}
@override
NodeList<Annotation> get metadata => _metadata;
@override
List<AstNode> get sortedCommentAndAnnotations {
return <AstNode>[]
..add(_comment)
..addAll(_metadata)
..sort(AstNode.LEXICAL_ORDER);
}
/// Return a holder of child entities that subclasses can add to.
ChildEntities get _childEntities {
ChildEntities result = new ChildEntities();
if (_commentIsBeforeAnnotations()) {
result
..add(_comment)
..addAll(_metadata);
} else {
result.addAll(sortedCommentAndAnnotations);
}
return result;
}
@override
void visitChildren(AstVisitor visitor) {
if (_commentIsBeforeAnnotations()) {
_comment?.accept(visitor);
_metadata.accept(visitor);
} else {
List<AstNode> children = sortedCommentAndAnnotations;
int length = children.length;
for (int i = 0; i < length; i++) {
children[i].accept(visitor);
}
}
}
/// Return `true` if there are no annotations before the comment. Note that a
/// result of `true` does not imply that there is a comment, nor that there
/// are annotations associated with this node.
bool _commentIsBeforeAnnotations() {
if (_comment == null || _metadata.isEmpty) {
return true;
}
Annotation firstAnnotation = _metadata[0];
return _comment.offset < firstAnnotation.offset;
}
}
/// An annotation that can be associated with an AST node.
///
/// metadata ::=
/// annotation*
///
/// annotation ::=
/// '@' [Identifier] ('.' [SimpleIdentifier])? [ArgumentList]?
class AnnotationImpl extends AstNodeImpl implements Annotation {
/// The at sign that introduced the annotation.
@override
Token atSign;
/// The name of the class defining the constructor that is being invoked or
/// the name of the field that is being referenced.
IdentifierImpl _name;
/// The period before the constructor name, or `null` if this annotation is
/// not the invocation of a named constructor.
@override
Token period;
/// The name of the constructor being invoked, or `null` if this annotation is
/// not the invocation of a named constructor.
SimpleIdentifierImpl _constructorName;
/// The arguments to the constructor being invoked, or `null` if this
/// annotation is not the invocation of a constructor.
ArgumentListImpl _arguments;
/// The element associated with this annotation, or `null` if the AST
/// structure has not been resolved or if this annotation could not be
/// resolved.
Element _element;
/// The element annotation representing this annotation in the element model.
@override
ElementAnnotation elementAnnotation;
/// Initialize a newly created annotation. Both the [period] and the
/// [constructorName] can be `null` if the annotation is not referencing a
/// named constructor. The [arguments] can be `null` if the annotation is not
/// referencing a constructor.
AnnotationImpl(this.atSign, IdentifierImpl name, this.period,
SimpleIdentifierImpl constructorName, ArgumentListImpl arguments) {
_name = _becomeParentOf(name);
_constructorName = _becomeParentOf(constructorName);
_arguments = _becomeParentOf(arguments);
}
@override
ArgumentList get arguments => _arguments;
@override
void set arguments(ArgumentList arguments) {
_arguments = _becomeParentOf(arguments as ArgumentListImpl);
}
@override
Token get beginToken => atSign;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(atSign)
..add(_name)
..add(period)
..add(_constructorName)
..add(_arguments);
@override
SimpleIdentifier get constructorName => _constructorName;
@override
void set constructorName(SimpleIdentifier name) {
_constructorName = _becomeParentOf(name as SimpleIdentifierImpl);
}
@override
Element get element {
if (_element != null) {
return _element;
} else if (_constructorName == null && _name != null) {
return _name.staticElement;
}
return null;
}
@override
void set element(Element element) {
_element = element;
}
@override
Token get endToken {
if (_arguments != null) {
return _arguments.endToken;
} else if (_constructorName != null) {
return _constructorName.endToken;
}
return _name.endToken;
}
@override
Identifier get name => _name;
@override
void set name(Identifier name) {
_name = _becomeParentOf(name as IdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitAnnotation(this);
@override
void visitChildren(AstVisitor visitor) {
_name?.accept(visitor);
_constructorName?.accept(visitor);
_arguments?.accept(visitor);
}
}
/// A list of arguments in the invocation of an executable element (that is, a
/// function, method, or constructor).
///
/// argumentList ::=
/// '(' arguments? ')'
///
/// arguments ::=
/// [NamedExpression] (',' [NamedExpression])*
/// | [Expression] (',' [Expression])* (',' [NamedExpression])*
class ArgumentListImpl extends AstNodeImpl implements ArgumentList {
/// The left parenthesis.
@override
Token leftParenthesis;
/// The expressions producing the values of the arguments.
NodeList<Expression> _arguments;
/// The right parenthesis.
@override
Token rightParenthesis;
/// A list containing the elements representing the parameters corresponding
/// to each of the arguments in this list, or `null` if the AST has not been
/// resolved or if the function or method being invoked could not be
/// determined based on static type information. The list must be the same
/// length as the number of arguments, but can contain `null` entries if a
/// given argument does not correspond to a formal parameter.
List<ParameterElement> _correspondingStaticParameters;
/// Initialize a newly created list of arguments. The list of [arguments] can
/// be `null` if there are no arguments.
ArgumentListImpl(
this.leftParenthesis, List<Expression> arguments, this.rightParenthesis) {
_arguments = new NodeListImpl<Expression>(this, arguments);
}
@override
NodeList<Expression> get arguments => _arguments;
@override
Token get beginToken => leftParenthesis;
@override
// TODO(paulberry): Add commas.
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(leftParenthesis)
..addAll(_arguments)
..add(rightParenthesis);
@deprecated
List<ParameterElement> get correspondingPropagatedParameters => null;
@deprecated
@override
void set correspondingPropagatedParameters(
List<ParameterElement> parameters) {
if (parameters != null && parameters.length != _arguments.length) {
throw new ArgumentError(
"Expected ${_arguments.length} parameters, not ${parameters.length}");
}
}
List<ParameterElement> get correspondingStaticParameters =>
_correspondingStaticParameters;
@override
void set correspondingStaticParameters(List<ParameterElement> parameters) {
if (parameters != null && parameters.length != _arguments.length) {
throw new ArgumentError(
"Expected ${_arguments.length} parameters, not ${parameters.length}");
}
_correspondingStaticParameters = parameters;
}
@override
Token get endToken => rightParenthesis;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitArgumentList(this);
@override
void visitChildren(AstVisitor visitor) {
_arguments.accept(visitor);
}
/// If
/// * the given [expression] is a child of this list,
/// * the AST structure has been resolved,
/// * the function being invoked is known based on static type information,
/// and
/// * the expression corresponds to one of the parameters of the function
/// being invoked,
/// then return the parameter element representing the parameter to which the
/// value of the given expression will be bound. Otherwise, return `null`.
ParameterElement _getStaticParameterElementFor(Expression expression) {
if (_correspondingStaticParameters == null ||
_correspondingStaticParameters.length != _arguments.length) {
// Either the AST structure has not been resolved, the invocation of which
// this list is a part could not be resolved, or the argument list was
// modified after the parameters were set.
return null;
}
int index = _arguments.indexOf(expression);
if (index < 0) {
// The expression isn't a child of this node.
return null;
}
return _correspondingStaticParameters[index];
}
}
/// An as expression.
///
/// asExpression ::=
/// [Expression] 'as' [TypeName]
class AsExpressionImpl extends ExpressionImpl implements AsExpression {
/// The expression used to compute the value being cast.
ExpressionImpl _expression;
/// The 'as' operator.
@override
Token asOperator;
/// The type being cast to.
TypeAnnotationImpl _type;
/// Initialize a newly created as expression.
AsExpressionImpl(
ExpressionImpl expression, this.asOperator, TypeAnnotationImpl type) {
_expression = _becomeParentOf(expression);
_type = _becomeParentOf(type);
}
@override
Token get beginToken => _expression.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_expression)..add(asOperator)..add(_type);
@override
Token get endToken => _type.endToken;
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.relational;
@override
TypeAnnotation get type => _type;
@override
void set type(TypeAnnotation type) {
_type = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitAsExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
_type?.accept(visitor);
}
}
/// An assert in the initializer list of a constructor.
///
/// assertInitializer ::=
/// 'assert' '(' [Expression] (',' [Expression])? ')'
class AssertInitializerImpl extends ConstructorInitializerImpl
implements AssertInitializer {
@override
Token assertKeyword;
@override
Token leftParenthesis;
/// The condition that is being asserted to be `true`.
ExpressionImpl _condition;
@override
Token comma;
/// The message to report if the assertion fails, or `null` if no message was
/// supplied.
ExpressionImpl _message;
@override
Token rightParenthesis;
/// Initialize a newly created assert initializer.
AssertInitializerImpl(
this.assertKeyword,
this.leftParenthesis,
ExpressionImpl condition,
this.comma,
ExpressionImpl message,
this.rightParenthesis) {
_condition = _becomeParentOf(condition);
_message = _becomeParentOf(message);
}
@override
Token get beginToken => assertKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(assertKeyword)
..add(leftParenthesis)
..add(_condition)
..add(comma)
..add(_message)
..add(rightParenthesis);
@override
Expression get condition => _condition;
@override
void set condition(Expression condition) {
_condition = _becomeParentOf(condition as ExpressionImpl);
}
@override
Token get endToken => rightParenthesis;
@override
Expression get message => _message;
@override
void set message(Expression expression) {
_message = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitAssertInitializer(this);
@override
void visitChildren(AstVisitor visitor) {
_condition?.accept(visitor);
message?.accept(visitor);
}
}
/// An assert statement.
///
/// assertStatement ::=
/// 'assert' '(' [Expression] ')' ';'
class AssertStatementImpl extends StatementImpl implements AssertStatement {
@override
Token assertKeyword;
@override
Token leftParenthesis;
/// The condition that is being asserted to be `true`.
ExpressionImpl _condition;
@override
Token comma;
/// The message to report if the assertion fails, or `null` if no message was
/// supplied.
ExpressionImpl _message;
@override
Token rightParenthesis;
@override
Token semicolon;
/// Initialize a newly created assert statement.
AssertStatementImpl(
this.assertKeyword,
this.leftParenthesis,
ExpressionImpl condition,
this.comma,
ExpressionImpl message,
this.rightParenthesis,
this.semicolon) {
_condition = _becomeParentOf(condition);
_message = _becomeParentOf(message);
}
@override
Token get beginToken => assertKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(assertKeyword)
..add(leftParenthesis)
..add(_condition)
..add(comma)
..add(_message)
..add(rightParenthesis)
..add(semicolon);
@override
Expression get condition => _condition;
@override
void set condition(Expression condition) {
_condition = _becomeParentOf(condition as ExpressionImpl);
}
@override
Token get endToken => semicolon;
@override
Expression get message => _message;
@override
void set message(Expression expression) {
_message = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitAssertStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_condition?.accept(visitor);
message?.accept(visitor);
}
}
/// An assignment expression.
///
/// assignmentExpression ::=
/// [Expression] operator [Expression]
class AssignmentExpressionImpl extends ExpressionImpl
implements AssignmentExpression {
/// The expression used to compute the left hand side.
ExpressionImpl _leftHandSide;
/// The assignment operator being applied.
@override
Token operator;
/// The expression used to compute the right hand side.
ExpressionImpl _rightHandSide;
/// The element associated with the operator based on the static type of the
/// left-hand-side, or `null` if the AST structure has not been resolved, if
/// the operator is not a compound operator, or if the operator could not be
/// resolved.
@override
MethodElement staticElement;
/// Initialize a newly created assignment expression.
AssignmentExpressionImpl(ExpressionImpl leftHandSide, this.operator,
ExpressionImpl rightHandSide) {
if (leftHandSide == null || rightHandSide == null) {
String message;
if (leftHandSide == null) {
if (rightHandSide == null) {
message = "Both the left-hand and right-hand sides are null";
} else {
message = "The left-hand size is null";
}
} else {
message = "The right-hand size is null";
}
AnalysisEngine.instance.logger.logError(
message, new CaughtException(new AnalysisException(message), null));
}
_leftHandSide = _becomeParentOf(leftHandSide);
_rightHandSide = _becomeParentOf(rightHandSide);
}
@override
Token get beginToken => _leftHandSide.beginToken;
@override
@deprecated
MethodElement get bestElement => staticElement;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_leftHandSide)
..add(operator)
..add(_rightHandSide);
@override
Token get endToken => _rightHandSide.endToken;
@override
Expression get leftHandSide => _leftHandSide;
@override
void set leftHandSide(Expression expression) {
_leftHandSide = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.assignment;
@deprecated
@override
MethodElement get propagatedElement => null;
@deprecated
@override
set propagatedElement(MethodElement element) {}
@override
Expression get rightHandSide => _rightHandSide;
@override
void set rightHandSide(Expression expression) {
_rightHandSide = _becomeParentOf(expression as ExpressionImpl);
}
/// If the AST structure has been resolved, and the function being invoked is
/// known based on static type information, then return the parameter element
/// representing the parameter to which the value of the right operand will be
/// bound. Otherwise, return `null`.
ParameterElement get _staticParameterElementForRightHandSide {
ExecutableElement executableElement;
if (staticElement != null) {
executableElement = staticElement;
} else {
Expression left = _leftHandSide;
if (left is Identifier) {
Element leftElement = left.staticElement;
if (leftElement is ExecutableElement) {
executableElement = leftElement;
}
} else if (left is PropertyAccess) {
Element leftElement = left.propertyName.staticElement;
if (leftElement is ExecutableElement) {
executableElement = leftElement;
}
}
}
if (executableElement == null) {
return null;
}
List<ParameterElement> parameters = executableElement.parameters;
if (parameters.isEmpty) {
return null;
}
return parameters[0];
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitAssignmentExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_leftHandSide?.accept(visitor);
_rightHandSide?.accept(visitor);
}
}
/// A node in the AST structure for a Dart program.
abstract class AstNodeImpl implements AstNode {
/// The parent of the node, or `null` if the node is the root of an AST
/// structure.
AstNode _parent;
/// A table mapping the names of properties to their values, or `null` if this
/// node does not have any properties associated with it.
Map<String, Object> _propertyMap;
@override
int get end => offset + length;
@override
bool get isSynthetic => false;
@override
int get length {
Token beginToken = this.beginToken;
Token endToken = this.endToken;
if (beginToken == null || endToken == null) {
return -1;
}
return endToken.offset + endToken.length - beginToken.offset;
}
@override
int get offset {
Token beginToken = this.beginToken;
if (beginToken == null) {
return -1;
}
return beginToken.offset;
}
@override
AstNode get parent => _parent;
@override
AstNode get root {
AstNode root = this;
AstNode parent = this.parent;
while (parent != null) {
root = parent;
parent = root.parent;
}
return root;
}
Token findPrevious(Token target) =>
util.findPrevious(beginToken, target) ?? parent?.findPrevious(target);
@override
E getProperty<E>(String name) {
if (_propertyMap == null) {
return null;
}
return _propertyMap[name] as E;
}
@override
void setProperty(String name, Object value) {
if (value == null) {
if (_propertyMap != null) {
_propertyMap.remove(name);
if (_propertyMap.isEmpty) {
_propertyMap = null;
}
}
} else {
if (_propertyMap == null) {
_propertyMap = new HashMap<String, Object>();
}
_propertyMap[name] = value;
}
}
@override
E thisOrAncestorMatching<E extends AstNode>(Predicate<AstNode> predicate) {
// TODO(brianwilkerson) It is a bug that this method can return `this`.
AstNode node = this;
while (node != null && !predicate(node)) {
node = node.parent;
}
return node as E;
}
@override
T thisOrAncestorOfType<T extends AstNode>() {
AstNode node = this;
while (node != null && node is! T) {
node = node.parent;
}
return node as T;
}
@override
String toSource() {
StringBuffer buffer = new StringBuffer();
accept(new ToSourceVisitor2(buffer));
return buffer.toString();
}
@override
String toString() => toSource();
/// Make this node the parent of the given [child] node. Return the child
/// node.
T _becomeParentOf<T extends AstNodeImpl>(T child) {
if (child != null) {
child._parent = this;
}
return child;
}
}
/// An await expression.
///
/// awaitExpression ::=
/// 'await' [Expression]
class AwaitExpressionImpl extends ExpressionImpl implements AwaitExpression {
/// The 'await' keyword.
@override
Token awaitKeyword;
/// The expression whose value is being waited on.
ExpressionImpl _expression;
/// Initialize a newly created await expression.
AwaitExpressionImpl(this.awaitKeyword, ExpressionImpl expression) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken {
if (awaitKeyword != null) {
return awaitKeyword;
}
return _expression.beginToken;
}
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(awaitKeyword)..add(_expression);
@override
Token get endToken => _expression.endToken;
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.prefix;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitAwaitExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// A binary (infix) expression.
///
/// binaryExpression ::=
/// [Expression] [Token] [Expression]
class BinaryExpressionImpl extends ExpressionImpl implements BinaryExpression {
/// The expression used to compute the left operand.
ExpressionImpl _leftOperand;
/// The binary operator being applied.
@override
Token operator;
/// The expression used to compute the right operand.
ExpressionImpl _rightOperand;
/// The element associated with the operator based on the static type of the
/// left operand, or `null` if the AST structure has not been resolved, if the
/// operator is not user definable, or if the operator could not be resolved.
@override
MethodElement staticElement;
@override
FunctionType staticInvokeType;
/// Initialize a newly created binary expression.
BinaryExpressionImpl(
ExpressionImpl leftOperand, this.operator, ExpressionImpl rightOperand) {
_leftOperand = _becomeParentOf(leftOperand);
_rightOperand = _becomeParentOf(rightOperand);
}
@override
Token get beginToken => _leftOperand.beginToken;
@override
@deprecated
MethodElement get bestElement => staticElement;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_leftOperand)..add(operator)..add(_rightOperand);
@override
Token get endToken => _rightOperand.endToken;
@override
Expression get leftOperand => _leftOperand;
@override
void set leftOperand(Expression expression) {
_leftOperand = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.forTokenType(operator.type);
@deprecated
@override
MethodElement get propagatedElement => null;
@deprecated
@override
set propagatedElement(MethodElement element) {}
@override
Expression get rightOperand => _rightOperand;
@override
void set rightOperand(Expression expression) {
_rightOperand = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitBinaryExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_leftOperand?.accept(visitor);
_rightOperand?.accept(visitor);
}
}
/// A function body that consists of a block of statements.
///
/// blockFunctionBody ::=
/// ('async' | 'async' '*' | 'sync' '*')? [Block]
class BlockFunctionBodyImpl extends FunctionBodyImpl
implements BlockFunctionBody {
/// The token representing the 'async' or 'sync' keyword, or `null` if there
/// is no such keyword.
@override
Token keyword;
/// The star optionally following the 'async' or 'sync' keyword, or `null` if
/// there is wither no such keyword or no star.
@override
Token star;
/// The block representing the body of the function.
BlockImpl _block;
/// Initialize a newly created function body consisting of a block of
/// statements. The [keyword] can be `null` if there is no keyword specified
/// for the block. The [star] can be `null` if there is no star following the
/// keyword (and must be `null` if there is no keyword).
BlockFunctionBodyImpl(this.keyword, this.star, BlockImpl block) {
_block = _becomeParentOf(block);
}
@override
Token get beginToken {
if (keyword != null) {
return keyword;
}
return _block.beginToken;
}
@override
Block get block => _block;
@override
void set block(Block block) {
_block = _becomeParentOf(block as BlockImpl);
}
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(keyword)..add(star)..add(_block);
@override
Token get endToken => _block.endToken;
@override
bool get isAsynchronous => keyword != null && keyword.lexeme == Parser.ASYNC;
@override
bool get isGenerator => star != null;
@override
bool get isSynchronous => keyword == null || keyword.lexeme != Parser.ASYNC;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitBlockFunctionBody(this);
@override
void visitChildren(AstVisitor visitor) {
_block?.accept(visitor);
}
}
/// A sequence of statements.
///
/// block ::=
/// '{' statement* '}'
class BlockImpl extends StatementImpl implements Block {
/// The left curly bracket.
@override
Token leftBracket;
/// The statements contained in the block.
NodeList<Statement> _statements;
/// The right curly bracket.
@override
Token rightBracket;
/// Initialize a newly created block of code.
BlockImpl(this.leftBracket, List<Statement> statements, this.rightBracket) {
_statements = new NodeListImpl<Statement>(this, statements);
}
@override
Token get beginToken => leftBracket;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(leftBracket)
..addAll(_statements)
..add(rightBracket);
@override
Token get endToken => rightBracket;
@override
NodeList<Statement> get statements => _statements;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitBlock(this);
@override
void visitChildren(AstVisitor visitor) {
_statements.accept(visitor);
}
}
/// A boolean literal expression.
///
/// booleanLiteral ::=
/// 'false' | 'true'
class BooleanLiteralImpl extends LiteralImpl implements BooleanLiteral {
/// The token representing the literal.
@override
Token literal;
/// The value of the literal.
@override
bool value = false;
/// Initialize a newly created boolean literal.
BooleanLiteralImpl(this.literal, this.value);
@override
Token get beginToken => literal;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(literal);
@override
Token get endToken => literal;
@override
bool get isSynthetic => literal.isSynthetic;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitBooleanLiteral(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// A break statement.
///
/// breakStatement ::=
/// 'break' [SimpleIdentifier]? ';'
class BreakStatementImpl extends StatementImpl implements BreakStatement {
/// The token representing the 'break' keyword.
@override
Token breakKeyword;
/// The label associated with the statement, or `null` if there is no label.
SimpleIdentifierImpl _label;
/// The semicolon terminating the statement.
@override
Token semicolon;
/// The AstNode which this break statement is breaking from. This will be
/// either a [Statement] (in the case of breaking out of a loop), a
/// [SwitchMember] (in the case of a labeled break statement whose label
/// matches a label on a switch case in an enclosing switch statement), or
/// `null` if the AST has not yet been resolved or if the target could not be
/// resolved. Note that if the source code has errors, the target might be
/// invalid (e.g. trying to break to a switch case).
@override
AstNode target;
/// Initialize a newly created break statement. The [label] can be `null` if
/// there is no label associated with the statement.
BreakStatementImpl(
this.breakKeyword, SimpleIdentifierImpl label, this.semicolon) {
_label = _becomeParentOf(label);
}
@override
Token get beginToken => breakKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(breakKeyword)..add(_label)..add(semicolon);
@override
Token get endToken => semicolon;
@override
SimpleIdentifier get label => _label;
@override
void set label(SimpleIdentifier identifier) {
_label = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitBreakStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_label?.accept(visitor);
}
}
/// A sequence of cascaded expressions: expressions that share a common target.
/// There are three kinds of expressions that can be used in a cascade
/// expression: [IndexExpression], [MethodInvocation] and [PropertyAccess].
///
/// cascadeExpression ::=
/// [Expression] cascadeSection*
///
/// cascadeSection ::=
/// '..' (cascadeSelector arguments*) (assignableSelector arguments*)*
/// (assignmentOperator expressionWithoutCascade)?
///
/// cascadeSelector ::=
/// '[ ' expression '] '
/// | identifier
class CascadeExpressionImpl extends ExpressionImpl
implements CascadeExpression {
/// The target of the cascade sections.
ExpressionImpl _target;
/// The cascade sections sharing the common target.
NodeList<Expression> _cascadeSections;
/// Initialize a newly created cascade expression. The list of
/// [cascadeSections] must contain at least one element.
CascadeExpressionImpl(
ExpressionImpl target, List<Expression> cascadeSections) {
_target = _becomeParentOf(target);
_cascadeSections = new NodeListImpl<Expression>(this, cascadeSections);
}
@override
Token get beginToken => _target.beginToken;
@override
NodeList<Expression> get cascadeSections => _cascadeSections;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_target)
..addAll(_cascadeSections);
@override
Token get endToken => _cascadeSections.endToken;
@override
Precedence get precedence => Precedence.cascade;
@override
Expression get target => _target;
@override
void set target(Expression target) {
_target = _becomeParentOf(target as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitCascadeExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_target?.accept(visitor);
_cascadeSections.accept(visitor);
}
}
/// A catch clause within a try statement.
///
/// onPart ::=
/// catchPart [Block]
/// | 'on' type catchPart? [Block]
///
/// catchPart ::=
/// 'catch' '(' [SimpleIdentifier] (',' [SimpleIdentifier])? ')'
class CatchClauseImpl extends AstNodeImpl implements CatchClause {
/// The token representing the 'on' keyword, or `null` if there is no 'on'
/// keyword.
@override
Token onKeyword;
/// The type of exceptions caught by this catch clause, or `null` if this
/// catch clause catches every type of exception.
TypeAnnotationImpl _exceptionType;
/// The token representing the 'catch' keyword, or `null` if there is no
/// 'catch' keyword.
@override
Token catchKeyword;
/// The left parenthesis, or `null` if there is no 'catch' keyword.
@override
Token leftParenthesis;
/// The parameter whose value will be the exception that was thrown, or `null`
/// if there is no 'catch' keyword.
SimpleIdentifierImpl _exceptionParameter;
/// The comma separating the exception parameter from the stack trace
/// parameter, or `null` if there is no stack trace parameter.
@override
Token comma;
/// The parameter whose value will be the stack trace associated with the
/// exception, or `null` if there is no stack trace parameter.
SimpleIdentifierImpl _stackTraceParameter;
/// The right parenthesis, or `null` if there is no 'catch' keyword.
@override
Token rightParenthesis;
/// The body of the catch block.
BlockImpl _body;
/// Initialize a newly created catch clause. The [onKeyword] and
/// [exceptionType] can be `null` if the clause will catch all exceptions. The
/// [comma] and [stackTraceParameter] can be `null` if the stack trace
/// parameter is not defined.
CatchClauseImpl(
this.onKeyword,
TypeAnnotationImpl exceptionType,
this.catchKeyword,
this.leftParenthesis,
SimpleIdentifierImpl exceptionParameter,
this.comma,
SimpleIdentifierImpl stackTraceParameter,
this.rightParenthesis,
BlockImpl body) {
_exceptionType = _becomeParentOf(exceptionType);
_exceptionParameter = _becomeParentOf(exceptionParameter);
_stackTraceParameter = _becomeParentOf(stackTraceParameter);
_body = _becomeParentOf(body);
}
@override
Token get beginToken {
if (onKeyword != null) {
return onKeyword;
}
return catchKeyword;
}
@override
Block get body => _body;
@override
void set body(Block block) {
_body = _becomeParentOf(block as BlockImpl);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(onKeyword)
..add(_exceptionType)
..add(catchKeyword)
..add(leftParenthesis)
..add(_exceptionParameter)
..add(comma)
..add(_stackTraceParameter)
..add(rightParenthesis)
..add(_body);
@override
Token get endToken => _body.endToken;
@override
SimpleIdentifier get exceptionParameter => _exceptionParameter;
@override
void set exceptionParameter(SimpleIdentifier parameter) {
_exceptionParameter = _becomeParentOf(parameter as SimpleIdentifierImpl);
}
@override
TypeAnnotation get exceptionType => _exceptionType;
@override
void set exceptionType(TypeAnnotation exceptionType) {
_exceptionType = _becomeParentOf(exceptionType as TypeAnnotationImpl);
}
@override
SimpleIdentifier get stackTraceParameter => _stackTraceParameter;
@override
void set stackTraceParameter(SimpleIdentifier parameter) {
_stackTraceParameter = _becomeParentOf(parameter as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitCatchClause(this);
@override
void visitChildren(AstVisitor visitor) {
_exceptionType?.accept(visitor);
_exceptionParameter?.accept(visitor);
_stackTraceParameter?.accept(visitor);
_body?.accept(visitor);
}
}
/// Helper class to allow iteration of child entities of an AST node.
class ChildEntities
with IterableMixin<SyntacticEntity>
implements Iterable<SyntacticEntity> {
/// The list of child entities to be iterated over.
List<SyntacticEntity> _entities = [];
@override
Iterator<SyntacticEntity> get iterator => _entities.iterator;
/// Add an AST node or token as the next child entity, if it is not null.
void add(SyntacticEntity entity) {
if (entity != null) {
_entities.add(entity);
}
}
/// Add the given items as the next child entities, if [items] is not null.
void addAll(Iterable<SyntacticEntity> items) {
if (items != null) {
_entities.addAll(items);
}
}
}
/// The declaration of a class.
///
/// classDeclaration ::=
/// 'abstract'? 'class' [SimpleIdentifier] [TypeParameterList]?
/// ([ExtendsClause] [WithClause]?)?
/// [ImplementsClause]?
/// '{' [ClassMember]* '}'
class ClassDeclarationImpl extends ClassOrMixinDeclarationImpl
implements ClassDeclaration {
/// The 'abstract' keyword, or `null` if the keyword was absent.
@override
Token abstractKeyword;
/// The token representing the 'class' keyword.
@override
Token classKeyword;
/// The extends clause for the class, or `null` if the class does not extend
/// any other class.
ExtendsClauseImpl _extendsClause;
/// The with clause for the class, or `null` if the class does not have a with
/// clause.
WithClauseImpl _withClause;
/// The native clause for the class, or `null` if the class does not have a
/// native clause.
NativeClauseImpl _nativeClause;
/// Initialize a newly created class declaration. Either or both of the
/// [comment] and [metadata] can be `null` if the class does not have the
/// corresponding attribute. The [abstractKeyword] can be `null` if the class
/// is not abstract. The [typeParameters] can be `null` if the class does not
/// have any type parameters. Any or all of the [extendsClause], [withClause],
/// and [implementsClause] can be `null` if the class does not have the
/// corresponding clause. The list of [members] can be `null` if the class
/// does not have any members.
ClassDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
this.abstractKeyword,
this.classKeyword,
SimpleIdentifierImpl name,
TypeParameterListImpl typeParameters,
ExtendsClauseImpl extendsClause,
WithClauseImpl withClause,
ImplementsClauseImpl implementsClause,
Token leftBracket,
List<ClassMember> members,
Token rightBracket)
: super(comment, metadata, name, typeParameters, implementsClause,
leftBracket, members, rightBracket) {
_extendsClause = _becomeParentOf(extendsClause);
_withClause = _becomeParentOf(withClause);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(abstractKeyword)
..add(classKeyword)
..add(_name)
..add(_typeParameters)
..add(_extendsClause)
..add(_withClause)
..add(_implementsClause)
..add(_nativeClause)
..add(leftBracket)
..addAll(members)
..add(rightBracket);
@override
ClassElement get declaredElement => _name?.staticElement as ClassElement;
@deprecated
@override
ClassElement get element => declaredElement;
@override
ExtendsClause get extendsClause => _extendsClause;
@override
void set extendsClause(ExtendsClause extendsClause) {
_extendsClause = _becomeParentOf(extendsClause as ExtendsClauseImpl);
}
@override
Token get firstTokenAfterCommentAndMetadata {
if (abstractKeyword != null) {
return abstractKeyword;
}
return classKeyword;
}
@override
bool get isAbstract => abstractKeyword != null;
@override
NativeClause get nativeClause => _nativeClause;
@override
void set nativeClause(NativeClause nativeClause) {
_nativeClause = _becomeParentOf(nativeClause as NativeClauseImpl);
}
@override
WithClause get withClause => _withClause;
@override
void set withClause(WithClause withClause) {
_withClause = _becomeParentOf(withClause as WithClauseImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitClassDeclaration(this);
@override
ConstructorDeclaration getConstructor(String name) {
int length = _members.length;
for (int i = 0; i < length; i++) {
ClassMember classMember = _members[i];
if (classMember is ConstructorDeclaration) {
ConstructorDeclaration constructor = classMember;
SimpleIdentifier constructorName = constructor.name;
if (name == null && constructorName == null) {
return constructor;
}
if (constructorName != null && constructorName.name == name) {
return constructor;
}
}
}
return null;
}
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_name?.accept(visitor);
_typeParameters?.accept(visitor);
_extendsClause?.accept(visitor);
_withClause?.accept(visitor);
_implementsClause?.accept(visitor);
_nativeClause?.accept(visitor);
members.accept(visitor);
}
}
/// A node that declares a name within the scope of a class.
abstract class ClassMemberImpl extends DeclarationImpl implements ClassMember {
/// Initialize a newly created member of a class. Either or both of the
/// [comment] and [metadata] can be `null` if the member does not have the
/// corresponding attribute.
ClassMemberImpl(CommentImpl comment, List<Annotation> metadata)
: super(comment, metadata);
}
abstract class ClassOrMixinDeclarationImpl
extends NamedCompilationUnitMemberImpl implements ClassOrMixinDeclaration {
/// The type parameters for the class or mixin,
/// or `null` if the declaration does not have any type parameters.
TypeParameterListImpl _typeParameters;
/// The implements clause for the class or mixin,
/// or `null` if the declaration does not implement any interfaces.
ImplementsClauseImpl _implementsClause;
/// The left curly bracket.
Token leftBracket;
/// The members defined by the class or mixin.
NodeList<ClassMember> _members;
/// The right curly bracket.
Token rightBracket;
ClassOrMixinDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
SimpleIdentifierImpl name,
TypeParameterListImpl typeParameters,
ImplementsClauseImpl implementsClause,
this.leftBracket,
List<ClassMember> members,
this.rightBracket)
: super(comment, metadata, name) {
_typeParameters = _becomeParentOf(typeParameters);
_implementsClause = _becomeParentOf(implementsClause);
_members = new NodeListImpl<ClassMember>(this, members);
}
Token get endToken => rightBracket;
ImplementsClause get implementsClause => _implementsClause;
void set implementsClause(ImplementsClause implementsClause) {
_implementsClause =
_becomeParentOf(implementsClause as ImplementsClauseImpl);
}
NodeList<ClassMember> get members => _members;
TypeParameterList get typeParameters => _typeParameters;
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
VariableDeclaration getField(String name) {
int memberLength = _members.length;
for (int i = 0; i < memberLength; i++) {
ClassMember classMember = _members[i];
if (classMember is FieldDeclaration) {
FieldDeclaration fieldDeclaration = classMember;
NodeList<VariableDeclaration> fields =
fieldDeclaration.fields.variables;
int fieldLength = fields.length;
for (int i = 0; i < fieldLength; i++) {
VariableDeclaration field = fields[i];
SimpleIdentifier fieldName = field.name;
if (fieldName != null && name == fieldName.name) {
return field;
}
}
}
}
return null;
}
MethodDeclaration getMethod(String name) {
int length = _members.length;
for (int i = 0; i < length; i++) {
ClassMember classMember = _members[i];
if (classMember is MethodDeclaration) {
MethodDeclaration method = classMember;
SimpleIdentifier methodName = method.name;
if (methodName != null && name == methodName.name) {
return method;
}
}
}
return null;
}
}
/// A class type alias.
///
/// classTypeAlias ::=
/// [SimpleIdentifier] [TypeParameterList]? '=' 'abstract'?
/// mixinApplication
///
/// mixinApplication ::=
/// [TypeName] [WithClause] [ImplementsClause]? ';'
class ClassTypeAliasImpl extends TypeAliasImpl implements ClassTypeAlias {
/// The type parameters for the class, or `null` if the class does not have
/// any type parameters.
TypeParameterListImpl _typeParameters;
/// The token for the '=' separating the name from the definition.
@override
Token equals;
/// The token for the 'abstract' keyword, or `null` if this is not defining an
/// abstract class.
@override
Token abstractKeyword;
/// The name of the superclass of the class being declared.
TypeNameImpl _superclass;
/// The with clause for this class.
WithClauseImpl _withClause;
/// The implements clause for this class, or `null` if there is no implements
/// clause.
ImplementsClauseImpl _implementsClause;
/// Initialize a newly created class type alias. Either or both of the
/// [comment] and [metadata] can be `null` if the class type alias does not
/// have the corresponding attribute. The [typeParameters] can be `null` if
/// the class does not have any type parameters. The [abstractKeyword] can be
/// `null` if the class is not abstract. The [implementsClause] can be `null`
/// if the class does not implement any interfaces.
ClassTypeAliasImpl(
CommentImpl comment,
List<Annotation> metadata,
Token keyword,
SimpleIdentifierImpl name,
TypeParameterListImpl typeParameters,
this.equals,
this.abstractKeyword,
TypeNameImpl superclass,
WithClauseImpl withClause,
ImplementsClauseImpl implementsClause,
Token semicolon)
: super(comment, metadata, keyword, name, semicolon) {
_typeParameters = _becomeParentOf(typeParameters);
_superclass = _becomeParentOf(superclass);
_withClause = _becomeParentOf(withClause);
_implementsClause = _becomeParentOf(implementsClause);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(typedefKeyword)
..add(_name)
..add(_typeParameters)
..add(equals)
..add(abstractKeyword)
..add(_superclass)
..add(_withClause)
..add(_implementsClause)
..add(semicolon);
@override
ClassElement get declaredElement => _name?.staticElement as ClassElement;
@deprecated
@override
ClassElement get element => declaredElement;
@override
Token get firstTokenAfterCommentAndMetadata {
if (abstractKeyword != null) {
return abstractKeyword;
}
return typedefKeyword;
}
@override
ImplementsClause get implementsClause => _implementsClause;
@override
void set implementsClause(ImplementsClause implementsClause) {
_implementsClause =
_becomeParentOf(implementsClause as ImplementsClauseImpl);
}
@override
bool get isAbstract => abstractKeyword != null;
@override
TypeName get superclass => _superclass;
@override
void set superclass(TypeName superclass) {
_superclass = _becomeParentOf(superclass as TypeNameImpl);
}
@override
TypeParameterList get typeParameters => _typeParameters;
@override
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
WithClause get withClause => _withClause;
@override
void set withClause(WithClause withClause) {
_withClause = _becomeParentOf(withClause as WithClauseImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitClassTypeAlias(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_name?.accept(visitor);
_typeParameters?.accept(visitor);
_superclass?.accept(visitor);
_withClause?.accept(visitor);
_implementsClause?.accept(visitor);
}
}
abstract class CollectionElementImpl extends AstNodeImpl
implements CollectionElement {}
/// A combinator associated with an import or export directive.
///
/// combinator ::=
/// [HideCombinator]
/// | [ShowCombinator]
abstract class CombinatorImpl extends AstNodeImpl implements Combinator {
/// The 'hide' or 'show' keyword specifying what kind of processing is to be
/// done on the names.
@override
Token keyword;
/// Initialize a newly created combinator.
CombinatorImpl(this.keyword);
@override
Token get beginToken => keyword;
}
/// A comment within the source code.
///
/// comment ::=
/// endOfLineComment
/// | blockComment
/// | documentationComment
///
/// endOfLineComment ::=
/// '//' (CHARACTER - EOL)* EOL
///
/// blockComment ::=
/// '/ *' CHARACTER* '*/'
///
/// documentationComment ::=
/// '/ **' (CHARACTER | [CommentReference])* '*/'
/// | ('///' (CHARACTER - EOL)* EOL)+
class CommentImpl extends AstNodeImpl implements Comment {
/// The tokens representing the comment.
@override
final List<Token> tokens;
/// The type of the comment.
final CommentType _type;
/// The references embedded within the documentation comment. This list will
/// be empty unless this is a documentation comment that has references embedded
/// within it.
NodeList<CommentReference> _references;
/// Initialize a newly created comment. The list of [tokens] must contain at
/// least one token. The [_type] is the type of the comment. The list of
/// [references] can be empty if the comment does not contain any embedded
/// references.
CommentImpl(this.tokens, this._type, List<CommentReference> references) {
_references = new NodeListImpl<CommentReference>(this, references);
}
@override
Token get beginToken => tokens[0];
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..addAll(tokens);
@override
Token get endToken => tokens[tokens.length - 1];
@override
bool get isBlock => _type == CommentType.BLOCK;
@override
bool get isDocumentation => _type == CommentType.DOCUMENTATION;
@override
bool get isEndOfLine => _type == CommentType.END_OF_LINE;
@override
NodeList<CommentReference> get references => _references;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitComment(this);
@override
void visitChildren(AstVisitor visitor) {
_references.accept(visitor);
}
/// Create a block comment consisting of the given [tokens].
static Comment createBlockComment(List<Token> tokens) =>
new CommentImpl(tokens, CommentType.BLOCK, null);
/// Create a documentation comment consisting of the given [tokens].
static Comment createDocumentationComment(List<Token> tokens) =>
new CommentImpl(
tokens, CommentType.DOCUMENTATION, new List<CommentReference>());
/// Create a documentation comment consisting of the given [tokens] and having
/// the given [references] embedded within it.
static Comment createDocumentationCommentWithReferences(
List<Token> tokens, List<CommentReference> references) =>
new CommentImpl(tokens, CommentType.DOCUMENTATION, references);
/// Create an end-of-line comment consisting of the given [tokens].
static Comment createEndOfLineComment(List<Token> tokens) =>
new CommentImpl(tokens, CommentType.END_OF_LINE, null);
}
/// A reference to a Dart element that is found within a documentation comment.
///
/// commentReference ::=
/// '[' 'new'? [Identifier] ']'
class CommentReferenceImpl extends AstNodeImpl implements CommentReference {
/// The token representing the 'new' keyword, or `null` if there was no 'new'
/// keyword.
@override
Token newKeyword;
/// The identifier being referenced.
IdentifierImpl _identifier;
/// Initialize a newly created reference to a Dart element. The [newKeyword]
/// can be `null` if the reference is not to a constructor.
CommentReferenceImpl(this.newKeyword, IdentifierImpl identifier) {
_identifier = _becomeParentOf(identifier);
}
@override
Token get beginToken => newKeyword ?? _identifier.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(newKeyword)..add(_identifier);
@override
Token get endToken => _identifier.endToken;
@override
Identifier get identifier => _identifier;
@override
void set identifier(Identifier identifier) {
_identifier = _becomeParentOf(identifier as IdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitCommentReference(this);
@override
void visitChildren(AstVisitor visitor) {
_identifier?.accept(visitor);
}
}
/// The possible types of comments that are recognized by the parser.
class CommentType {
/// A block comment.
static const CommentType BLOCK = const CommentType('BLOCK');
/// A documentation comment.
static const CommentType DOCUMENTATION = const CommentType('DOCUMENTATION');
/// An end-of-line comment.
static const CommentType END_OF_LINE = const CommentType('END_OF_LINE');
/// The name of the comment type.
final String name;
/// Initialize a newly created comment type to have the given [name].
const CommentType(this.name);
@override
String toString() => name;
}
/// A compilation unit.
///
/// While the grammar restricts the order of the directives and declarations
/// within a compilation unit, this class does not enforce those restrictions.
/// In particular, the children of a compilation unit will be visited in lexical
/// order even if lexical order does not conform to the restrictions of the
/// grammar.
///
/// compilationUnit ::=
/// directives declarations
///
/// directives ::=
/// [ScriptTag]? [LibraryDirective]? namespaceDirective* [PartDirective]*
/// | [PartOfDirective]
///
/// namespaceDirective ::=
/// [ImportDirective]
/// | [ExportDirective]
///
/// declarations ::=
/// [CompilationUnitMember]*
class CompilationUnitImpl extends AstNodeImpl implements CompilationUnit {
/// The first token in the token stream that was parsed to form this
/// compilation unit.
@override
Token beginToken;
/// The script tag at the beginning of the compilation unit, or `null` if
/// there is no script tag in this compilation unit.
ScriptTagImpl _scriptTag;
/// The directives contained in this compilation unit.
NodeList<Directive> _directives;
/// The declarations contained in this compilation unit.
NodeList<CompilationUnitMember> _declarations;
/// The last token in the token stream that was parsed to form this
/// compilation unit. This token should always have a type of [TokenType.EOF].
@override
Token endToken;
/// The element associated with this compilation unit, or `null` if the AST
/// structure has not been resolved.
@override
CompilationUnitElement declaredElement;
/// The line information for this compilation unit.
@override
LineInfo lineInfo;
/// ?
// TODO(brianwilkerson) Remove this field. It is never read, only written.
Map<int, AstNode> localDeclarations;
/// Additional information about local variables that are declared within this
/// compilation unit but outside any function body, or `null` if resolution
/// has not yet been performed.
LocalVariableInfo localVariableInfo = new LocalVariableInfo();
@override
final FeatureSet featureSet;
/// Initialize a newly created compilation unit to have the given directives
/// and declarations. The [scriptTag] can be `null` if there is no script tag
/// in the compilation unit. The list of [directives] can be `null` if there
/// are no directives in the compilation unit. The list of [declarations] can
/// be `null` if there are no declarations in the compilation unit.
CompilationUnitImpl(
this.beginToken,
ScriptTagImpl scriptTag,
List<Directive> directives,
List<CompilationUnitMember> declarations,
this.endToken,
this.featureSet) {
_scriptTag = _becomeParentOf(scriptTag);
_directives = new NodeListImpl<Directive>(this, directives);
_declarations = new NodeListImpl<CompilationUnitMember>(this, declarations);
}
@override
Iterable<SyntacticEntity> get childEntities {
ChildEntities result = new ChildEntities()..add(_scriptTag);
if (_directivesAreBeforeDeclarations) {
result..addAll(_directives)..addAll(_declarations);
} else {
result.addAll(sortedDirectivesAndDeclarations);
}
return result;
}
@override
NodeList<CompilationUnitMember> get declarations => _declarations;
@override
NodeList<Directive> get directives => _directives;
@deprecated
@override
CompilationUnitElement get element => declaredElement;
@override
set element(CompilationUnitElement element) {
declaredElement = element;
}
@override
int get length {
Token endToken = this.endToken;
if (endToken == null) {
return 0;
}
return endToken.offset + endToken.length;
}
@override
int get offset => 0;
@override
ScriptTag get scriptTag => _scriptTag;
@override
void set scriptTag(ScriptTag scriptTag) {
_scriptTag = _becomeParentOf(scriptTag as ScriptTagImpl);
}
@override
List<AstNode> get sortedDirectivesAndDeclarations {
return <AstNode>[]
..addAll(_directives)
..addAll(_declarations)
..sort(AstNode.LEXICAL_ORDER);
}
/// Return `true` if all of the directives are lexically before any
/// declarations.
bool get _directivesAreBeforeDeclarations {
if (_directives.isEmpty || _declarations.isEmpty) {
return true;
}
Directive lastDirective = _directives[_directives.length - 1];
CompilationUnitMember firstDeclaration = _declarations[0];
return lastDirective.offset < firstDeclaration.offset;
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitCompilationUnit(this);
bool isPotentiallyMutatedInClosure(VariableElement variable) {
if (localVariableInfo == null) {
throw new StateError('Resolution has not yet been performed');
}
return localVariableInfo.potentiallyMutatedInClosure.contains(variable);
}
bool isPotentiallyMutatedInScope(VariableElement variable) {
if (localVariableInfo == null) {
throw new StateError('Resolution has not yet been performed');
}
return localVariableInfo.potentiallyMutatedInScope.contains(variable);
}
@override
void visitChildren(AstVisitor visitor) {
_scriptTag?.accept(visitor);
if (_directivesAreBeforeDeclarations) {
_directives.accept(visitor);
_declarations.accept(visitor);
} else {
List<AstNode> sortedMembers = sortedDirectivesAndDeclarations;
int length = sortedMembers.length;
for (int i = 0; i < length; i++) {
AstNode child = sortedMembers[i];
child.accept(visitor);
}
}
}
}
/// A node that declares one or more names within the scope of a compilation
/// unit.
///
/// compilationUnitMember ::=
/// [ClassDeclaration]
/// | [MixinDeclaration]
/// | [ExtensionDeclaration]
/// | [EnumDeclaration]
/// | [TypeAlias]
/// | [FunctionDeclaration]
/// | [TopLevelVariableDeclaration]
abstract class CompilationUnitMemberImpl extends DeclarationImpl
implements CompilationUnitMember {
/// Initialize a newly created generic compilation unit member. Either or both
/// of the [comment] and [metadata] can be `null` if the member does not have
/// the corresponding attribute.
CompilationUnitMemberImpl(CommentImpl comment, List<Annotation> metadata)
: super(comment, metadata);
}
/// A conditional expression.
///
/// conditionalExpression ::=
/// [Expression] '?' [Expression] ':' [Expression]
class ConditionalExpressionImpl extends ExpressionImpl
implements ConditionalExpression {
/// The condition used to determine which of the expressions is executed next.
ExpressionImpl _condition;
/// The token used to separate the condition from the then expression.
@override
Token question;
/// The expression that is executed if the condition evaluates to `true`.
ExpressionImpl _thenExpression;
/// The token used to separate the then expression from the else expression.
@override
Token colon;
/// The expression that is executed if the condition evaluates to `false`.
ExpressionImpl _elseExpression;
/// Initialize a newly created conditional expression.
ConditionalExpressionImpl(
ExpressionImpl condition,
this.question,
ExpressionImpl thenExpression,
this.colon,
ExpressionImpl elseExpression) {
_condition = _becomeParentOf(condition);
_thenExpression = _becomeParentOf(thenExpression);
_elseExpression = _becomeParentOf(elseExpression);
}
@override
Token get beginToken => _condition.beginToken;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_condition)
..add(question)
..add(_thenExpression)
..add(colon)
..add(_elseExpression);
@override
Expression get condition => _condition;
@override
void set condition(Expression expression) {
_condition = _becomeParentOf(expression as ExpressionImpl);
}
@override
Expression get elseExpression => _elseExpression;
@override
void set elseExpression(Expression expression) {
_elseExpression = _becomeParentOf(expression as ExpressionImpl);
}
@override
Token get endToken => _elseExpression.endToken;
@override
Precedence get precedence => Precedence.conditional;
@override
Expression get thenExpression => _thenExpression;
@override
void set thenExpression(Expression expression) {
_thenExpression = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitConditionalExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_condition?.accept(visitor);
_thenExpression?.accept(visitor);
_elseExpression?.accept(visitor);
}
}
/// A configuration in either an import or export directive.
///
/// configuration ::=
/// 'if' '(' test ')' uri
///
/// test ::=
/// dottedName ('==' stringLiteral)?
///
/// dottedName ::=
/// identifier ('.' identifier)*
class ConfigurationImpl extends AstNodeImpl implements Configuration {
@override
Token ifKeyword;
@override
Token leftParenthesis;
DottedNameImpl _name;
@override
Token equalToken;
StringLiteralImpl _value;
@override
Token rightParenthesis;
StringLiteralImpl _uri;
@override
Source uriSource;
ConfigurationImpl(
this.ifKeyword,
this.leftParenthesis,
DottedNameImpl name,
this.equalToken,
StringLiteralImpl value,
this.rightParenthesis,
StringLiteralImpl libraryUri) {
_name = _becomeParentOf(name);
_value = _becomeParentOf(value);
_uri = _becomeParentOf(libraryUri);
}
@override
Token get beginToken => ifKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(ifKeyword)
..add(leftParenthesis)
..add(_name)
..add(equalToken)
..add(_value)
..add(rightParenthesis)
..add(_uri);
@override
Token get endToken => _uri.endToken;
@deprecated
@override
StringLiteral get libraryUri => _uri;
@deprecated
@override
void set libraryUri(StringLiteral libraryUri) {
_uri = _becomeParentOf(libraryUri as StringLiteralImpl);
}
@override
DottedName get name => _name;
@override
void set name(DottedName name) {
_name = _becomeParentOf(name as DottedNameImpl);
}
@override
StringLiteral get uri => _uri;
@override
void set uri(StringLiteral uri) {
_uri = _becomeParentOf(uri as StringLiteralImpl);
}
@override
StringLiteral get value => _value;
@override
void set value(StringLiteral value) {
_value = _becomeParentOf(value as StringLiteralImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitConfiguration(this);
@override
void visitChildren(AstVisitor visitor) {
_name?.accept(visitor);
_value?.accept(visitor);
_uri?.accept(visitor);
}
}
/// An error listener that only records whether any constant related errors have
/// been reported.
class ConstantAnalysisErrorListener extends AnalysisErrorListener {
/// A flag indicating whether any constant related errors have been reported
/// to this listener.
bool hasConstError = false;
@override
void onError(AnalysisError error) {
ErrorCode errorCode = error.errorCode;
if (errorCode is CompileTimeErrorCode) {
switch (errorCode) {
case CompileTimeErrorCode
.CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST:
case CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL:
case CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_INT:
case CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING:
case CompileTimeErrorCode.CONST_EVAL_TYPE_INT:
case CompileTimeErrorCode.CONST_EVAL_TYPE_NUM:
case CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION:
case CompileTimeErrorCode.CONST_EVAL_THROWS_IDBZE:
case CompileTimeErrorCode.CONST_WITH_NON_CONST:
case CompileTimeErrorCode.CONST_WITH_NON_CONSTANT_ARGUMENT:
case CompileTimeErrorCode.CONST_WITH_TYPE_PARAMETERS:
case CompileTimeErrorCode.INVALID_CONSTANT:
case CompileTimeErrorCode.MISSING_CONST_IN_LIST_LITERAL:
case CompileTimeErrorCode.MISSING_CONST_IN_MAP_LITERAL:
case CompileTimeErrorCode.MISSING_CONST_IN_SET_LITERAL:
hasConstError = true;
}
}
}
}
/// A constructor declaration.
///
/// constructorDeclaration ::=
/// constructorSignature [FunctionBody]?
/// | constructorName formalParameterList ':' 'this'
/// ('.' [SimpleIdentifier])? arguments
///
/// constructorSignature ::=
/// 'external'? constructorName formalParameterList initializerList?
/// | 'external'? 'factory' factoryName formalParameterList
/// initializerList?
/// | 'external'? 'const' constructorName formalParameterList
/// initializerList?
///
/// constructorName ::=
/// [SimpleIdentifier] ('.' [SimpleIdentifier])?
///
/// factoryName ::=
/// [Identifier] ('.' [SimpleIdentifier])?
///
/// initializerList ::=
/// ':' [ConstructorInitializer] (',' [ConstructorInitializer])*
class ConstructorDeclarationImpl extends ClassMemberImpl
implements ConstructorDeclaration {
/// The token for the 'external' keyword, or `null` if the constructor is not
/// external.
@override
Token externalKeyword;
/// The token for the 'const' keyword, or `null` if the constructor is not a
/// const constructor.
@override
Token constKeyword;
/// The token for the 'factory' keyword, or `null` if the constructor is not a
/// factory constructor.
@override
Token factoryKeyword;
/// The type of object being created. This can be different than the type in
/// which the constructor is being declared if the constructor is the
/// implementation of a factory constructor.
IdentifierImpl _returnType;
/// The token for the period before the constructor name, or `null` if the
/// constructor being declared is unnamed.
@override
Token period;
/// The name of the constructor, or `null` if the constructor being declared
/// is unnamed.
SimpleIdentifierImpl _name;
/// The parameters associated with the constructor.
FormalParameterListImpl _parameters;
/// The token for the separator (colon or equals) before the initializer list
/// or redirection, or `null` if there are no initializers.
@override
Token separator;
/// The initializers associated with the constructor.
NodeList<ConstructorInitializer> _initializers;
/// The name of the constructor to which this constructor will be redirected,
/// or `null` if this is not a redirecting factory constructor.
ConstructorNameImpl _redirectedConstructor;
/// The body of the constructor, or `null` if the constructor does not have a
/// body.
FunctionBodyImpl _body;
/// The element associated with this constructor, or `null` if the AST
/// structure has not been resolved or if this constructor could not be
/// resolved.
@override
ConstructorElement declaredElement;
/// Initialize a newly created constructor declaration. The [externalKeyword]
/// can be `null` if the constructor is not external. Either or both of the
/// [comment] and [metadata] can be `null` if the constructor does not have
/// the corresponding attribute. The [constKeyword] can be `null` if the
/// constructor cannot be used to create a constant. The [factoryKeyword] can
/// be `null` if the constructor is not a factory. The [period] and [name] can
/// both be `null` if the constructor is not a named constructor. The
/// [separator] can be `null` if the constructor does not have any
/// initializers and does not redirect to a different constructor. The list of
/// [initializers] can be `null` if the constructor does not have any
/// initializers. The [redirectedConstructor] can be `null` if the constructor
/// does not redirect to a different constructor. The [body] can be `null` if
/// the constructor does not have a body.
ConstructorDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
this.externalKeyword,
this.constKeyword,
this.factoryKeyword,
IdentifierImpl returnType,
this.period,
SimpleIdentifierImpl name,
FormalParameterListImpl parameters,
this.separator,
List<ConstructorInitializer> initializers,
ConstructorNameImpl redirectedConstructor,
FunctionBodyImpl body)
: super(comment, metadata) {
_returnType = _becomeParentOf(returnType);
_name = _becomeParentOf(name);
_parameters = _becomeParentOf(parameters);
_initializers =
new NodeListImpl<ConstructorInitializer>(this, initializers);
_redirectedConstructor = _becomeParentOf(redirectedConstructor);
_body = _becomeParentOf(body);
}
@override
FunctionBody get body => _body;
@override
void set body(FunctionBody functionBody) {
_body = _becomeParentOf(functionBody as FunctionBodyImpl);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(externalKeyword)
..add(constKeyword)
..add(factoryKeyword)
..add(_returnType)
..add(period)
..add(_name)
..add(_parameters)
..add(separator)
..addAll(initializers)
..add(_redirectedConstructor)
..add(_body);
@deprecated
@override
ConstructorElement get element => declaredElement;
@deprecated
@override
set element(ConstructorElement element) {
declaredElement = element;
}
@override
Token get endToken {
if (_body != null) {
return _body.endToken;
} else if (_initializers.isNotEmpty) {
return _initializers.endToken;
}
return _parameters.endToken;
}
@override
Token get firstTokenAfterCommentAndMetadata {
Token leftMost =
Token.lexicallyFirst([externalKeyword, constKeyword, factoryKeyword]);
if (leftMost != null) {
return leftMost;
}
return _returnType.beginToken;
}
@override
NodeList<ConstructorInitializer> get initializers => _initializers;
@override
SimpleIdentifier get name => _name;
@override
void set name(SimpleIdentifier identifier) {
_name = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
FormalParameterList get parameters => _parameters;
@override
void set parameters(FormalParameterList parameters) {
_parameters = _becomeParentOf(parameters as FormalParameterListImpl);
}
@override
ConstructorName get redirectedConstructor => _redirectedConstructor;
@override
void set redirectedConstructor(ConstructorName redirectedConstructor) {
_redirectedConstructor =
_becomeParentOf(redirectedConstructor as ConstructorNameImpl);
}
@override
Identifier get returnType => _returnType;
@override
void set returnType(Identifier typeName) {
_returnType = _becomeParentOf(typeName as IdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitConstructorDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_returnType?.accept(visitor);
_name?.accept(visitor);
_parameters?.accept(visitor);
_initializers.accept(visitor);
_redirectedConstructor?.accept(visitor);
_body?.accept(visitor);
}
}
/// The initialization of a field within a constructor's initialization list.
///
/// fieldInitializer ::=
/// ('this' '.')? [SimpleIdentifier] '=' [Expression]
class ConstructorFieldInitializerImpl extends ConstructorInitializerImpl
implements ConstructorFieldInitializer {
/// The token for the 'this' keyword, or `null` if there is no 'this' keyword.
@override
Token thisKeyword;
/// The token for the period after the 'this' keyword, or `null` if there is
/// no'this' keyword.
@override
Token period;
/// The name of the field being initialized.
SimpleIdentifierImpl _fieldName;
/// The token for the equal sign between the field name and the expression.
@override
Token equals;
/// The expression computing the value to which the field will be initialized.
ExpressionImpl _expression;
/// Initialize a newly created field initializer to initialize the field with
/// the given name to the value of the given expression. The [thisKeyword] and
/// [period] can be `null` if the 'this' keyword was not specified.
ConstructorFieldInitializerImpl(this.thisKeyword, this.period,
SimpleIdentifierImpl fieldName, this.equals, ExpressionImpl expression) {
_fieldName = _becomeParentOf(fieldName);
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken {
if (thisKeyword != null) {
return thisKeyword;
}
return _fieldName.beginToken;
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(thisKeyword)
..add(period)
..add(_fieldName)
..add(equals)
..add(_expression);
@override
Token get endToken => _expression.endToken;
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
SimpleIdentifier get fieldName => _fieldName;
@override
void set fieldName(SimpleIdentifier identifier) {
_fieldName = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitConstructorFieldInitializer(this);
@override
void visitChildren(AstVisitor visitor) {
_fieldName?.accept(visitor);
_expression?.accept(visitor);
}
}
/// A node that can occur in the initializer list of a constructor declaration.
///
/// constructorInitializer ::=
/// [SuperConstructorInvocation]
/// | [ConstructorFieldInitializer]
/// | [RedirectingConstructorInvocation]
abstract class ConstructorInitializerImpl extends AstNodeImpl
implements ConstructorInitializer {}
/// The name of the constructor.
///
/// constructorName ::=
/// type ('.' identifier)?
class ConstructorNameImpl extends AstNodeImpl implements ConstructorName {
/// The name of the type defining the constructor.
TypeNameImpl _type;
/// The token for the period before the constructor name, or `null` if the
/// specified constructor is the unnamed constructor.
@override
Token period;
/// The name of the constructor, or `null` if the specified constructor is the
/// unnamed constructor.
SimpleIdentifierImpl _name;
/// The element associated with this constructor name based on static type
/// information, or `null` if the AST structure has not been resolved or if
/// this constructor name could not be resolved.
@override
ConstructorElement staticElement;
/// Initialize a newly created constructor name. The [period] and [name] can
/// be`null` if the constructor being named is the unnamed constructor.
ConstructorNameImpl(
TypeNameImpl type, this.period, SimpleIdentifierImpl name) {
_type = _becomeParentOf(type);
_name = _becomeParentOf(name);
}
@override
Token get beginToken => _type.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_type)..add(period)..add(_name);
@override
Token get endToken {
if (_name != null) {
return _name.endToken;
}
return _type.endToken;
}
@override
SimpleIdentifier get name => _name;
@override
void set name(SimpleIdentifier name) {
_name = _becomeParentOf(name as SimpleIdentifierImpl);
}
@override
TypeName get type => _type;
@override
void set type(TypeName type) {
_type = _becomeParentOf(type as TypeNameImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitConstructorName(this);
@override
void visitChildren(AstVisitor visitor) {
_type?.accept(visitor);
_name?.accept(visitor);
}
}
/// A continue statement.
///
/// continueStatement ::=
/// 'continue' [SimpleIdentifier]? ';'
class ContinueStatementImpl extends StatementImpl implements ContinueStatement {
/// The token representing the 'continue' keyword.
@override
Token continueKeyword;
/// The label associated with the statement, or `null` if there is no label.
SimpleIdentifierImpl _label;
/// The semicolon terminating the statement.
@override
Token semicolon;
/// The AstNode which this continue statement is continuing to. This will be
/// either a Statement (in the case of continuing a loop) or a SwitchMember
/// (in the case of continuing from one switch case to another). Null if the
/// AST has not yet been resolved or if the target could not be resolved.
/// Note that if the source code has errors, the target may be invalid (e.g.
/// the target may be in an enclosing function).
AstNode target;
/// Initialize a newly created continue statement. The [label] can be `null`
/// if there is no label associated with the statement.
ContinueStatementImpl(
this.continueKeyword, SimpleIdentifierImpl label, this.semicolon) {
_label = _becomeParentOf(label);
}
@override
Token get beginToken => continueKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(continueKeyword)..add(_label)..add(semicolon);
@override
Token get endToken => semicolon;
@override
SimpleIdentifier get label => _label;
@override
void set label(SimpleIdentifier identifier) {
_label = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitContinueStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_label?.accept(visitor);
}
}
/// A node that represents the declaration of one or more names. Each declared
/// name is visible within a name scope.
abstract class DeclarationImpl extends AnnotatedNodeImpl
implements Declaration {
/// Initialize a newly created declaration. Either or both of the [comment]
/// and [metadata] can be `null` if the declaration does not have the
/// corresponding attribute.
DeclarationImpl(CommentImpl comment, List<Annotation> metadata)
: super(comment, metadata);
}
/// The declaration of a single identifier.
///
/// declaredIdentifier ::=
/// [Annotation] finalConstVarOrType [SimpleIdentifier]
class DeclaredIdentifierImpl extends DeclarationImpl
implements DeclaredIdentifier {
/// The token representing either the 'final', 'const' or 'var' keyword, or
/// `null` if no keyword was used.
@override
Token keyword;
/// The name of the declared type of the parameter, or `null` if the parameter
/// does not have a declared type.
TypeAnnotationImpl _type;
/// The name of the variable being declared.
SimpleIdentifierImpl _identifier;
/// Initialize a newly created formal parameter. Either or both of the
/// [comment] and [metadata] can be `null` if the declaration does not have
/// the corresponding attribute. The [keyword] can be `null` if a type name is
/// given. The [type] must be `null` if the keyword is 'var'.
DeclaredIdentifierImpl(CommentImpl comment, List<Annotation> metadata,
this.keyword, TypeAnnotationImpl type, SimpleIdentifierImpl identifier)
: super(comment, metadata) {
_type = _becomeParentOf(type);
_identifier = _becomeParentOf(identifier);
}
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(keyword)..add(_type)..add(_identifier);
@override
LocalVariableElement get declaredElement {
if (_identifier == null) {
return null;
}
return _identifier.staticElement as LocalVariableElement;
}
@override
LocalVariableElement get element => declaredElement;
@override
Token get endToken => _identifier.endToken;
@override
Token get firstTokenAfterCommentAndMetadata {
if (keyword != null) {
return keyword;
} else if (_type != null) {
return _type.beginToken;
}
return _identifier.beginToken;
}
@override
SimpleIdentifier get identifier => _identifier;
@override
void set identifier(SimpleIdentifier identifier) {
_identifier = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
bool get isConst => keyword?.keyword == Keyword.CONST;
@override
bool get isFinal => keyword?.keyword == Keyword.FINAL;
@override
TypeAnnotation get type => _type;
@override
void set type(TypeAnnotation type) {
_type = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitDeclaredIdentifier(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_type?.accept(visitor);
_identifier?.accept(visitor);
}
}
/// A simple identifier that declares a name.
// TODO(rnystrom): Consider making this distinct from [SimpleIdentifier] and
// get rid of all of the:
//
// if (node.inDeclarationContext()) { ... }
//
// code and instead visit this separately. A declaration is semantically pretty
// different from a use, so using the same node type doesn't seem to buy us
// much.
class DeclaredSimpleIdentifier extends SimpleIdentifierImpl {
DeclaredSimpleIdentifier(Token token) : super(token);
@override
bool inDeclarationContext() => true;
}
/// A formal parameter with a default value. There are two kinds of parameters
/// that are both represented by this class: named formal parameters and
/// positional formal parameters.
///
/// defaultFormalParameter ::=
/// [NormalFormalParameter] ('=' [Expression])?
///
/// defaultNamedParameter ::=
/// [NormalFormalParameter] (':' [Expression])?
class DefaultFormalParameterImpl extends FormalParameterImpl
implements DefaultFormalParameter {
/// The formal parameter with which the default value is associated.
NormalFormalParameterImpl _parameter;
/// The kind of this parameter.
@override
ParameterKind kind;
/// The token separating the parameter from the default value, or `null` if
/// there is no default value.
@override
Token separator;
/// The expression computing the default value for the parameter, or `null` if
/// there is no default value.
ExpressionImpl _defaultValue;
/// Initialize a newly created default formal parameter. The [separator] and
/// [defaultValue] can be `null` if there is no default value.
DefaultFormalParameterImpl(NormalFormalParameterImpl parameter, this.kind,
this.separator, ExpressionImpl defaultValue) {
_parameter = _becomeParentOf(parameter);
_defaultValue = _becomeParentOf(defaultValue);
}
@override
Token get beginToken => _parameter.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_parameter)..add(separator)..add(_defaultValue);
@override
Token get covariantKeyword => null;
@override
ParameterElement get declaredElement => _parameter.declaredElement;
@override
Expression get defaultValue => _defaultValue;
@override
void set defaultValue(Expression expression) {
_defaultValue = _becomeParentOf(expression as ExpressionImpl);
}
@override
Token get endToken {
if (_defaultValue != null) {
return _defaultValue.endToken;
}
return _parameter.endToken;
}
@override
SimpleIdentifier get identifier => _parameter.identifier;
@override
bool get isConst => _parameter != null && _parameter.isConst;
@override
bool get isFinal => _parameter != null && _parameter.isFinal;
@override
NodeList<Annotation> get metadata => _parameter.metadata;
@override
NormalFormalParameter get parameter => _parameter;
@override
void set parameter(NormalFormalParameter formalParameter) {
_parameter = _becomeParentOf(formalParameter as NormalFormalParameterImpl);
}
@override
Token get requiredKeyword => null;
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitDefaultFormalParameter(this);
@override
void visitChildren(AstVisitor visitor) {
_parameter?.accept(visitor);
_defaultValue?.accept(visitor);
}
}
/// A node that represents a directive.
///
/// directive ::=
/// [ExportDirective]
/// | [ImportDirective]
/// | [LibraryDirective]
/// | [PartDirective]
/// | [PartOfDirective]
abstract class DirectiveImpl extends AnnotatedNodeImpl implements Directive {
/// The element associated with this directive, or `null` if the AST structure
/// has not been resolved or if this directive could not be resolved.
Element _element;
/// Initialize a newly create directive. Either or both of the [comment] and
/// [metadata] can be `null` if the directive does not have the corresponding
/// attribute.
DirectiveImpl(CommentImpl comment, List<Annotation> metadata)
: super(comment, metadata);
@override
Element get element => _element;
/// Set the element associated with this directive to be the given [element].
void set element(Element element) {
_element = element;
}
}
/// A do statement.
///
/// doStatement ::=
/// 'do' [Statement] 'while' '(' [Expression] ')' ';'
class DoStatementImpl extends StatementImpl implements DoStatement {
/// The token representing the 'do' keyword.
@override
Token doKeyword;
/// The body of the loop.
StatementImpl _body;
/// The token representing the 'while' keyword.
@override
Token whileKeyword;
/// The left parenthesis.
Token leftParenthesis;
/// The condition that determines when the loop will terminate.
ExpressionImpl _condition;
/// The right parenthesis.
@override
Token rightParenthesis;
/// The semicolon terminating the statement.
@override
Token semicolon;
/// Initialize a newly created do loop.
DoStatementImpl(
this.doKeyword,
StatementImpl body,
this.whileKeyword,
this.leftParenthesis,
ExpressionImpl condition,
this.rightParenthesis,
this.semicolon) {
_body = _becomeParentOf(body);
_condition = _becomeParentOf(condition);
}
@override
Token get beginToken => doKeyword;
@override
Statement get body => _body;
@override
void set body(Statement statement) {
_body = _becomeParentOf(statement as StatementImpl);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(doKeyword)
..add(_body)
..add(whileKeyword)
..add(leftParenthesis)
..add(_condition)
..add(rightParenthesis)
..add(semicolon);
@override
Expression get condition => _condition;
@override
void set condition(Expression expression) {
_condition = _becomeParentOf(expression as ExpressionImpl);
}
@override
Token get endToken => semicolon;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitDoStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_body?.accept(visitor);
_condition?.accept(visitor);
}
}
/// A dotted name, used in a configuration within an import or export directive.
///
/// dottedName ::=
/// [SimpleIdentifier] ('.' [SimpleIdentifier])*
class DottedNameImpl extends AstNodeImpl implements DottedName {
/// The components of the identifier.
NodeList<SimpleIdentifier> _components;
/// Initialize a newly created dotted name.
DottedNameImpl(List<SimpleIdentifier> components) {
_components = new NodeListImpl<SimpleIdentifier>(this, components);
}
@override
Token get beginToken => _components.beginToken;
@override
// TODO(paulberry): add "." tokens.
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..addAll(_components);
@override
NodeList<SimpleIdentifier> get components => _components;
@override
Token get endToken => _components.endToken;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitDottedName(this);
@override
void visitChildren(AstVisitor visitor) {
_components.accept(visitor);
}
}
/// A floating point literal expression.
///
/// doubleLiteral ::=
/// decimalDigit+ ('.' decimalDigit*)? exponent?
/// | '.' decimalDigit+ exponent?
///
/// exponent ::=
/// ('e' | 'E') ('+' | '-')? decimalDigit+
class DoubleLiteralImpl extends LiteralImpl implements DoubleLiteral {
/// The token representing the literal.
@override
Token literal;
/// The value of the literal.
@override
double value;
/// Initialize a newly created floating point literal.
DoubleLiteralImpl(this.literal, this.value);
@override
Token get beginToken => literal;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(literal);
@override
Token get endToken => literal;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitDoubleLiteral(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// An empty function body, which can only appear in constructors or abstract
/// methods.
///
/// emptyFunctionBody ::=
/// ';'
class EmptyFunctionBodyImpl extends FunctionBodyImpl
implements EmptyFunctionBody {
/// The token representing the semicolon that marks the end of the function
/// body.
@override
Token semicolon;
/// Initialize a newly created function body.
EmptyFunctionBodyImpl(this.semicolon);
@override
Token get beginToken => semicolon;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(semicolon);
@override
Token get endToken => semicolon;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitEmptyFunctionBody(this);
@override
void visitChildren(AstVisitor visitor) {
// Empty function bodies have no children.
}
}
/// An empty statement.
///
/// emptyStatement ::=
/// ';'
class EmptyStatementImpl extends StatementImpl implements EmptyStatement {
/// The semicolon terminating the statement.
Token semicolon;
/// Initialize a newly created empty statement.
EmptyStatementImpl(this.semicolon);
@override
Token get beginToken => semicolon;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(semicolon);
@override
Token get endToken => semicolon;
@override
bool get isSynthetic => semicolon.isSynthetic;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitEmptyStatement(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// The declaration of an enum constant.
class EnumConstantDeclarationImpl extends DeclarationImpl
implements EnumConstantDeclaration {
/// The name of the constant.
SimpleIdentifierImpl _name;
/// Initialize a newly created enum constant declaration. Either or both of
/// the [comment] and [metadata] can be `null` if the constant does not have
/// the corresponding attribute. (Technically, enum constants cannot have
/// metadata, but we allow it for consistency.)
EnumConstantDeclarationImpl(
CommentImpl comment, List<Annotation> metadata, SimpleIdentifierImpl name)
: super(comment, metadata) {
_name = _becomeParentOf(name);
}
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(_name);
@override
FieldElement get declaredElement => _name?.staticElement as FieldElement;
@deprecated
@override
FieldElement get element => declaredElement;
@override
Token get endToken => _name.endToken;
@override
Token get firstTokenAfterCommentAndMetadata => _name.beginToken;
@override
SimpleIdentifier get name => _name;
@override
void set name(SimpleIdentifier name) {
_name = _becomeParentOf(name as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitEnumConstantDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_name?.accept(visitor);
}
}
/// The declaration of an enumeration.
///
/// enumType ::=
/// metadata 'enum' [SimpleIdentifier] '{' [SimpleIdentifier]
/// (',' [SimpleIdentifier])* (',')? '}'
class EnumDeclarationImpl extends NamedCompilationUnitMemberImpl
implements EnumDeclaration {
/// The 'enum' keyword.
@override
Token enumKeyword;
/// The left curly bracket.
@override
Token leftBracket;
/// The enumeration constants being declared.
NodeList<EnumConstantDeclaration> _constants;
/// The right curly bracket.
@override
Token rightBracket;
/// Initialize a newly created enumeration declaration. Either or both of the
/// [comment] and [metadata] can be `null` if the declaration does not have
/// the corresponding attribute. The list of [constants] must contain at least
/// one value.
EnumDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
this.enumKeyword,
SimpleIdentifierImpl name,
this.leftBracket,
List<EnumConstantDeclaration> constants,
this.rightBracket)
: super(comment, metadata, name) {
_constants = new NodeListImpl<EnumConstantDeclaration>(this, constants);
}
@override
// TODO(brianwilkerson) Add commas?
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(enumKeyword)
..add(_name)
..add(leftBracket)
..addAll(_constants)
..add(rightBracket);
@override
NodeList<EnumConstantDeclaration> get constants => _constants;
@override
ClassElement get declaredElement => _name?.staticElement as ClassElement;
@deprecated
@override
ClassElement get element => declaredElement;
@override
Token get endToken => rightBracket;
@override
Token get firstTokenAfterCommentAndMetadata => enumKeyword;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitEnumDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_name?.accept(visitor);
_constants.accept(visitor);
}
}
/// Ephemeral identifiers are created as needed to mimic the presence of an
/// empty identifier.
class EphemeralIdentifier extends SimpleIdentifierImpl {
EphemeralIdentifier(AstNode parent, int location)
: super(new StringToken(TokenType.IDENTIFIER, "", location)) {
(parent as AstNodeImpl)._becomeParentOf(this);
}
}
/// An export directive.
///
/// exportDirective ::=
/// [Annotation] 'export' [StringLiteral] [Combinator]* ';'
class ExportDirectiveImpl extends NamespaceDirectiveImpl
implements ExportDirective {
/// Initialize a newly created export directive. Either or both of the
/// [comment] and [metadata] can be `null` if the directive does not have the
/// corresponding attribute. The list of [combinators] can be `null` if there
/// are no combinators.
ExportDirectiveImpl(
CommentImpl comment,
List<Annotation> metadata,
Token keyword,
StringLiteralImpl libraryUri,
List<Configuration> configurations,
List<Combinator> combinators,
Token semicolon)
: super(comment, metadata, keyword, libraryUri, configurations,
combinators, semicolon);
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(keyword)
..add(_uri)
..addAll(combinators)
..add(semicolon);
@override
ExportElement get element => super.element as ExportElement;
@override
LibraryElement get uriElement {
if (element != null) {
return element.exportedLibrary;
}
return null;
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitExportDirective(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
combinators.accept(visitor);
}
}
/// A function body consisting of a single expression.
///
/// expressionFunctionBody ::=
/// 'async'? '=>' [Expression] ';'
class ExpressionFunctionBodyImpl extends FunctionBodyImpl
implements ExpressionFunctionBody {
/// The token representing the 'async' keyword, or `null` if there is no such
/// keyword.
@override
Token keyword;
/// The token introducing the expression that represents the body of the
/// function.
@override
Token functionDefinition;
/// The expression representing the body of the function.
ExpressionImpl _expression;
/// The semicolon terminating the statement.
@override
Token semicolon;
/// Initialize a newly created function body consisting of a block of
/// statements. The [keyword] can be `null` if the function body is not an
/// async function body.
ExpressionFunctionBodyImpl(this.keyword, this.functionDefinition,
ExpressionImpl expression, this.semicolon) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken {
if (keyword != null) {
return keyword;
}
return functionDefinition;
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(keyword)
..add(functionDefinition)
..add(_expression)
..add(semicolon);
@override
Token get endToken {
if (semicolon != null) {
return semicolon;
}
return _expression.endToken;
}
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
bool get isAsynchronous => keyword != null;
@override
bool get isSynchronous => keyword == null;
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitExpressionFunctionBody(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// A node that represents an expression.
///
/// expression ::=
/// [AssignmentExpression]
/// | [ConditionalExpression] cascadeSection*
/// | [ThrowExpression]
abstract class ExpressionImpl extends AstNodeImpl
implements CollectionElementImpl, Expression {
/// The static type of this expression, or `null` if the AST structure has not
/// been resolved.
@override
DartType staticType;
/// Return the best parameter element information available for this
/// expression. If type propagation was able to find a better parameter
/// element than static analysis, that type will be returned. Otherwise, the
/// result of static analysis will be returned.
@override
@deprecated
ParameterElement get bestParameterElement => staticParameterElement;
@override
@deprecated
DartType get bestType => staticType ?? DynamicTypeImpl.instance;
/// An expression _e_ is said to _occur in a constant context_,
/// * if _e_ is an element of a constant list literal, or a key or value of an
/// entry of a constant map literal.
/// * if _e_ is an actual argument of a constant object expression or of a
/// metadata annotation.
/// * if _e_ is the initializing expression of a constant variable
/// declaration.
/// * if _e_ is a switch case expression.
/// * if _e_ is an immediate subexpression of an expression _e1_ which occurs
/// in a constant context, unless _e1_ is a `throw` expression or a function
/// literal.
///
/// This roughly means that everything which is inside a syntactically
/// constant expression is in a constant context. A `throw` expression is
/// currently not allowed in a constant expression, but extensions affecting
/// that status may be considered. A similar situation arises for function
/// literals.
///
/// Note that the default value of an optional formal parameter is _not_ a
/// constant context. This choice reserves some freedom to modify the
/// semantics of default values.
bool get inConstantContext {
AstNode child = this;
while (child is Expression ||
child is ArgumentList ||
child is MapLiteralEntry ||
child is SpreadElement ||
child is IfElement ||
child is ForElement) {
AstNode parent = child.parent;
if (parent is TypedLiteralImpl && parent.constKeyword != null) {
// Inside an explicitly `const` list or map literal.
return true;
} else if (parent is InstanceCreationExpression &&
parent.keyword?.keyword == Keyword.CONST) {
// Inside an explicitly `const` instance creation expression.
return true;
} else if (parent is Annotation) {
// Inside an annotation.
return true;
} else if (parent is VariableDeclaration) {
AstNode grandParent = parent.parent;
// Inside the initializer for a `const` variable declaration.
return grandParent is VariableDeclarationList &&
grandParent.keyword?.keyword == Keyword.CONST;
} else if (parent is SwitchCase) {
// Inside a switch case.
return true;
}
child = parent;
}
return false;
}
@override
bool get isAssignable => false;
@Deprecated('Use precedence')
@override
Precedence get precedence2 => precedence;
@deprecated
@override
ParameterElement get propagatedParameterElement => null;
@deprecated
@override
DartType get propagatedType => null;
@deprecated
@override
set propagatedType(DartType type) {}
@override
ParameterElement get staticParameterElement {
AstNode parent = this.parent;
if (parent is ArgumentListImpl) {
return parent._getStaticParameterElementFor(this);
} else if (parent is IndexExpressionImpl) {
if (identical(parent.index, this)) {
return parent._staticParameterElementForIndex;
}
} else if (parent is BinaryExpressionImpl) {
if (identical(parent.rightOperand, this)) {
var parameters = parent.staticInvokeType?.parameters;
if (parameters != null && parameters.isNotEmpty) {
return parameters[0];
}
return null;
}
} else if (parent is AssignmentExpressionImpl) {
if (identical(parent.rightHandSide, this)) {
return parent._staticParameterElementForRightHandSide;
}
} else if (parent is PrefixExpressionImpl) {
return parent._staticParameterElementForOperand;
} else if (parent is PostfixExpressionImpl) {
return parent._staticParameterElementForOperand;
}
return null;
}
@override
Expression get unParenthesized => this;
}
/// An expression used as a statement.
///
/// expressionStatement ::=
/// [Expression]? ';'
class ExpressionStatementImpl extends StatementImpl
implements ExpressionStatement {
/// The expression that comprises the statement.
ExpressionImpl _expression;
/// The semicolon terminating the statement, or `null` if the expression is a
/// function expression and therefore isn't followed by a semicolon.
@override
Token semicolon;
/// Initialize a newly created expression statement.
ExpressionStatementImpl(ExpressionImpl expression, this.semicolon) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken => _expression.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_expression)..add(semicolon);
@override
Token get endToken {
if (semicolon != null) {
return semicolon;
}
return _expression.endToken;
}
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
bool get isSynthetic => _expression.isSynthetic && semicolon.isSynthetic;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitExpressionStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// The "extends" clause in a class declaration.
///
/// extendsClause ::=
/// 'extends' [TypeName]
class ExtendsClauseImpl extends AstNodeImpl implements ExtendsClause {
/// The token representing the 'extends' keyword.
@override
Token extendsKeyword;
/// The name of the class that is being extended.
TypeNameImpl _superclass;
/// Initialize a newly created extends clause.
ExtendsClauseImpl(this.extendsKeyword, TypeNameImpl superclass) {
_superclass = _becomeParentOf(superclass);
}
@override
Token get beginToken => extendsKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(extendsKeyword)..add(_superclass);
@override
Token get endToken => _superclass.endToken;
@override
TypeName get superclass => _superclass;
@override
void set superclass(TypeName name) {
_superclass = _becomeParentOf(name as TypeNameImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitExtendsClause(this);
@override
void visitChildren(AstVisitor visitor) {
_superclass?.accept(visitor);
}
}
/// The declaration of an extension of a type.
///
/// extension ::=
/// 'extension' [SimpleIdentifier] [TypeParameterList]?
/// 'on' [TypeAnnotation] '{' [ClassMember]* '}'
///
/// Clients may not extend, implement or mix-in this class.
class ExtensionDeclarationImpl extends CompilationUnitMemberImpl
implements ExtensionDeclaration {
@override
Token extensionKeyword;
/// The name of the extension, or `null` if the extension does not have a
/// name.
SimpleIdentifierImpl _name;
/// The type parameters for the extension, or `null` if the extension does not
/// have any type parameters.
TypeParameterListImpl _typeParameters;
@override
Token onKeyword;
/// The type that is being extended.
TypeAnnotationImpl _extendedType;
@override
Token leftBracket;
/// The members being added to the extended class.
NodeList<ClassMember> _members;
@override
Token rightBracket;
ExtensionElement _declaredElement;
ExtensionDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
this.extensionKeyword,
SimpleIdentifierImpl name,
TypeParameterListImpl typeParameters,
this.onKeyword,
TypeAnnotationImpl extendedType,
this.leftBracket,
List<ClassMember> members,
this.rightBracket)
: super(comment, metadata) {
_name = _becomeParentOf(name);
_typeParameters = _becomeParentOf(typeParameters);
_extendedType = _becomeParentOf(extendedType);
_members = new NodeListImpl<ClassMember>(this, members);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(extensionKeyword)
..add(name)
..add(typeParameters)
..add(onKeyword)
..add(extendedType)
..add(leftBracket)
..addAll(members)
..add(rightBracket);
@override
ExtensionElement get declaredElement => _declaredElement;
/// Set the element declared by this declaration to the given [element].
set declaredElement(ExtensionElement element) {
_declaredElement = element;
}
@override
ExtensionElement get element => declaredElement;
@override
Token get endToken => rightBracket;
@override
TypeAnnotation get extendedType => _extendedType;
void set extendedType(TypeAnnotation extendedClass) {
_extendedType = _becomeParentOf(extendedClass as TypeAnnotationImpl);
}
@override
Token get firstTokenAfterCommentAndMetadata => extensionKeyword;
@override
NodeList<ClassMember> get members => _members;
@override
SimpleIdentifier get name => _name;
void set name(SimpleIdentifier identifier) {
_name = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
TypeParameterList get typeParameters => _typeParameters;
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitExtensionDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
name?.accept(visitor);
_typeParameters?.accept(visitor);
_extendedType?.accept(visitor);
_members.accept(visitor);
}
}
/// An override to force resolution to choose a member from a specific
/// extension.
///
/// extensionOverride ::=
/// [Identifier] [TypeArgumentList]? [ArgumentList]
class ExtensionOverrideImpl extends ExpressionImpl
implements ExtensionOverride {
/// The list of arguments to the override. In valid code this will contain a
/// single argument, which evaluates to the object being extended.
ArgumentListImpl _argumentList;
/// The name of the extension being selected.
IdentifierImpl _extensionName;
/// The type arguments to be applied to the extension, or `null` if no type
/// arguments were provided.
TypeArgumentListImpl _typeArguments;
@override
List<DartType> typeArgumentTypes;
@override
DartType extendedType;
ExtensionOverrideImpl(IdentifierImpl extensionName,
TypeArgumentListImpl typeArguments, ArgumentListImpl argumentList) {
_extensionName = _becomeParentOf(extensionName);
_typeArguments = _becomeParentOf(typeArguments);
_argumentList = _becomeParentOf(argumentList);
}
@override
ArgumentList get argumentList => _argumentList;
void set argumentList(ArgumentList argumentList) {
_argumentList = _becomeParentOf(argumentList as ArgumentListImpl);
}
@override
Token get beginToken => _extensionName?.beginToken;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_extensionName)
..add(_typeArguments)
..add(_argumentList);
@override
Token get endToken => _argumentList.endToken;
@override
Identifier get extensionName => _extensionName;
void set extensionName(Identifier extensionName) {
_extensionName = _becomeParentOf(extensionName as IdentifierImpl);
}
@override
Precedence get precedence => Precedence.postfix;
@override
ExtensionElement get staticElement => extensionName.staticElement;
@override
TypeArgumentList get typeArguments => _typeArguments;
void set typeArguments(TypeArgumentList typeArguments) {
_typeArguments = _becomeParentOf(typeArguments as TypeArgumentListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) {
return visitor.visitExtensionOverride(this);
}
@override
void visitChildren(AstVisitor visitor) {
_extensionName?.accept(visitor);
_typeArguments?.accept(visitor);
_argumentList?.accept(visitor);
}
}
/// The declaration of one or more fields of the same type.
///
/// fieldDeclaration ::=
/// 'static'? [VariableDeclarationList] ';'
class FieldDeclarationImpl extends ClassMemberImpl implements FieldDeclaration {
/// The 'covariant' keyword, or `null` if the keyword was not used.
@override
Token covariantKeyword;
/// The token representing the 'static' keyword, or `null` if the fields are
/// not static.
@override
Token staticKeyword;
/// The fields being declared.
VariableDeclarationListImpl _fieldList;
/// The semicolon terminating the declaration.
@override
Token semicolon;
/// Initialize a newly created field declaration. Either or both of the
/// [comment] and [metadata] can be `null` if the declaration does not have
/// the corresponding attribute. The [staticKeyword] can be `null` if the
/// field is not a static field.
FieldDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
this.covariantKeyword,
this.staticKeyword,
VariableDeclarationListImpl fieldList,
this.semicolon)
: super(comment, metadata) {
_fieldList = _becomeParentOf(fieldList);
}
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(staticKeyword)..add(_fieldList)..add(semicolon);
@override
Element get declaredElement => null;
@deprecated
@override
Element get element => null;
@override
Token get endToken => semicolon;
@override
VariableDeclarationList get fields => _fieldList;
@override
void set fields(VariableDeclarationList fields) {
_fieldList = _becomeParentOf(fields as VariableDeclarationListImpl);
}
@override
Token get firstTokenAfterCommentAndMetadata {
if (covariantKeyword != null) {
return covariantKeyword;
} else if (staticKeyword != null) {
return staticKeyword;
}
return _fieldList.beginToken;
}
@override
bool get isStatic => staticKeyword != null;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitFieldDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_fieldList?.accept(visitor);
}
}
/// A field formal parameter.
///
/// fieldFormalParameter ::=
/// ('final' [TypeName] | 'const' [TypeName] | 'var' | [TypeName])?
/// 'this' '.' [SimpleIdentifier]
/// ([TypeParameterList]? [FormalParameterList])?
class FieldFormalParameterImpl extends NormalFormalParameterImpl
implements FieldFormalParameter {
/// The token representing either the 'final', 'const' or 'var' keyword, or
/// `null` if no keyword was used.
@override
Token keyword;
/// The name of the declared type of the parameter, or `null` if the parameter
/// does not have a declared type.
TypeAnnotationImpl _type;
/// The token representing the 'this' keyword.
@override
Token thisKeyword;
/// The token representing the period.
@override
Token period;
/// The type parameters associated with the method, or `null` if the method is
/// not a generic method.
TypeParameterListImpl _typeParameters;
/// The parameters of the function-typed parameter, or `null` if this is not a
/// function-typed field formal parameter.
FormalParameterListImpl _parameters;
/// Initialize a newly created formal parameter. Either or both of the
/// [comment] and [metadata] can be `null` if the parameter does not have the
/// corresponding attribute. The [keyword] can be `null` if there is a type.
/// The [type] must be `null` if the keyword is 'var'. The [thisKeyword] and
/// [period] can be `null` if the keyword 'this' was not provided. The
/// [parameters] can be `null` if this is not a function-typed field formal
/// parameter.
FieldFormalParameterImpl(
CommentImpl comment,
List<Annotation> metadata,
Token covariantKeyword,
Token requiredKeyword,
this.keyword,
TypeAnnotationImpl type,
this.thisKeyword,
this.period,
SimpleIdentifierImpl identifier,
TypeParameterListImpl typeParameters,
FormalParameterListImpl parameters)
: super(
comment, metadata, covariantKeyword, requiredKeyword, identifier) {
_type = _becomeParentOf(type);
_typeParameters = _becomeParentOf(typeParameters);
_parameters = _becomeParentOf(parameters);
}
@override
Token get beginToken {
NodeList<Annotation> metadata = this.metadata;
if (metadata.isNotEmpty) {
return metadata.beginToken;
} else if (covariantKeyword != null) {
return covariantKeyword;
} else if (keyword != null) {
return keyword;
} else if (_type != null) {
return _type.beginToken;
}
return thisKeyword;
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(keyword)
..add(_type)
..add(thisKeyword)
..add(period)
..add(identifier)
..add(_parameters);
@override
Token get endToken {
if (_parameters != null) {
return _parameters.endToken;
}
return identifier.endToken;
}
@override
bool get isConst => keyword?.keyword == Keyword.CONST;
@override
bool get isFinal => keyword?.keyword == Keyword.FINAL;
@override
FormalParameterList get parameters => _parameters;
@override
void set parameters(FormalParameterList parameters) {
_parameters = _becomeParentOf(parameters as FormalParameterListImpl);
}
@override
TypeAnnotation get type => _type;
@override
void set type(TypeAnnotation type) {
_type = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
TypeParameterList get typeParameters => _typeParameters;
@override
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitFieldFormalParameter(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_type?.accept(visitor);
identifier?.accept(visitor);
_typeParameters?.accept(visitor);
_parameters?.accept(visitor);
}
}
abstract class ForEachPartsImpl extends ForLoopPartsImpl
implements ForEachParts {
@override
Token inKeyword;
/// The expression evaluated to produce the iterator.
ExpressionImpl _iterable;
/// Initialize a newly created for-each statement whose loop control variable
/// is declared internally (in the for-loop part). The [awaitKeyword] can be
/// `null` if this is not an asynchronous for loop.
ForEachPartsImpl(this.inKeyword, ExpressionImpl iterator) {
_iterable = _becomeParentOf(iterator);
}
@override
Token get beginToken => inKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(inKeyword)..add(_iterable);
@override
Token get endToken => _iterable.endToken;
@override
Expression get iterable => _iterable;
void set iterable(Expression expression) {
_iterable = _becomeParentOf(expression as ExpressionImpl);
}
@override
void visitChildren(AstVisitor visitor) {
_iterable?.accept(visitor);
}
}
class ForEachPartsWithDeclarationImpl extends ForEachPartsImpl
implements ForEachPartsWithDeclaration {
/// The declaration of the loop variable.
DeclaredIdentifierImpl _loopVariable;
/// Initialize a newly created for-each statement whose loop control variable
/// is declared internally (inside the for-loop part).
ForEachPartsWithDeclarationImpl(DeclaredIdentifierImpl loopVariable,
Token inKeyword, ExpressionImpl iterator)
: super(inKeyword, iterator) {
_loopVariable = _becomeParentOf(loopVariable);
}
@override
Token get beginToken => _loopVariable.beginToken;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_loopVariable)
..addAll(super.childEntities);
@override
DeclaredIdentifier get loopVariable => _loopVariable;
void set loopVariable(DeclaredIdentifier variable) {
_loopVariable = _becomeParentOf(variable as DeclaredIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitForEachPartsWithDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
_loopVariable?.accept(visitor);
super.visitChildren(visitor);
}
}
class ForEachPartsWithIdentifierImpl extends ForEachPartsImpl
implements ForEachPartsWithIdentifier {
/// The loop variable.
SimpleIdentifierImpl _identifier;
/// Initialize a newly created for-each statement whose loop control variable
/// is declared externally (outside the for-loop part).
ForEachPartsWithIdentifierImpl(
SimpleIdentifierImpl identifier, Token inKeyword, ExpressionImpl iterator)
: super(inKeyword, iterator) {
_identifier = _becomeParentOf(identifier);
}
@override
Token get beginToken => _identifier.beginToken;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_identifier)
..addAll(super.childEntities);
@override
SimpleIdentifier get identifier => _identifier;
void set identifier(SimpleIdentifier identifier) {
_identifier = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitForEachPartsWithIdentifier(this);
@override
void visitChildren(AstVisitor visitor) {
_identifier?.accept(visitor);
_iterable?.accept(visitor);
}
}
class ForElementImpl extends CollectionElementImpl
with ForMixin
implements ForElement {
/// The body of the loop.
CollectionElementImpl _body;
/// Initialize a newly created for element.
ForElementImpl(
Token awaitKeyword,
Token forKeyword,
Token leftParenthesis,
ForLoopPartsImpl forLoopParts,
Token rightParenthesis,
CollectionElementImpl body) {
this.awaitKeyword = awaitKeyword;
this.forKeyword = forKeyword;
this.leftParenthesis = leftParenthesis;
_forLoopParts = _becomeParentOf(forLoopParts);
this.rightParenthesis = rightParenthesis;
_body = _becomeParentOf(body);
}
@override
CollectionElement get body => _body;
void set body(CollectionElement statement) {
_body = _becomeParentOf(statement as CollectionElementImpl);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..addAll(super.childEntities)
..add(_body);
@override
Token get endToken => _body.endToken;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitForElement(this);
@override
void visitChildren(AstVisitor visitor) {
_forLoopParts?.accept(visitor);
_body?.accept(visitor);
}
}
abstract class ForLoopPartsImpl extends AstNodeImpl implements ForLoopParts {}
/// A node representing a parameter to a function.
///
/// formalParameter ::=
/// [NormalFormalParameter]
/// | [DefaultFormalParameter]
abstract class FormalParameterImpl extends AstNodeImpl
implements FormalParameter {
@override
ParameterElement get declaredElement {
SimpleIdentifier identifier = this.identifier;
if (identifier == null) {
return null;
}
return identifier.staticElement as ParameterElement;
}
@deprecated
@override
ParameterElement get element => declaredElement;
@override
bool get isNamed =>
kind == ParameterKind.NAMED || kind == ParameterKind.NAMED_REQUIRED;
@override
bool get isOptional =>
kind == ParameterKind.NAMED || kind == ParameterKind.POSITIONAL;
@override
bool get isOptionalNamed => kind == ParameterKind.NAMED;
@override
bool get isOptionalPositional => kind == ParameterKind.POSITIONAL;
@override
bool get isPositional =>
kind == ParameterKind.POSITIONAL || kind == ParameterKind.REQUIRED;
@override
bool get isRequired =>
kind == ParameterKind.REQUIRED || kind == ParameterKind.NAMED_REQUIRED;
@override
bool get isRequiredNamed => kind == ParameterKind.NAMED_REQUIRED;
@override
bool get isRequiredPositional => kind == ParameterKind.REQUIRED;
@override
// Overridden to remove the 'deprecated' annotation.
ParameterKind get kind;
}
/// The formal parameter list of a method declaration, function declaration, or
/// function type alias.
///
/// While the grammar requires all optional formal parameters to follow all of
/// the normal formal parameters and at most one grouping of optional formal
/// parameters, this class does not enforce those constraints. All parameters
/// are flattened into a single list, which can have any or all kinds of
/// parameters (normal, named, and positional) in any order.
///
/// formalParameterList ::=
/// '(' ')'
/// | '(' normalFormalParameters (',' optionalFormalParameters)? ')'
/// | '(' optionalFormalParameters ')'
///
/// normalFormalParameters ::=
/// [NormalFormalParameter] (',' [NormalFormalParameter])*
///
/// optionalFormalParameters ::=
/// optionalPositionalFormalParameters
/// | namedFormalParameters
///
/// optionalPositionalFormalParameters ::=
/// '[' [DefaultFormalParameter] (',' [DefaultFormalParameter])* ']'
///
/// namedFormalParameters ::=
/// '{' [DefaultFormalParameter] (',' [DefaultFormalParameter])* '}'
class FormalParameterListImpl extends AstNodeImpl
implements FormalParameterList {
/// The left parenthesis.
@override
Token leftParenthesis;
/// The parameters associated with the method.
NodeList<FormalParameter> _parameters;
/// The left square bracket ('[') or left curly brace ('{') introducing the
/// optional parameters, or `null` if there are no optional parameters.
@override
Token leftDelimiter;
/// The right square bracket (']') or right curly brace ('}') terminating the
/// optional parameters, or `null` if there are no optional parameters.
@override
Token rightDelimiter;
/// The right parenthesis.
@override
Token rightParenthesis;
/// Initialize a newly created parameter list. The list of [parameters] can be
/// `null` if there are no parameters. The [leftDelimiter] and
/// [rightDelimiter] can be `null` if there are no optional parameters.
FormalParameterListImpl(
this.leftParenthesis,
List<FormalParameter> parameters,
this.leftDelimiter,
this.rightDelimiter,
this.rightParenthesis) {
_parameters = new NodeListImpl<FormalParameter>(this, parameters);
}
@override
Token get beginToken => leftParenthesis;
@override
Iterable<SyntacticEntity> get childEntities {
// TODO(paulberry): include commas.
ChildEntities result = new ChildEntities()..add(leftParenthesis);
bool leftDelimiterNeeded = leftDelimiter != null;
int length = _parameters.length;
for (int i = 0; i < length; i++) {
FormalParameter parameter = _parameters[i];
if (leftDelimiterNeeded && leftDelimiter.offset < parameter.offset) {
result.add(leftDelimiter);
leftDelimiterNeeded = false;
}
result.add(parameter);
}
return result..add(rightDelimiter)..add(rightParenthesis);
}
@override
Token get endToken => rightParenthesis;
@override
List<ParameterElement> get parameterElements {
int count = _parameters.length;
List<ParameterElement> types = new List<ParameterElement>(count);
for (int i = 0; i < count; i++) {
types[i] = _parameters[i].declaredElement;
}
return types;
}
@override
NodeList<FormalParameter> get parameters => _parameters;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitFormalParameterList(this);
@override
void visitChildren(AstVisitor visitor) {
_parameters.accept(visitor);
}
}
mixin ForMixin on AstNodeImpl {
Token awaitKeyword;
Token forKeyword;
Token leftParenthesis;
ForLoopPartsImpl _forLoopParts;
Token rightParenthesis;
@override
Token get beginToken => awaitKeyword ?? forKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(awaitKeyword)
..add(forKeyword)
..add(leftParenthesis)
..add(_forLoopParts)
..add(rightParenthesis);
ForLoopParts get forLoopParts => _forLoopParts;
void set forLoopParts(ForLoopParts forLoopParts) {
_forLoopParts = _becomeParentOf(forLoopParts as ForLoopPartsImpl);
}
}
abstract class ForPartsImpl extends ForLoopPartsImpl implements ForParts {
@override
Token leftSeparator;
/// The condition used to determine when to terminate the loop, or `null` if
/// there is no condition.
ExpressionImpl _condition;
@override
Token rightSeparator;
/// The list of expressions run after each execution of the loop body.
NodeList<Expression> _updaters;
/// Initialize a newly created for statement. Either the [variableList] or the
/// [initialization] must be `null`. Either the [condition] and the list of
/// [updaters] can be `null` if the loop does not have the corresponding
/// attribute.
ForPartsImpl(this.leftSeparator, ExpressionImpl condition,
this.rightSeparator, List<Expression> updaters) {
_condition = _becomeParentOf(condition);
_updaters = new NodeListImpl<Expression>(this, updaters);
}
@override
Token get beginToken => leftSeparator;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(leftSeparator)
..add(_condition)
..add(rightSeparator)
..addAll(_updaters);
@override
Expression get condition => _condition;
void set condition(Expression expression) {
_condition = _becomeParentOf(expression as ExpressionImpl);
}
@override
Token get endToken => _updaters?.endToken ?? rightSeparator;
@override
NodeList<Expression> get updaters => _updaters;
@override
void visitChildren(AstVisitor visitor) {
_condition?.accept(visitor);
_updaters.accept(visitor);
}
}
class ForPartsWithDeclarationsImpl extends ForPartsImpl
implements ForPartsWithDeclarations {
/// The declaration of the loop variables, or `null` if there are no
/// variables. Note that a for statement cannot have both a variable list and
/// an initialization expression, but can validly have neither.
VariableDeclarationListImpl _variableList;
/// Initialize a newly created for statement. Both the [condition] and the
/// list of [updaters] can be `null` if the loop does not have the
/// corresponding attribute.
ForPartsWithDeclarationsImpl(
VariableDeclarationListImpl variableList,
Token leftSeparator,
ExpressionImpl condition,
Token rightSeparator,
List<Expression> updaters)
: super(leftSeparator, condition, rightSeparator, updaters) {
_variableList = _becomeParentOf(variableList);
}
@override
Token get beginToken => _variableList?.beginToken ?? super.beginToken;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_variableList)
..addAll(super.childEntities);
@override
VariableDeclarationList get variables => _variableList;
void set variables(VariableDeclarationList variableList) {
_variableList =
_becomeParentOf(variableList as VariableDeclarationListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitForPartsWithDeclarations(this);
@override
void visitChildren(AstVisitor visitor) {
_variableList?.accept(visitor);
super.visitChildren(visitor);
}
}
class ForPartsWithExpressionImpl extends ForPartsImpl
implements ForPartsWithExpression {
/// The initialization expression, or `null` if there is no initialization
/// expression. Note that a for statement cannot have both a variable list and
/// an initialization expression, but can validly have neither.
ExpressionImpl _initialization;
/// Initialize a newly created for statement. Both the [condition] and the
/// list of [updaters] can be `null` if the loop does not have the
/// corresponding attribute.
ForPartsWithExpressionImpl(ExpressionImpl initialization, Token leftSeparator,
ExpressionImpl condition, Token rightSeparator, List<Expression> updaters)
: super(leftSeparator, condition, rightSeparator, updaters) {
_initialization = _becomeParentOf(initialization);
}
@override
Token get beginToken => initialization?.beginToken ?? super.beginToken;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_initialization)
..addAll(super.childEntities);
@override
Expression get initialization => _initialization;
void set initialization(Expression initialization) {
_initialization = _becomeParentOf(initialization as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitForPartsWithExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_initialization?.accept(visitor);
super.visitChildren(visitor);
}
}
class ForStatementImpl extends StatementImpl
with ForMixin
implements ForStatement {
/// The body of the loop.
StatementImpl _body;
/// Initialize a newly created for statement.
ForStatementImpl(
Token awaitKeyword,
Token forKeyword,
Token leftParenthesis,
ForLoopPartsImpl forLoopParts,
Token rightParenthesis,
StatementImpl body) {
this.awaitKeyword = awaitKeyword;
this.forKeyword = forKeyword;
this.leftParenthesis = leftParenthesis;
_forLoopParts = _becomeParentOf(forLoopParts);
this.rightParenthesis = rightParenthesis;
_body = _becomeParentOf(body);
}
ForStatementImpl._();
Statement get body => _body;
void set body(Statement statement) {
_body = _becomeParentOf(statement as StatementImpl);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..addAll(super.childEntities)
..add(_body);
@override
Token get endToken => _body.endToken;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitForStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_forLoopParts?.accept(visitor);
_body?.accept(visitor);
}
}
/// A node representing the body of a function or method.
///
/// functionBody ::=
/// [BlockFunctionBody]
/// | [EmptyFunctionBody]
/// | [ExpressionFunctionBody]
abstract class FunctionBodyImpl extends AstNodeImpl implements FunctionBody {
/// Additional information about local variables and parameters that are
/// declared within this function body or any enclosing function body. `null`
/// if resolution has not yet been performed.
LocalVariableInfo localVariableInfo;
/// Return `true` if this function body is asynchronous.
@override
bool get isAsynchronous => false;
/// Return `true` if this function body is a generator.
@override
bool get isGenerator => false;
/// Return `true` if this function body is synchronous.
@override
bool get isSynchronous => true;
/// Return the token representing the 'async' or 'sync' keyword, or `null` if
/// there is no such keyword.
@override
Token get keyword => null;
/// Return the star following the 'async' or 'sync' keyword, or `null` if
/// there is no star.
@override
Token get star => null;
@override
bool isPotentiallyMutatedInClosure(VariableElement variable) {
if (localVariableInfo == null) {
throw new StateError('Resolution has not yet been performed');
}
return localVariableInfo.potentiallyMutatedInClosure.contains(variable);
}
@override
bool isPotentiallyMutatedInScope(VariableElement variable) {
if (localVariableInfo == null) {
throw new StateError('Resolution has not yet been performed');
}
return localVariableInfo.potentiallyMutatedInScope.contains(variable);
}
}
/// A top-level declaration.
///
/// functionDeclaration ::=
/// 'external' functionSignature
/// | functionSignature [FunctionBody]
///
/// functionSignature ::=
/// [Type]? ('get' | 'set')? [SimpleIdentifier] [FormalParameterList]
class FunctionDeclarationImpl extends NamedCompilationUnitMemberImpl
implements FunctionDeclaration {
/// The token representing the 'external' keyword, or `null` if this is not an
/// external function.
@override
Token externalKeyword;
/// The return type of the function, or `null` if no return type was declared.
TypeAnnotationImpl _returnType;
/// The token representing the 'get' or 'set' keyword, or `null` if this is a
/// function declaration rather than a property declaration.
@override
Token propertyKeyword;
/// The function expression being wrapped.
FunctionExpressionImpl _functionExpression;
/// Initialize a newly created function declaration. Either or both of the
/// [comment] and [metadata] can be `null` if the function does not have the
/// corresponding attribute. The [externalKeyword] can be `null` if the
/// function is not an external function. The [returnType] can be `null` if no
/// return type was specified. The [propertyKeyword] can be `null` if the
/// function is neither a getter or a setter.
FunctionDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
this.externalKeyword,
TypeAnnotationImpl returnType,
this.propertyKeyword,
SimpleIdentifierImpl name,
FunctionExpressionImpl functionExpression)
: super(comment, metadata, name) {
_returnType = _becomeParentOf(returnType);
_functionExpression = _becomeParentOf(functionExpression);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(externalKeyword)
..add(_returnType)
..add(propertyKeyword)
..add(_name)
..add(_functionExpression);
@override
ExecutableElement get declaredElement =>
_name?.staticElement as ExecutableElement;
@deprecated
@override
ExecutableElement get element => declaredElement;
@override
Token get endToken => _functionExpression.endToken;
@override
Token get firstTokenAfterCommentAndMetadata {
if (externalKeyword != null) {
return externalKeyword;
} else if (_returnType != null) {
return _returnType.beginToken;
} else if (propertyKeyword != null) {
return propertyKeyword;
} else if (_name != null) {
return _name.beginToken;
}
return _functionExpression.beginToken;
}
@override
FunctionExpression get functionExpression => _functionExpression;
@override
void set functionExpression(FunctionExpression functionExpression) {
_functionExpression =
_becomeParentOf(functionExpression as FunctionExpressionImpl);
}
@override
bool get isGetter => propertyKeyword?.keyword == Keyword.GET;
@override
bool get isSetter => propertyKeyword?.keyword == Keyword.SET;
@override
TypeAnnotation get returnType => _returnType;
@override
void set returnType(TypeAnnotation type) {
_returnType = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitFunctionDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_returnType?.accept(visitor);
_name?.accept(visitor);
_functionExpression?.accept(visitor);
}
}
/// A [FunctionDeclaration] used as a statement.
class FunctionDeclarationStatementImpl extends StatementImpl
implements FunctionDeclarationStatement {
/// The function declaration being wrapped.
FunctionDeclarationImpl _functionDeclaration;
/// Initialize a newly created function declaration statement.
FunctionDeclarationStatementImpl(
FunctionDeclarationImpl functionDeclaration) {
_functionDeclaration = _becomeParentOf(functionDeclaration);
}
@override
Token get beginToken => _functionDeclaration.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_functionDeclaration);
@override
Token get endToken => _functionDeclaration.endToken;
@override
FunctionDeclaration get functionDeclaration => _functionDeclaration;
@override
void set functionDeclaration(FunctionDeclaration functionDeclaration) {
_functionDeclaration =
_becomeParentOf(functionDeclaration as FunctionDeclarationImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitFunctionDeclarationStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_functionDeclaration?.accept(visitor);
}
}
/// A function expression.
///
/// functionExpression ::=
/// [TypeParameterList]? [FormalParameterList] [FunctionBody]
class FunctionExpressionImpl extends ExpressionImpl
implements FunctionExpression {
/// The type parameters associated with the method, or `null` if the method is
/// not a generic method.
TypeParameterListImpl _typeParameters;
/// The parameters associated with the function, or `null` if the function is
/// part of a top-level getter.
FormalParameterListImpl _parameters;
/// The body of the function, or `null` if this is an external function.
FunctionBodyImpl _body;
@override
ExecutableElement declaredElement;
/// Initialize a newly created function declaration.
FunctionExpressionImpl(TypeParameterListImpl typeParameters,
FormalParameterListImpl parameters, FunctionBodyImpl body) {
_typeParameters = _becomeParentOf(typeParameters);
_parameters = _becomeParentOf(parameters);
_body = _becomeParentOf(body);
}
@override
Token get beginToken {
if (_typeParameters != null) {
return _typeParameters.beginToken;
} else if (_parameters != null) {
return _parameters.beginToken;
} else if (_body != null) {
return _body.beginToken;
}
// This should never be reached because external functions must be named,
// hence either the body or the name should be non-null.
throw new StateError("Non-external functions must have a body");
}
@override
FunctionBody get body => _body;
@override
void set body(FunctionBody functionBody) {
_body = _becomeParentOf(functionBody as FunctionBodyImpl);
}
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_parameters)..add(_body);
@deprecated
@override
ExecutableElement get element => declaredElement;
@deprecated
@override
set element(ExecutableElement element) {
declaredElement = element;
}
@override
Token get endToken {
if (_body != null) {
return _body.endToken;
} else if (_parameters != null) {
return _parameters.endToken;
}
// This should never be reached because external functions must be named,
// hence either the body or the name should be non-null.
throw new StateError("Non-external functions must have a body");
}
@override
FormalParameterList get parameters => _parameters;
@override
void set parameters(FormalParameterList parameters) {
_parameters = _becomeParentOf(parameters as FormalParameterListImpl);
}
@override
Precedence get precedence => Precedence.primary;
@override
TypeParameterList get typeParameters => _typeParameters;
@override
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitFunctionExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_typeParameters?.accept(visitor);
_parameters?.accept(visitor);
_body?.accept(visitor);
}
}
/// The invocation of a function resulting from evaluating an expression.
/// Invocations of methods and other forms of functions are represented by
/// [MethodInvocation] nodes. Invocations of getters and setters are represented
/// by either [PrefixedIdentifier] or [PropertyAccess] nodes.
///
/// functionExpressionInvocation ::=
/// [Expression] [TypeArgumentList]? [ArgumentList]
class FunctionExpressionInvocationImpl extends InvocationExpressionImpl
implements FunctionExpressionInvocation {
/// The expression producing the function being invoked.
ExpressionImpl _function;
/// The element associated with the function being invoked based on static
/// type information, or `null` if the AST structure has not been resolved or
/// the function could not be resolved.
@override
ExecutableElement staticElement;
/// Initialize a newly created function expression invocation.
FunctionExpressionInvocationImpl(ExpressionImpl function,
TypeArgumentListImpl typeArguments, ArgumentListImpl argumentList)
: super(typeArguments, argumentList) {
_function = _becomeParentOf(function);
}
@override
Token get beginToken => _function.beginToken;
@override
@deprecated
ExecutableElement get bestElement => staticElement;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_function)..add(_argumentList);
@override
Token get endToken => _argumentList.endToken;
@override
Expression get function => _function;
@override
void set function(Expression expression) {
_function = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.postfix;
@deprecated
@override
ExecutableElement get propagatedElement => null;
@deprecated
@override
set propagatedElement(ExecutableElement element) {}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitFunctionExpressionInvocation(this);
@override
void visitChildren(AstVisitor visitor) {
_function?.accept(visitor);
_typeArguments?.accept(visitor);
_argumentList?.accept(visitor);
}
}
/// A function type alias.
///
/// functionTypeAlias ::=
/// functionPrefix [TypeParameterList]? [FormalParameterList] ';'
///
/// functionPrefix ::=
/// [TypeName]? [SimpleIdentifier]
class FunctionTypeAliasImpl extends TypeAliasImpl implements FunctionTypeAlias {
/// The name of the return type of the function type being defined, or `null`
/// if no return type was given.
TypeAnnotationImpl _returnType;
/// The type parameters for the function type, or `null` if the function type
/// does not have any type parameters.
TypeParameterListImpl _typeParameters;
/// The parameters associated with the function type.
FormalParameterListImpl _parameters;
/// Initialize a newly created function type alias. Either or both of the
/// [comment] and [metadata] can be `null` if the function does not have the
/// corresponding attribute. The [returnType] can be `null` if no return type
/// was specified. The [typeParameters] can be `null` if the function has no
/// type parameters.
FunctionTypeAliasImpl(
CommentImpl comment,
List<Annotation> metadata,
Token keyword,
TypeAnnotationImpl returnType,
SimpleIdentifierImpl name,
TypeParameterListImpl typeParameters,
FormalParameterListImpl parameters,
Token semicolon)
: super(comment, metadata, keyword, name, semicolon) {
_returnType = _becomeParentOf(returnType);
_typeParameters = _becomeParentOf(typeParameters);
_parameters = _becomeParentOf(parameters);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(typedefKeyword)
..add(_returnType)
..add(_name)
..add(_typeParameters)
..add(_parameters)
..add(semicolon);
@override
FunctionTypeAliasElement get declaredElement =>
_name?.staticElement as FunctionTypeAliasElement;
@deprecated
@override
FunctionTypeAliasElement get element => declaredElement;
@override
FormalParameterList get parameters => _parameters;
@override
void set parameters(FormalParameterList parameters) {
_parameters = _becomeParentOf(parameters as FormalParameterListImpl);
}
@override
TypeAnnotation get returnType => _returnType;
@override
void set returnType(TypeAnnotation type) {
_returnType = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
TypeParameterList get typeParameters => _typeParameters;
@override
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitFunctionTypeAlias(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_returnType?.accept(visitor);
_name?.accept(visitor);
_typeParameters?.accept(visitor);
_parameters?.accept(visitor);
}
}
/// A function-typed formal parameter.
///
/// functionSignature ::=
/// [TypeName]? [SimpleIdentifier] [TypeParameterList]?
/// [FormalParameterList] '?'?
class FunctionTypedFormalParameterImpl extends NormalFormalParameterImpl
implements FunctionTypedFormalParameter {
/// The return type of the function, or `null` if the function does not have a
/// return type.
TypeAnnotationImpl _returnType;
/// The type parameters associated with the function, or `null` if the
/// function is not a generic function.
TypeParameterListImpl _typeParameters;
/// The parameters of the function-typed parameter.
FormalParameterListImpl _parameters;
@override
Token question;
/// Initialize a newly created formal parameter. Either or both of the
/// [comment] and [metadata] can be `null` if the parameter does not have the
/// corresponding attribute. The [returnType] can be `null` if no return type
/// was specified.
FunctionTypedFormalParameterImpl(
CommentImpl comment,
List<Annotation> metadata,
Token covariantKeyword,
Token requiredKeyword,
TypeAnnotationImpl returnType,
SimpleIdentifierImpl identifier,
TypeParameterListImpl typeParameters,
FormalParameterListImpl parameters,
this.question)
: super(
comment, metadata, covariantKeyword, requiredKeyword, identifier) {
_returnType = _becomeParentOf(returnType);
_typeParameters = _becomeParentOf(typeParameters);
_parameters = _becomeParentOf(parameters);
}
@override
Token get beginToken =>
this.metadata.beginToken ??
covariantKeyword ??
_returnType?.beginToken ??
identifier?.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(_returnType)..add(identifier)..add(parameters);
@override
Token get endToken => _parameters.endToken;
@override
bool get isConst => false;
@override
bool get isFinal => false;
@override
FormalParameterList get parameters => _parameters;
@override
void set parameters(FormalParameterList parameters) {
_parameters = _becomeParentOf(parameters as FormalParameterListImpl);
}
@override
TypeAnnotation get returnType => _returnType;
@override
void set returnType(TypeAnnotation type) {
_returnType = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
TypeParameterList get typeParameters => _typeParameters;
@override
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitFunctionTypedFormalParameter(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_returnType?.accept(visitor);
identifier?.accept(visitor);
_typeParameters?.accept(visitor);
_parameters?.accept(visitor);
}
}
/// An anonymous function type.
///
/// functionType ::=
/// [TypeAnnotation]? 'Function' [TypeParameterList]?
/// [FormalParameterList]
///
/// where the FormalParameterList is being used to represent the following
/// grammar, despite the fact that FormalParameterList can represent a much
/// larger grammar than the one below. This is done in order to simplify the
/// implementation.
///
/// parameterTypeList ::=
/// () |
/// ( normalParameterTypes ,? ) |
/// ( normalParameterTypes , optionalParameterTypes ) |
/// ( optionalParameterTypes )
/// namedParameterTypes ::=
/// { namedParameterType (, namedParameterType)* ,? }
/// namedParameterType ::=
/// [TypeAnnotation]? [SimpleIdentifier]
/// normalParameterTypes ::=
/// normalParameterType (, normalParameterType)*
/// normalParameterType ::=
/// [TypeAnnotation] [SimpleIdentifier]?
/// optionalParameterTypes ::=
/// optionalPositionalParameterTypes | namedParameterTypes
/// optionalPositionalParameterTypes ::=
/// [ normalParameterTypes ,? ]
class GenericFunctionTypeImpl extends TypeAnnotationImpl
implements GenericFunctionType {
/// The name of the return type of the function type being defined, or
/// `null` if no return type was given.
TypeAnnotationImpl _returnType;
@override
Token functionKeyword;
/// The type parameters for the function type, or `null` if the function type
/// does not have any type parameters.
TypeParameterListImpl _typeParameters;
/// The parameters associated with the function type.
FormalParameterListImpl _parameters;
@override
Token question;
@override
DartType type;
/// Return the element associated with the function type, or `null` if the
/// AST structure has not been resolved.
GenericFunctionTypeElement declaredElement;
/// Initialize a newly created generic function type.
GenericFunctionTypeImpl(TypeAnnotationImpl returnType, this.functionKeyword,
TypeParameterListImpl typeParameters, FormalParameterListImpl parameters,
{this.question}) {
_returnType = _becomeParentOf(returnType);
_typeParameters = _becomeParentOf(typeParameters);
_parameters = _becomeParentOf(parameters);
}
@override
Token get beginToken => _returnType?.beginToken ?? functionKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_returnType)
..add(functionKeyword)
..add(_typeParameters)
..add(_parameters)
..add(question);
@override
Token get endToken => question ?? _parameters.endToken;
@override
FormalParameterList get parameters => _parameters;
@override
void set parameters(FormalParameterList parameters) {
_parameters = _becomeParentOf(parameters as FormalParameterListImpl);
}
@override
TypeAnnotation get returnType => _returnType;
@override
void set returnType(TypeAnnotation type) {
_returnType = _becomeParentOf(type as TypeAnnotationImpl);
}
/// Return the type parameters for the function type, or `null` if the
/// function type does not have any type parameters.
TypeParameterList get typeParameters => _typeParameters;
/// Set the type parameters for the function type to the given list of
/// [typeParameters].
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
// TODO: implement type
@override
E accept<E>(AstVisitor<E> visitor) {
return visitor.visitGenericFunctionType(this);
}
@override
void visitChildren(AstVisitor visitor) {
_returnType?.accept(visitor);
_typeParameters?.accept(visitor);
_parameters?.accept(visitor);
}
}
/// A generic type alias.
///
/// functionTypeAlias ::=
/// metadata 'typedef' [SimpleIdentifier] [TypeParameterList]? =
/// [FunctionType] ';'
class GenericTypeAliasImpl extends TypeAliasImpl implements GenericTypeAlias {
/// The type parameters for the function type, or `null` if the function
/// type does not have any type parameters.
TypeParameterListImpl _typeParameters;
@override
Token equals;
/// The type of function being defined by the alias.
GenericFunctionTypeImpl _functionType;
/// Returns a newly created generic type alias. Either or both of the
/// [comment] and [metadata] can be `null` if the variable list does not have
/// the corresponding attribute. The [typeParameters] can be `null` if there
/// are no type parameters.
GenericTypeAliasImpl(
CommentImpl comment,
List<Annotation> metadata,
Token typedefToken,
SimpleIdentifierImpl name,
TypeParameterListImpl typeParameters,
this.equals,
GenericFunctionTypeImpl functionType,
Token semicolon)
: super(comment, metadata, typedefToken, name, semicolon) {
_typeParameters = _becomeParentOf(typeParameters);
_functionType = _becomeParentOf(functionType);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..addAll(metadata)
..add(typedefKeyword)
..add(name)
..add(_typeParameters)
..add(equals)
..add(_functionType);
@override
Element get declaredElement => name.staticElement;
@deprecated
@override
Element get element => declaredElement;
@override
GenericFunctionType get functionType => _functionType;
@override
void set functionType(GenericFunctionType functionType) {
_functionType = _becomeParentOf(functionType as GenericFunctionTypeImpl);
}
@override
TypeParameterList get typeParameters => _typeParameters;
@override
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) {
return visitor.visitGenericTypeAlias(this);
}
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
name?.accept(visitor);
_typeParameters?.accept(visitor);
_functionType?.accept(visitor);
}
}
/// A combinator that restricts the names being imported to those that are not
/// in a given list.
///
/// hideCombinator ::=
/// 'hide' [SimpleIdentifier] (',' [SimpleIdentifier])*
class HideCombinatorImpl extends CombinatorImpl implements HideCombinator {
/// The list of names from the library that are hidden by this combinator.
NodeList<SimpleIdentifier> _hiddenNames;
/// Initialize a newly created import show combinator.
HideCombinatorImpl(Token keyword, List<SimpleIdentifier> hiddenNames)
: super(keyword) {
_hiddenNames = new NodeListImpl<SimpleIdentifier>(this, hiddenNames);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(keyword)
..addAll(_hiddenNames);
@override
Token get endToken => _hiddenNames.endToken;
@override
NodeList<SimpleIdentifier> get hiddenNames => _hiddenNames;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitHideCombinator(this);
@override
void visitChildren(AstVisitor visitor) {
_hiddenNames.accept(visitor);
}
}
/// A node that represents an identifier.
///
/// identifier ::=
/// [SimpleIdentifier]
/// | [PrefixedIdentifier]
abstract class IdentifierImpl extends ExpressionImpl implements Identifier {
/// Return the best element available for this operator. If resolution was
/// able to find a better element based on type propagation, that element will
/// be returned. Otherwise, the element found using the result of static
/// analysis will be returned. If resolution has not been performed, then `null` will
/// be returned.
@override
@deprecated
Element get bestElement;
@override
bool get isAssignable => true;
}
class IfElementImpl extends CollectionElementImpl
with IfMixin
implements IfElement {
/// The element to be executed if the condition is `true`.
CollectionElementImpl _thenElement;
/// The element to be executed if the condition is `false`, or `null` if there
/// is no such element.
CollectionElementImpl _elseElement;
/// Initialize a newly created for element.
IfElementImpl(
Token ifKeyword,
Token leftParenthesis,
ExpressionImpl condition,
Token rightParenthesis,
CollectionElementImpl thenElement,
Token elseKeyword,
CollectionElementImpl elseElement) {
this.ifKeyword = ifKeyword;
this.leftParenthesis = leftParenthesis;
_condition = _becomeParentOf(condition);
this.rightParenthesis = rightParenthesis;
_thenElement = _becomeParentOf(thenElement);
this.elseKeyword = elseKeyword;
_elseElement = _becomeParentOf(elseElement);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..addAll(super.childEntities)
..add(_thenElement)
..add(elseKeyword)
..add(_elseElement);
@override
CollectionElement get elseElement => _elseElement;
set elseElement(CollectionElement element) {
_elseElement = _becomeParentOf(element as CollectionElementImpl);
}
@override
Token get endToken => _elseElement?.endToken ?? _thenElement.endToken;
@override
CollectionElement get thenElement => _thenElement;
set thenElement(CollectionElement element) {
_thenElement = _becomeParentOf(element as CollectionElementImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitIfElement(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_thenElement?.accept(visitor);
_elseElement?.accept(visitor);
}
}
mixin IfMixin on AstNodeImpl {
Token ifKeyword;
Token leftParenthesis;
/// The condition used to determine which of the branches is executed next.
ExpressionImpl _condition;
Token rightParenthesis;
Token elseKeyword;
@override
Token get beginToken => ifKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(ifKeyword)
..add(leftParenthesis)
..add(_condition)
..add(rightParenthesis);
Expression get condition => _condition;
void set condition(Expression expression) {
_condition = _becomeParentOf(expression as ExpressionImpl);
}
@override
void visitChildren(AstVisitor visitor) {
_condition?.accept(visitor);
}
}
/// An if statement.
///
/// ifStatement ::=
/// 'if' '(' [Expression] ')' [Statement] ('else' [Statement])?
class IfStatementImpl extends StatementImpl
with IfMixin
implements IfStatement {
/// The statement that is executed if the condition evaluates to `true`.
StatementImpl _thenStatement;
/// The statement that is executed if the condition evaluates to `false`, or
/// `null` if there is no else statement.
StatementImpl _elseStatement;
/// Initialize a newly created if statement. The [elseKeyword] and
/// [elseStatement] can be `null` if there is no else clause.
IfStatementImpl(
Token ifKeyword,
Token leftParenthesis,
ExpressionImpl condition,
Token rightParenthesis,
StatementImpl thenStatement,
Token elseKeyword,
StatementImpl elseStatement) {
this.ifKeyword = ifKeyword;
this.leftParenthesis = leftParenthesis;
_condition = _becomeParentOf(condition);
this.rightParenthesis = rightParenthesis;
_thenStatement = _becomeParentOf(thenStatement);
this.elseKeyword = elseKeyword;
_elseStatement = _becomeParentOf(elseStatement);
}
@override
Token get beginToken => ifKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..addAll(super.childEntities)
..add(_thenStatement)
..add(elseKeyword)
..add(_elseStatement);
@override
Statement get elseStatement => _elseStatement;
@override
void set elseStatement(Statement statement) {
_elseStatement = _becomeParentOf(statement as StatementImpl);
}
@override
Token get endToken {
if (_elseStatement != null) {
return _elseStatement.endToken;
}
return _thenStatement.endToken;
}
@override
Statement get thenStatement => _thenStatement;
@override
void set thenStatement(Statement statement) {
_thenStatement = _becomeParentOf(statement as StatementImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitIfStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_condition?.accept(visitor);
_thenStatement?.accept(visitor);
_elseStatement?.accept(visitor);
}
}
/// The "implements" clause in an class declaration.
///
/// implementsClause ::=
/// 'implements' [TypeName] (',' [TypeName])*
class ImplementsClauseImpl extends AstNodeImpl implements ImplementsClause {
/// The token representing the 'implements' keyword.
@override
Token implementsKeyword;
/// The interfaces that are being implemented.
NodeList<TypeName> _interfaces;
/// Initialize a newly created implements clause.
ImplementsClauseImpl(this.implementsKeyword, List<TypeName> interfaces) {
_interfaces = new NodeListImpl<TypeName>(this, interfaces);
}
@override
Token get beginToken => implementsKeyword;
@override
// TODO(paulberry): add commas.
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(implementsKeyword)
..addAll(interfaces);
@override
Token get endToken => _interfaces.endToken;
@override
NodeList<TypeName> get interfaces => _interfaces;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitImplementsClause(this);
@override
void visitChildren(AstVisitor visitor) {
_interfaces.accept(visitor);
}
}
/// An import directive.
///
/// importDirective ::=
/// [Annotation] 'import' [StringLiteral] ('as' identifier)?
// [Combinator]* ';'
/// | [Annotation] 'import' [StringLiteral] 'deferred' 'as' identifier
// [Combinator]* ';'
class ImportDirectiveImpl extends NamespaceDirectiveImpl
implements ImportDirective {
/// The token representing the 'deferred' keyword, or `null` if the imported
/// is not deferred.
Token deferredKeyword;
/// The token representing the 'as' keyword, or `null` if the imported names
/// are not prefixed.
@override
Token asKeyword;
/// The prefix to be used with the imported names, or `null` if the imported
/// names are not prefixed.
SimpleIdentifierImpl _prefix;
/// Initialize a newly created import directive. Either or both of the
/// [comment] and [metadata] can be `null` if the function does not have the
/// corresponding attribute. The [deferredKeyword] can be `null` if the import
/// is not deferred. The [asKeyword] and [prefix] can be `null` if the import
/// does not specify a prefix. The list of [combinators] can be `null` if
/// there are no combinators.
ImportDirectiveImpl(
CommentImpl comment,
List<Annotation> metadata,
Token keyword,
StringLiteralImpl libraryUri,
List<Configuration> configurations,
this.deferredKeyword,
this.asKeyword,
SimpleIdentifierImpl prefix,
List<Combinator> combinators,
Token semicolon)
: super(comment, metadata, keyword, libraryUri, configurations,
combinators, semicolon) {
_prefix = _becomeParentOf(prefix);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(keyword)
..add(_uri)
..add(deferredKeyword)
..add(asKeyword)
..add(_prefix)
..addAll(combinators)
..add(semicolon);
@override
ImportElement get element => super.element as ImportElement;
@override
SimpleIdentifier get prefix => _prefix;
@override
void set prefix(SimpleIdentifier identifier) {
_prefix = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
LibraryElement get uriElement {
ImportElement element = this.element;
if (element == null) {
return null;
}
return element.importedLibrary;
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitImportDirective(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_prefix?.accept(visitor);
combinators.accept(visitor);
}
}
/// An index expression.
///
/// indexExpression ::=
/// [Expression] '[' [Expression] ']'
class IndexExpressionImpl extends ExpressionImpl implements IndexExpression {
/// The expression used to compute the object being indexed, or `null` if this
/// index expression is part of a cascade expression.
ExpressionImpl _target;
/// The period (".." | "?..") before a cascaded index expression,
/// or `null` if this index expression is not part of a cascade expression.
@override
Token period;
/// The left square bracket.
@override
Token leftBracket;
/// The expression used to compute the index.
ExpressionImpl _index;
/// The right square bracket.
@override
Token rightBracket;
/// The element associated with the operator based on the static type of the
/// target, or `null` if the AST structure has not been resolved or if the
/// operator could not be resolved.
@override
MethodElement staticElement;
/// If this expression is both in a getter and setter context, the
/// [AuxiliaryElements] will be set to hold onto the static element from the
/// getter context.
AuxiliaryElements auxiliaryElements;
/// Initialize a newly created index expression.
IndexExpressionImpl.forCascade(
this.period, this.leftBracket, ExpressionImpl index, this.rightBracket) {
_index = _becomeParentOf(index);
}
/// Initialize a newly created index expression.
IndexExpressionImpl.forTarget(ExpressionImpl target, this.leftBracket,
ExpressionImpl index, this.rightBracket) {
_target = _becomeParentOf(target);
_index = _becomeParentOf(index);
}
@override
Token get beginToken {
if (_target != null) {
return _target.beginToken;
}
return period;
}
@override
@deprecated
MethodElement get bestElement => staticElement;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_target)
..add(period)
..add(leftBracket)
..add(_index)
..add(rightBracket);
@override
Token get endToken => rightBracket;
@override
Expression get index => _index;
@override
void set index(Expression expression) {
_index = _becomeParentOf(expression as ExpressionImpl);
}
@override
bool get isAssignable => true;
@override
bool get isCascaded => period != null;
@override
bool get isNullAware =>
leftBracket.type == TokenType.QUESTION_PERIOD_OPEN_SQUARE_BRACKET;
@override
Precedence get precedence => Precedence.postfix;
@deprecated
@override
MethodElement get propagatedElement => null;
@deprecated
@override
set propagatedElement(MethodElement element) {}
@override
Expression get realTarget {
if (isCascaded) {
AstNode ancestor = parent;
while (ancestor is! CascadeExpression) {
if (ancestor == null) {
return _target;
}
ancestor = ancestor.parent;
}
return (ancestor as CascadeExpression).target;
}
return _target;
}
@override
Expression get target => _target;
@override
void set target(Expression expression) {
_target = _becomeParentOf(expression as ExpressionImpl);
}
/// If the AST structure has been resolved, and the function being invoked is
/// known based on static type information, then return the parameter element
/// representing the parameter to which the value of the index expression will
/// be bound. Otherwise, return `null`.
ParameterElement get _staticParameterElementForIndex {
if (staticElement == null) {
return null;
}
List<ParameterElement> parameters = staticElement.parameters;
if (parameters.isEmpty) {
return null;
}
return parameters[0];
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitIndexExpression(this);
@override
bool inGetterContext() {
// TODO(brianwilkerson) Convert this to a getter.
AstNode parent = this.parent;
if (parent is AssignmentExpression) {
AssignmentExpression assignment = parent;
if (identical(assignment.leftHandSide, this) &&
assignment.operator.type == TokenType.EQ) {
return false;
}
}
return true;
}
@override
bool inSetterContext() {
// TODO(brianwilkerson) Convert this to a getter.
AstNode parent = this.parent;
if (parent is PrefixExpression) {
return parent.operator.type.isIncrementOperator;
} else if (parent is PostfixExpression) {
return true;
} else if (parent is AssignmentExpression) {
return identical(parent.leftHandSide, this);
}
return false;
}
@override
void visitChildren(AstVisitor visitor) {
_target?.accept(visitor);
_index?.accept(visitor);
}
}
/// An instance creation expression.
///
/// newExpression ::=
/// ('new' | 'const')? [TypeName] ('.' [SimpleIdentifier])?
/// [ArgumentList]
class InstanceCreationExpressionImpl extends ExpressionImpl
implements InstanceCreationExpression {
// TODO(brianwilkerson) Consider making InstanceCreationExpressionImpl extend
// InvocationExpressionImpl. This would probably be a breaking change, but is
// also probably worth it.
/// The 'new' or 'const' keyword used to indicate how an object should be
/// created, or `null` if the keyword is implicit.
@override
Token keyword;
/// The name of the constructor to be invoked.
ConstructorNameImpl _constructorName;
/// The type arguments associated with the constructor, rather than with the
/// class in which the constructor is defined. It is always an error if there
/// are type arguments because Dart doesn't currently support generic
/// constructors, but we capture them in the AST in order to recover better.
TypeArgumentListImpl _typeArguments;
/// The list of arguments to the constructor.
ArgumentListImpl _argumentList;
/// The element associated with the constructor based on static type
/// information, or `null` if the AST structure has not been resolved or if
/// the constructor could not be resolved.
@override
ConstructorElement staticElement;
/// Initialize a newly created instance creation expression.
InstanceCreationExpressionImpl(this.keyword,
ConstructorNameImpl constructorName, ArgumentListImpl argumentList,
{TypeArgumentListImpl typeArguments}) {
_constructorName = _becomeParentOf(constructorName);
_typeArguments = _becomeParentOf(typeArguments);
_argumentList = _becomeParentOf(argumentList);
}
@override
ArgumentList get argumentList => _argumentList;
@override
void set argumentList(ArgumentList argumentList) {
_argumentList = _becomeParentOf(argumentList as ArgumentListImpl);
}
@override
Token get beginToken => keyword ?? _constructorName.beginToken;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(keyword)
..add(_constructorName)
..add(_typeArguments)
..add(_argumentList);
@override
ConstructorName get constructorName => _constructorName;
@override
void set constructorName(ConstructorName name) {
_constructorName = _becomeParentOf(name as ConstructorNameImpl);
}
@override
Token get endToken => _argumentList.endToken;
@override
bool get isConst {
if (!isImplicit) {
return keyword.keyword == Keyword.CONST;
} else {
return inConstantContext;
}
}
/// Return `true` if this is an implicit constructor invocations.
bool get isImplicit => keyword == null;
@override
Precedence get precedence => Precedence.primary;
/// Return the type arguments associated with the constructor, rather than
/// with the class in which the constructor is defined. It is always an error
/// if there are type arguments because Dart doesn't currently support generic
/// constructors, but we capture them in the AST in order to recover better.
TypeArgumentList get typeArguments => _typeArguments;
/// Return the type arguments associated with the constructor, rather than
/// with the class in which the constructor is defined. It is always an error
/// if there are type arguments because Dart doesn't currently support generic
/// constructors, but we capture them in the AST in order to recover better.
void set typeArguments(TypeArgumentList typeArguments) {
_typeArguments = _becomeParentOf(typeArguments as TypeArgumentListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitInstanceCreationExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_constructorName?.accept(visitor);
_typeArguments?.accept(visitor);
_argumentList?.accept(visitor);
}
}
/// An integer literal expression.
///
/// integerLiteral ::=
/// decimalIntegerLiteral
/// | hexadecimalIntegerLiteral
///
/// decimalIntegerLiteral ::=
/// decimalDigit+
///
/// hexadecimalIntegerLiteral ::=
/// '0x' hexadecimalDigit+
/// | '0X' hexadecimalDigit+
class IntegerLiteralImpl extends LiteralImpl implements IntegerLiteral {
/// The token representing the literal.
@override
Token literal;
/// The value of the literal.
@override
int value = 0;
/// Initialize a newly created integer literal.
IntegerLiteralImpl(this.literal, this.value);
@override
Token get beginToken => literal;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(literal);
@override
Token get endToken => literal;
/// Returns whether this literal's [parent] is a [PrefixExpression] of unary
/// negation.
///
/// Note: this does *not* indicate that the value itself is negated, just that
/// the literal is the child of a negation operation. The literal value itself
/// will always be positive.
bool get immediatelyNegated {
AstNode parent = this.parent; // Capture for type propagation.
return parent is PrefixExpression &&
parent.operator.type == TokenType.MINUS;
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitIntegerLiteral(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
static bool isValidAsDouble(String lexeme) {
// Less than 16 characters must be a valid double since it will be less than
// 9007199254740992, 0x10000000000000, both 16 characters and 53 bits.
if (lexeme.length < 16) {
return true;
}
BigInt fullPrecision = BigInt.tryParse(lexeme);
if (fullPrecision == null) {
return false;
}
// Usually handled by the length check, however, we must check this before
// constructing a mask later, or we'd get a negative-shift runtime error.
int bitLengthAsInt = fullPrecision.bitLength;
if (bitLengthAsInt <= 53) {
return true;
}
// This would overflow the exponent (larger than maximum double).
if (fullPrecision > BigInt.from(double.maxFinite)) {
return false;
}
// Say [lexeme] uses 100 bits as an integer. The bottom 47 must be 0s -- so
// construct a mask of 47 ones, via of 2^n - 1 where n is 47.
BigInt bottomMask = (BigInt.one << (bitLengthAsInt - 53)) - BigInt.one;
return fullPrecision & bottomMask == BigInt.zero;
}
/// Return `true` if the given [lexeme] is a valid lexeme for an integer
/// literal. The flag [isNegative] should be `true` if the lexeme is preceded
/// by a unary negation operator.
static bool isValidAsInteger(String lexeme, bool isNegative) {
// TODO(jmesserly): this depends on the platform int implementation, and
// may not be accurate if run on dart4web.
//
// (Prior to https://dart-review.googlesource.com/c/sdk/+/63023 there was
// a partial implementation here which may be a good starting point.
// _isValidDecimalLiteral relied on int.parse so that would need some fixes.
// _isValidHexadecimalLiteral worked except for negative int64 max.)
if (isNegative) lexeme = '-$lexeme';
return int.tryParse(lexeme) != null;
}
/// Suggest the nearest valid double to a user. If the integer they wrote
/// requires more than a 53 bit mantissa, or more than 10 exponent bits, do
/// them the favor of suggesting the nearest integer that would work for them.
static double nearestValidDouble(String lexeme) =>
math.min(double.maxFinite, BigInt.parse(lexeme).toDouble());
}
/// A node within a [StringInterpolation].
///
/// interpolationElement ::=
/// [InterpolationExpression]
/// | [InterpolationString]
abstract class InterpolationElementImpl extends AstNodeImpl
implements InterpolationElement {}
/// An expression embedded in a string interpolation.
///
/// interpolationExpression ::=
/// '$' [SimpleIdentifier]
/// | '$' '{' [Expression] '}'
class InterpolationExpressionImpl extends InterpolationElementImpl
implements InterpolationExpression {
/// The token used to introduce the interpolation expression; either '$' if
/// the expression is a simple identifier or '${' if the expression is a full
/// expression.
@override
Token leftBracket;
/// The expression to be evaluated for the value to be converted into a
/// string.
ExpressionImpl _expression;
/// The right curly bracket, or `null` if the expression is an identifier
/// without brackets.
@override
Token rightBracket;
/// Initialize a newly created interpolation expression.
InterpolationExpressionImpl(
this.leftBracket, ExpressionImpl expression, this.rightBracket) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken => leftBracket;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(leftBracket)
..add(_expression)
..add(rightBracket);
@override
Token get endToken {
if (rightBracket != null) {
return rightBracket;
}
return _expression.endToken;
}
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitInterpolationExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// A non-empty substring of an interpolated string.
///
/// interpolationString ::=
/// characters
class InterpolationStringImpl extends InterpolationElementImpl
implements InterpolationString {
/// The characters that will be added to the string.
@override
Token contents;
/// The value of the literal.
@override
String value;
/// Initialize a newly created string of characters that are part of a string
/// interpolation.
InterpolationStringImpl(this.contents, this.value);
@override
Token get beginToken => contents;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(contents);
@override
int get contentsEnd {
String lexeme = contents.lexeme;
return offset + new StringLexemeHelper(lexeme, true, true).end;
}
@override
int get contentsOffset {
int offset = contents.offset;
String lexeme = contents.lexeme;
return offset + new StringLexemeHelper(lexeme, true, true).start;
}
@override
Token get endToken => contents;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitInterpolationString(this);
@override
void visitChildren(AstVisitor visitor) {}
}
/// Common base class for [FunctionExpressionInvocationImpl] and
/// [MethodInvocationImpl].
abstract class InvocationExpressionImpl extends ExpressionImpl
implements InvocationExpression {
/// The list of arguments to the function.
ArgumentListImpl _argumentList;
/// The type arguments to be applied to the method being invoked, or `null` if
/// no type arguments were provided.
TypeArgumentListImpl _typeArguments;
@override
List<DartType> typeArgumentTypes;
@override
DartType staticInvokeType;
/// Initialize a newly created invocation.
InvocationExpressionImpl(
TypeArgumentListImpl typeArguments, ArgumentListImpl argumentList) {
_typeArguments = _becomeParentOf(typeArguments);
_argumentList = _becomeParentOf(argumentList);
}
@override
ArgumentList get argumentList => _argumentList;
void set argumentList(ArgumentList argumentList) {
_argumentList = _becomeParentOf(argumentList as ArgumentListImpl);
}
@deprecated
@override
DartType get propagatedInvokeType => null;
@deprecated
@override
set propagatedInvokeType(DartType type) {}
@override
TypeArgumentList get typeArguments => _typeArguments;
void set typeArguments(TypeArgumentList typeArguments) {
_typeArguments = _becomeParentOf(typeArguments as TypeArgumentListImpl);
}
}
/// An is expression.
///
/// isExpression ::=
/// [Expression] 'is' '!'? [TypeName]
class IsExpressionImpl extends ExpressionImpl implements IsExpression {
/// The expression used to compute the value whose type is being tested.
ExpressionImpl _expression;
/// The is operator.
@override
Token isOperator;
/// The not operator, or `null` if the sense of the test is not negated.
@override
Token notOperator;
/// The name of the type being tested for.
TypeAnnotationImpl _type;
/// Initialize a newly created is expression. The [notOperator] can be `null`
/// if the sense of the test is not negated.
IsExpressionImpl(ExpressionImpl expression, this.isOperator, this.notOperator,
TypeAnnotationImpl type) {
_expression = _becomeParentOf(expression);
_type = _becomeParentOf(type);
}
@override
Token get beginToken => _expression.beginToken;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_expression)
..add(isOperator)
..add(notOperator)
..add(_type);
@override
Token get endToken => _type.endToken;
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.relational;
@override
TypeAnnotation get type => _type;
@override
void set type(TypeAnnotation type) {
_type = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitIsExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
_type?.accept(visitor);
}
}
/// A statement that has a label associated with them.
///
/// labeledStatement ::=
/// [Label]+ [Statement]
class LabeledStatementImpl extends StatementImpl implements LabeledStatement {
/// The labels being associated with the statement.
NodeList<Label> _labels;
/// The statement with which the labels are being associated.
StatementImpl _statement;
/// Initialize a newly created labeled statement.
LabeledStatementImpl(List<Label> labels, StatementImpl statement) {
_labels = new NodeListImpl<Label>(this, labels);
_statement = _becomeParentOf(statement);
}
@override
Token get beginToken {
if (_labels.isNotEmpty) {
return _labels.beginToken;
}
return _statement.beginToken;
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..addAll(_labels)
..add(_statement);
@override
Token get endToken => _statement.endToken;
@override
NodeList<Label> get labels => _labels;
@override
Statement get statement => _statement;
@override
void set statement(Statement statement) {
_statement = _becomeParentOf(statement as StatementImpl);
}
@override
Statement get unlabeled => _statement.unlabeled;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitLabeledStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_labels.accept(visitor);
_statement?.accept(visitor);
}
}
/// A label on either a [LabeledStatement] or a [NamedExpression].
///
/// label ::=
/// [SimpleIdentifier] ':'
class LabelImpl extends AstNodeImpl implements Label {
/// The label being associated with the statement.
SimpleIdentifierImpl _label;
/// The colon that separates the label from the statement.
@override
Token colon;
/// Initialize a newly created label.
LabelImpl(SimpleIdentifierImpl label, this.colon) {
_label = _becomeParentOf(label);
}
@override
Token get beginToken => _label.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_label)..add(colon);
@override
Token get endToken => colon;
@override
SimpleIdentifier get label => _label;
@override
void set label(SimpleIdentifier label) {
_label = _becomeParentOf(label as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitLabel(this);
@override
void visitChildren(AstVisitor visitor) {
_label?.accept(visitor);
}
}
/// A library directive.
///
/// libraryDirective ::=
/// [Annotation] 'library' [Identifier] ';'
class LibraryDirectiveImpl extends DirectiveImpl implements LibraryDirective {
/// The token representing the 'library' keyword.
@override
Token libraryKeyword;
/// The name of the library being defined.
LibraryIdentifierImpl _name;
/// The semicolon terminating the directive.
@override
Token semicolon;
/// Initialize a newly created library directive. Either or both of the
/// [comment] and [metadata] can be `null` if the directive does not have the
/// corresponding attribute.
LibraryDirectiveImpl(CommentImpl comment, List<Annotation> metadata,
this.libraryKeyword, LibraryIdentifierImpl name, this.semicolon)
: super(comment, metadata) {
_name = _becomeParentOf(name);
}
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(libraryKeyword)..add(_name)..add(semicolon);
@override
Token get endToken => semicolon;
@override
Token get firstTokenAfterCommentAndMetadata => libraryKeyword;
@override
Token get keyword => libraryKeyword;
@override
LibraryIdentifier get name => _name;
@override
void set name(LibraryIdentifier name) {
_name = _becomeParentOf(name as LibraryIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitLibraryDirective(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_name?.accept(visitor);
}
}
/// The identifier for a library.
///
/// libraryIdentifier ::=
/// [SimpleIdentifier] ('.' [SimpleIdentifier])*
class LibraryIdentifierImpl extends IdentifierImpl
implements LibraryIdentifier {
/// The components of the identifier.
NodeList<SimpleIdentifier> _components;
/// Initialize a newly created prefixed identifier.
LibraryIdentifierImpl(List<SimpleIdentifier> components) {
_components = new NodeListImpl<SimpleIdentifier>(this, components);
}
@override
Token get beginToken => _components.beginToken;
@override
@deprecated
Element get bestElement => staticElement;
@override
// TODO(paulberry): add "." tokens.
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..addAll(_components);
@override
NodeList<SimpleIdentifier> get components => _components;
@override
Token get endToken => _components.endToken;
@override
String get name {
StringBuffer buffer = new StringBuffer();
bool needsPeriod = false;
int length = _components.length;
for (int i = 0; i < length; i++) {
SimpleIdentifier identifier = _components[i];
if (needsPeriod) {
buffer.write(".");
} else {
needsPeriod = true;
}
buffer.write(identifier.name);
}
return buffer.toString();
}
@override
Precedence get precedence => Precedence.postfix;
@deprecated
@override
Element get propagatedElement => null;
@override
Element get staticElement => null;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitLibraryIdentifier(this);
@override
void visitChildren(AstVisitor visitor) {
_components.accept(visitor);
}
}
class ListLiteralImpl extends TypedLiteralImpl implements ListLiteral {
/// The left square bracket.
@override
Token leftBracket;
/// The expressions used to compute the elements of the list.
NodeList<CollectionElement> _elements;
/// The right square bracket.
@override
Token rightBracket;
/// Initialize a newly created list literal. The [constKeyword] can be `null`
/// if the literal is not a constant. The [typeArguments] can be `null` if no
/// type arguments were declared. The list of [elements] can be `null` if the
/// list is empty.
ListLiteralImpl(Token constKeyword, TypeArgumentListImpl typeArguments,
this.leftBracket, List<Expression> elements, this.rightBracket)
: super(constKeyword, typeArguments) {
_elements = new NodeListImpl<Expression>(this, elements);
}
/// Initialize a newly created list literal.
///
/// The [constKeyword] can be `null` if the literal is not a constant. The
/// [typeArguments] can be `null` if no type arguments were declared. The list
/// of [elements] can be `null` if the list is empty.
ListLiteralImpl.experimental(
Token constKeyword,
TypeArgumentListImpl typeArguments,
this.leftBracket,
List<CollectionElement> elements,
this.rightBracket)
: super(constKeyword, typeArguments) {
_elements = new NodeListImpl<CollectionElement>(this, elements);
}
@override
Token get beginToken {
if (constKeyword != null) {
return constKeyword;
}
TypeArgumentList typeArguments = this.typeArguments;
if (typeArguments != null) {
return typeArguments.beginToken;
}
return leftBracket;
}
@override
// TODO(paulberry): add commas.
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(leftBracket)
..addAll(_elements)
..add(rightBracket);
@override
NodeList<CollectionElement> get elements => _elements;
@override
Token get endToken => rightBracket;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitListLiteral(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_elements.accept(visitor);
}
}
/// A node that represents a literal expression.
///
/// literal ::=
/// [BooleanLiteral]
/// | [DoubleLiteral]
/// | [IntegerLiteral]
/// | [ListLiteral]
/// | [MapLiteral]
/// | [NullLiteral]
/// | [StringLiteral]
abstract class LiteralImpl extends ExpressionImpl implements Literal {
@override
Precedence get precedence => Precedence.primary;
}
/// Additional information about local variables within a function or method
/// produced at resolution time.
class LocalVariableInfo {
/// The set of local variables and parameters that are potentially mutated
/// within a local function other than the function in which they are
/// declared.
final Set<VariableElement> potentiallyMutatedInClosure =
new Set<VariableElement>();
/// The set of local variables and parameters that are potentially mutated
/// within the scope of their declarations.
final Set<VariableElement> potentiallyMutatedInScope =
new Set<VariableElement>();
}
/// A single key/value pair in a map literal.
///
/// mapLiteralEntry ::=
/// [Expression] ':' [Expression]
class MapLiteralEntryImpl extends CollectionElementImpl
implements MapLiteralEntry {
/// The expression computing the key with which the value will be associated.
ExpressionImpl _key;
/// The colon that separates the key from the value.
@override
Token separator;
/// The expression computing the value that will be associated with the key.
ExpressionImpl _value;
/// Initialize a newly created map literal entry.
MapLiteralEntryImpl(
ExpressionImpl key, this.separator, ExpressionImpl value) {
_key = _becomeParentOf(key);
_value = _becomeParentOf(value);
}
@override
Token get beginToken => _key.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_key)..add(separator)..add(_value);
@override
Token get endToken => _value.endToken;
@override
Expression get key => _key;
@override
void set key(Expression string) {
_key = _becomeParentOf(string as ExpressionImpl);
}
@override
Expression get value => _value;
@override
void set value(Expression expression) {
_value = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitMapLiteralEntry(this);
@override
void visitChildren(AstVisitor visitor) {
_key?.accept(visitor);
_value?.accept(visitor);
}
}
/// A method declaration.
///
/// methodDeclaration ::=
/// methodSignature [FunctionBody]
///
/// methodSignature ::=
/// 'external'? ('abstract' | 'static')? [Type]? ('get' | 'set')?
/// methodName [TypeParameterList] [FormalParameterList]
///
/// methodName ::=
/// [SimpleIdentifier]
/// | 'operator' [SimpleIdentifier]
class MethodDeclarationImpl extends ClassMemberImpl
implements MethodDeclaration {
/// The token for the 'external' keyword, or `null` if the constructor is not
/// external.
@override
Token externalKeyword;
/// The token representing the 'abstract' or 'static' keyword, or `null` if
/// neither modifier was specified.
@override
Token modifierKeyword;
/// The return type of the method, or `null` if no return type was declared.
TypeAnnotationImpl _returnType;
/// The token representing the 'get' or 'set' keyword, or `null` if this is a
/// method declaration rather than a property declaration.
@override
Token propertyKeyword;
/// The token representing the 'operator' keyword, or `null` if this method
/// does not declare an operator.
@override
Token operatorKeyword;
/// The name of the method.
SimpleIdentifierImpl _name;
/// The type parameters associated with the method, or `null` if the method is
/// not a generic method.
TypeParameterListImpl _typeParameters;
/// The parameters associated with the method, or `null` if this method
/// declares a getter.
FormalParameterListImpl _parameters;
/// The body of the method.
FunctionBodyImpl _body;
/// Initialize a newly created method declaration. Either or both of the
/// [comment] and [metadata] can be `null` if the declaration does not have
/// the corresponding attribute. The [externalKeyword] can be `null` if the
/// method is not external. The [modifierKeyword] can be `null` if the method
/// is neither abstract nor static. The [returnType] can be `null` if no
/// return type was specified. The [propertyKeyword] can be `null` if the
/// method is neither a getter or a setter. The [operatorKeyword] can be
/// `null` if the method does not implement an operator. The [parameters] must
/// be `null` if this method declares a getter.
MethodDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
this.externalKeyword,
this.modifierKeyword,
TypeAnnotationImpl returnType,
this.propertyKeyword,
this.operatorKeyword,
SimpleIdentifierImpl name,
TypeParameterListImpl typeParameters,
FormalParameterListImpl parameters,
FunctionBodyImpl body)
: super(comment, metadata) {
_returnType = _becomeParentOf(returnType);
_name = _becomeParentOf(name);
_typeParameters = _becomeParentOf(typeParameters);
_parameters = _becomeParentOf(parameters);
_body = _becomeParentOf(body);
}
@override
FunctionBody get body => _body;
@override
void set body(FunctionBody functionBody) {
_body = _becomeParentOf(functionBody as FunctionBodyImpl);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(externalKeyword)
..add(modifierKeyword)
..add(_returnType)
..add(propertyKeyword)
..add(operatorKeyword)
..add(_name)
..add(_parameters)
..add(_body);
/// Return the element associated with this method, or `null` if the AST
/// structure has not been resolved. The element can either be a
/// [MethodElement], if this represents the declaration of a normal method, or
/// a [PropertyAccessorElement] if this represents the declaration of either a
/// getter or a setter.
@override
ExecutableElement get declaredElement =>
_name?.staticElement as ExecutableElement;
@deprecated
@override
ExecutableElement get element => declaredElement;
@override
Token get endToken => _body.endToken;
@override
Token get firstTokenAfterCommentAndMetadata {
if (externalKeyword != null) {
return externalKeyword;
} else if (modifierKeyword != null) {
return modifierKeyword;
} else if (_returnType != null) {
return _returnType.beginToken;
} else if (propertyKeyword != null) {
return propertyKeyword;
} else if (operatorKeyword != null) {
return operatorKeyword;
}
return _name.beginToken;
}
@override
bool get isAbstract {
FunctionBody body = _body;
return externalKeyword == null &&
(body is EmptyFunctionBody && !body.semicolon.isSynthetic);
}
@override
bool get isGetter => propertyKeyword?.keyword == Keyword.GET;
@override
bool get isOperator => operatorKeyword != null;
@override
bool get isSetter => propertyKeyword?.keyword == Keyword.SET;
@override
bool get isStatic => modifierKeyword?.keyword == Keyword.STATIC;
@override
SimpleIdentifier get name => _name;
@override
void set name(SimpleIdentifier identifier) {
_name = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
FormalParameterList get parameters => _parameters;
@override
void set parameters(FormalParameterList parameters) {
_parameters = _becomeParentOf(parameters as FormalParameterListImpl);
}
@override
TypeAnnotation get returnType => _returnType;
@override
void set returnType(TypeAnnotation type) {
_returnType = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
TypeParameterList get typeParameters => _typeParameters;
@override
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitMethodDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_returnType?.accept(visitor);
_name?.accept(visitor);
_typeParameters?.accept(visitor);
_parameters?.accept(visitor);
_body?.accept(visitor);
}
}
/// The invocation of either a function or a method. Invocations of functions
/// resulting from evaluating an expression are represented by
/// [FunctionExpressionInvocation] nodes. Invocations of getters and setters are
/// represented by either [PrefixedIdentifier] or [PropertyAccess] nodes.
///
/// methodInvocation ::=
/// ([Expression] '.')? [SimpleIdentifier] [TypeArgumentList]?
/// [ArgumentList]
class MethodInvocationImpl extends InvocationExpressionImpl
implements MethodInvocation {
/// The expression producing the object on which the method is defined, or
/// `null` if there is no target (that is, the target is implicitly `this`).
ExpressionImpl _target;
/// The operator that separates the target from the method name, or `null`
/// if there is no target. In an ordinary method invocation this will be a
/// period ('.'). In a cascade section this will be the cascade operator
/// ('..' | '?..').
@override
Token operator;
/// The name of the method being invoked.
SimpleIdentifierImpl _methodName;
/// The invoke type of the [methodName] if the target element is a getter,
/// or `null` otherwise.
DartType _methodNameType;
/// Initialize a newly created method invocation. The [target] and [operator]
/// can be `null` if there is no target.
MethodInvocationImpl(
ExpressionImpl target,
this.operator,
SimpleIdentifierImpl methodName,
TypeArgumentListImpl typeArguments,
ArgumentListImpl argumentList)
: super(typeArguments, argumentList) {
_target = _becomeParentOf(target);
_methodName = _becomeParentOf(methodName);
}
@override
Token get beginToken {
if (_target != null) {
return _target.beginToken;
} else if (operator != null) {
return operator;
}
return _methodName.beginToken;
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(_target)
..add(operator)
..add(_methodName)
..add(_argumentList);
@override
Token get endToken => _argumentList.endToken;
@override
Expression get function => methodName;
@override
bool get isCascaded =>
operator != null &&
(operator.type == TokenType.PERIOD_PERIOD ||
operator.type == TokenType.QUESTION_PERIOD_PERIOD);
@override
bool get isNullAware => operator?.type == TokenType.QUESTION_PERIOD;
@override
SimpleIdentifier get methodName => _methodName;
@override
void set methodName(SimpleIdentifier identifier) {
_methodName = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
/// The invoke type of the [methodName].
///
/// If the target element is a [MethodElement], this is the same as the
/// [staticInvokeType]. If the target element is a getter, presumably
/// returning an [ExecutableElement] so that it can be invoked in this
/// [MethodInvocation], then this type is the type of the getter, and the
/// [staticInvokeType] is the invoked type of the returned element.
DartType get methodNameType => _methodNameType ?? staticInvokeType;
/// Set the [methodName] invoke type, only if the target element is a getter.
/// Otherwise, the target element itself is invoked, [_methodNameType] is
/// `null`, and the getter will return [staticInvokeType].
set methodNameType(DartType methodNameType) {
_methodNameType = methodNameType;
}
@override
Precedence get precedence => Precedence.postfix;
@override
Expression get realTarget {
if (isCascaded) {
AstNode ancestor = parent;
while (ancestor is! CascadeExpression) {
if (ancestor == null) {
return _target;
}
ancestor = ancestor.parent;
}
return (ancestor as CascadeExpression).target;
}
return _target;
}
@override
Expression get target => _target;
@override
void set target(Expression expression) {
_target = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitMethodInvocation(this);
@override
void visitChildren(AstVisitor visitor) {
_target?.accept(visitor);
_methodName?.accept(visitor);
_typeArguments?.accept(visitor);
_argumentList?.accept(visitor);
}
}
/// The declaration of a mixin.
///
/// mixinDeclaration ::=
/// metadata? 'mixin' [SimpleIdentifier] [TypeParameterList]?
/// [RequiresClause]? [ImplementsClause]? '{' [ClassMember]* '}'
class MixinDeclarationImpl extends ClassOrMixinDeclarationImpl
implements MixinDeclaration {
@override
Token mixinKeyword;
/// The on clause for the mixin, or `null` if the mixin does not have any
/// super-class constraints.
OnClauseImpl _onClause;
/// Initialize a newly created mixin declaration. Either or both of the
/// [comment] and [metadata] can be `null` if the mixin does not have the
/// corresponding attribute. The [typeParameters] can be `null` if the mixin
/// does not have any type parameters. Either or both of the [onClause],
/// and [implementsClause] can be `null` if the mixin does not have the
/// corresponding clause. The list of [members] can be `null` if the mixin
/// does not have any members.
MixinDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
this.mixinKeyword,
SimpleIdentifierImpl name,
TypeParameterListImpl typeParameters,
OnClauseImpl onClause,
ImplementsClauseImpl implementsClause,
Token leftBracket,
List<ClassMember> members,
Token rightBracket)
: super(comment, metadata, name, typeParameters, implementsClause,
leftBracket, members, rightBracket) {
_onClause = _becomeParentOf(onClause);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(mixinKeyword)
..add(_name)
..add(_typeParameters)
..add(_onClause)
..add(_implementsClause)
..add(leftBracket)
..addAll(members)
..add(rightBracket);
@override
ClassElement get declaredElement => _name?.staticElement as ClassElement;
@deprecated
@override
Element get element => declaredElement;
@override
Token get firstTokenAfterCommentAndMetadata {
return mixinKeyword;
}
@override
ImplementsClause get implementsClause => _implementsClause;
void set implementsClause(ImplementsClause implementsClause) {
_implementsClause =
_becomeParentOf(implementsClause as ImplementsClauseImpl);
}
@override
NodeList<ClassMember> get members => _members;
@override
OnClause get onClause => _onClause;
void set onClause(OnClause onClause) {
_onClause = _becomeParentOf(onClause as OnClauseImpl);
}
@override
TypeParameterList get typeParameters => _typeParameters;
void set typeParameters(TypeParameterList typeParameters) {
_typeParameters = _becomeParentOf(typeParameters as TypeParameterListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitMixinDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_name?.accept(visitor);
_typeParameters?.accept(visitor);
_onClause?.accept(visitor);
_implementsClause?.accept(visitor);
members.accept(visitor);
}
}
/// A node that declares a single name within the scope of a compilation unit.
abstract class NamedCompilationUnitMemberImpl extends CompilationUnitMemberImpl
implements NamedCompilationUnitMember {
/// The name of the member being declared.
SimpleIdentifierImpl _name;
/// Initialize a newly created compilation unit member with the given [name].
/// Either or both of the [comment] and [metadata] can be `null` if the member
/// does not have the corresponding attribute.
NamedCompilationUnitMemberImpl(
CommentImpl comment, List<Annotation> metadata, SimpleIdentifierImpl name)
: super(comment, metadata) {
_name = _becomeParentOf(name);
}
@override
SimpleIdentifier get name => _name;
@override
void set name(SimpleIdentifier identifier) {
_name = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
}
/// An expression that has a name associated with it. They are used in method
/// invocations when there are named parameters.
///
/// namedExpression ::=
/// [Label] [Expression]
class NamedExpressionImpl extends ExpressionImpl implements NamedExpression {
/// The name associated with the expression.
LabelImpl _name;
/// The expression with which the name is associated.
ExpressionImpl _expression;
/// Initialize a newly created named expression..
NamedExpressionImpl(LabelImpl name, ExpressionImpl expression) {
_name = _becomeParentOf(name);
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken => _name.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_name)..add(_expression);
@override
ParameterElement get element {
Element element = _name.label.staticElement;
if (element is ParameterElement) {
return element;
}
return null;
}
@override
Token get endToken => _expression.endToken;
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
Label get name => _name;
@override
void set name(Label identifier) {
_name = _becomeParentOf(identifier as LabelImpl);
}
@override
Precedence get precedence => Precedence.none;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitNamedExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_name?.accept(visitor);
_expression?.accept(visitor);
}
}
/// A node that represents a directive that impacts the namespace of a library.
///
/// directive ::=
/// [ExportDirective]
/// | [ImportDirective]
abstract class NamespaceDirectiveImpl extends UriBasedDirectiveImpl
implements NamespaceDirective {
/// The token representing the 'import' or 'export' keyword.
@override
Token keyword;
/// The configurations used to control which library will actually be loaded
/// at run-time.
NodeList<Configuration> _configurations;
/// The combinators used to control which names are imported or exported.
NodeList<Combinator> _combinators;
/// The semicolon terminating the directive.
@override
Token semicolon;
@override
String selectedUriContent;
@override
Source selectedSource;
/// Initialize a newly created namespace directive. Either or both of the
/// [comment] and [metadata] can be `null` if the directive does not have the
/// corresponding attribute. The list of [combinators] can be `null` if there
/// are no combinators.
NamespaceDirectiveImpl(
CommentImpl comment,
List<Annotation> metadata,
this.keyword,
StringLiteralImpl libraryUri,
List<Configuration> configurations,
List<Combinator> combinators,
this.semicolon)
: super(comment, metadata, libraryUri) {
_configurations = new NodeListImpl<Configuration>(this, configurations);
_combinators = new NodeListImpl<Combinator>(this, combinators);
}
@override
NodeList<Combinator> get combinators => _combinators;
@override
NodeList<Configuration> get configurations => _configurations;
@override
Token get endToken => semicolon;
@override
Token get firstTokenAfterCommentAndMetadata => keyword;
@deprecated
@override
Source get source => selectedSource;
@deprecated
@override
void set source(Source source) {
selectedSource = source;
}
@override
LibraryElement get uriElement;
}
/// The "native" clause in an class declaration.
///
/// nativeClause ::=
/// 'native' [StringLiteral]
class NativeClauseImpl extends AstNodeImpl implements NativeClause {
/// The token representing the 'native' keyword.
@override
Token nativeKeyword;
/// The name of the native object that implements the class.
StringLiteralImpl _name;
/// Initialize a newly created native clause.
NativeClauseImpl(this.nativeKeyword, StringLiteralImpl name) {
_name = _becomeParentOf(name);
}
@override
Token get beginToken => nativeKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(nativeKeyword)..add(_name);
@override
Token get endToken => _name.endToken;
@override
StringLiteral get name => _name;
@override
void set name(StringLiteral name) {
_name = _becomeParentOf(name as StringLiteralImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitNativeClause(this);
@override
void visitChildren(AstVisitor visitor) {
_name?.accept(visitor);
}
}
/// A function body that consists of a native keyword followed by a string
/// literal.
///
/// nativeFunctionBody ::=
/// 'native' [SimpleStringLiteral] ';'
class NativeFunctionBodyImpl extends FunctionBodyImpl
implements NativeFunctionBody {
/// The token representing 'native' that marks the start of the function body.
@override
Token nativeKeyword;
/// The string literal, after the 'native' token.
StringLiteralImpl _stringLiteral;
/// The token representing the semicolon that marks the end of the function
/// body.
@override
Token semicolon;
/// Initialize a newly created function body consisting of the 'native' token,
/// a string literal, and a semicolon.
NativeFunctionBodyImpl(
this.nativeKeyword, StringLiteralImpl stringLiteral, this.semicolon) {
_stringLiteral = _becomeParentOf(stringLiteral);
}
@override
Token get beginToken => nativeKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(nativeKeyword)
..add(_stringLiteral)
..add(semicolon);
@override
Token get endToken => semicolon;
@override
StringLiteral get stringLiteral => _stringLiteral;
@override
void set stringLiteral(StringLiteral stringLiteral) {
_stringLiteral = _becomeParentOf(stringLiteral as StringLiteralImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitNativeFunctionBody(this);
@override
void visitChildren(AstVisitor visitor) {
_stringLiteral?.accept(visitor);
}
}
/// A list of AST nodes that have a common parent.
class NodeListImpl<E extends AstNode> with ListMixin<E> implements NodeList<E> {
/// The node that is the parent of each of the elements in the list.
AstNodeImpl _owner;
/// The elements contained in the list.
List<E> _elements = <E>[];
/// Initialize a newly created list of nodes such that all of the nodes that
/// are added to the list will have their parent set to the given [owner]. The
/// list will initially be populated with the given [elements].
NodeListImpl(this._owner, [List<E> elements]) {
addAll(elements);
}
@override
Token get beginToken {
if (_elements.isEmpty) {
return null;
}
return _elements[0].beginToken;
}
@override
Token get endToken {
int length = _elements.length;
if (length == 0) {
return null;
}
return _elements[length - 1].endToken;
}
int get length => _elements.length;
@deprecated // Never intended for public use.
@override
void set length(int newLength) {
throw new UnsupportedError("Cannot resize NodeList.");
}
@override
AstNode get owner => _owner;
@override
void set owner(AstNode value) {
_owner = value as AstNodeImpl;
}
E operator [](int index) {
if (index < 0 || index >= _elements.length) {
throw new RangeError("Index: $index, Size: ${_elements.length}");
}
return _elements[index];
}
void operator []=(int index, E node) {
if (index < 0 || index >= _elements.length) {
throw new RangeError("Index: $index, Size: ${_elements.length}");
}
_owner._becomeParentOf(node as AstNodeImpl);
_elements[index] = node;
}
@override
accept(AstVisitor visitor) {
int length = _elements.length;
for (var i = 0; i < length; i++) {
_elements[i].accept(visitor);
}
}
@override
void add(E node) {
insert(length, node);
}
@override
bool addAll(Iterable<E> nodes) {
if (nodes != null && nodes.isNotEmpty) {
if (nodes is List<E>) {
int length = nodes.length;
for (int i = 0; i < length; i++) {
E node = nodes[i];
_elements.add(node);
_owner._becomeParentOf(node as AstNodeImpl);
}
} else {
for (E node in nodes) {
_elements.add(node);
_owner._becomeParentOf(node as AstNodeImpl);
}
}
return true;
}
return false;
}
@override
void clear() {
_elements = <E>[];
}
@override
void insert(int index, E node) {
int length = _elements.length;
if (index < 0 || index > length) {
throw new RangeError("Index: $index, Size: ${_elements.length}");
}
_owner._becomeParentOf(node as AstNodeImpl);
if (length == 0) {
_elements.add(node);
} else {
_elements.insert(index, node);
}
}
@override
E removeAt(int index) {
if (index < 0 || index >= _elements.length) {
throw new RangeError("Index: $index, Size: ${_elements.length}");
}
E removedNode = _elements[index];
_elements.removeAt(index);
return removedNode;
}
/// This is non-API and may be changed or removed at any point.
///
/// Changes the length of this list
/// If [newLength] is greater than the current length,
/// entries are initialized to `null`.
///
/// This list should NOT contain any `null` elements,
/// so be sure to immediately follow a call to this method with calls
/// to replace all the `null` elements with non-`null` elements.
void setLength(int newLength) {
_elements.length = newLength;
}
}
/// A formal parameter that is required (is not optional).
///
/// normalFormalParameter ::=
/// [FunctionTypedFormalParameter]
/// | [FieldFormalParameter]
/// | [SimpleFormalParameter]
abstract class NormalFormalParameterImpl extends FormalParameterImpl
implements NormalFormalParameter {
/// The documentation comment associated with this parameter, or `null` if
/// this parameter does not have a documentation comment associated with it.
CommentImpl _comment;
/// The annotations associated with this parameter.
NodeList<Annotation> _metadata;
/// The 'covariant' keyword, or `null` if the keyword was not used.
Token covariantKeyword;
/// The 'required' keyword, or `null` if the keyword was not used.
Token requiredKeyword;
/// The name of the parameter being declared.
SimpleIdentifierImpl _identifier;
/// Initialize a newly created formal parameter. Either or both of the
/// [comment] and [metadata] can be `null` if the parameter does not have the
/// corresponding attribute.
NormalFormalParameterImpl(
CommentImpl comment,
List<Annotation> metadata,
this.covariantKeyword,
this.requiredKeyword,
SimpleIdentifierImpl identifier) {
_comment = _becomeParentOf(comment);
_metadata = new NodeListImpl<Annotation>(this, metadata);
_identifier = _becomeParentOf(identifier);
}
@override
Comment get documentationComment => _comment;
@override
void set documentationComment(Comment comment) {
_comment = _becomeParentOf(comment as CommentImpl);
}
@override
SimpleIdentifier get identifier => _identifier;
@override
void set identifier(SimpleIdentifier identifier) {
_identifier = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@deprecated
@override
ParameterKind get kind {
AstNode parent = this.parent;
if (parent is DefaultFormalParameter) {
return parent.kind;
}
return ParameterKind.REQUIRED;
}
@override
NodeList<Annotation> get metadata => _metadata;
@override
void set metadata(List<Annotation> metadata) {
_metadata.clear();
_metadata.addAll(metadata);
}
@override
List<AstNode> get sortedCommentAndAnnotations {
return <AstNode>[]
..add(_comment)
..addAll(_metadata)
..sort(AstNode.LEXICAL_ORDER);
}
ChildEntities get _childEntities {
ChildEntities result = new ChildEntities();
if (_commentIsBeforeAnnotations()) {
result
..add(_comment)
..addAll(_metadata);
} else {
result.addAll(sortedCommentAndAnnotations);
}
if (covariantKeyword != null) {
result.add(covariantKeyword);
}
return result;
}
@override
void visitChildren(AstVisitor visitor) {
//
// Note that subclasses are responsible for visiting the identifier because
// they often need to visit other nodes before visiting the identifier.
//
if (_commentIsBeforeAnnotations()) {
_comment?.accept(visitor);
_metadata.accept(visitor);
} else {
List<AstNode> children = sortedCommentAndAnnotations;
int length = children.length;
for (int i = 0; i < length; i++) {
children[i].accept(visitor);
}
}
}
/// Return `true` if the comment is lexically before any annotations.
bool _commentIsBeforeAnnotations() {
if (_comment == null || _metadata.isEmpty) {
return true;
}
Annotation firstAnnotation = _metadata[0];
return _comment.offset < firstAnnotation.offset;
}
}
/// A null literal expression.
///
/// nullLiteral ::=
/// 'null'
class NullLiteralImpl extends LiteralImpl implements NullLiteral {
/// The token representing the literal.
Token literal;
/// Initialize a newly created null literal.
NullLiteralImpl(this.literal);
@override
Token get beginToken => literal;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(literal);
@override
Token get endToken => literal;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitNullLiteral(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// The "on" clause in a mixin declaration.
///
/// onClause ::=
/// 'on' [TypeName] (',' [TypeName])*
class OnClauseImpl extends AstNodeImpl implements OnClause {
@override
Token onKeyword;
/// The classes are super-class constraints for the mixin.
NodeList<TypeName> _superclassConstraints;
/// Initialize a newly created on clause.
OnClauseImpl(this.onKeyword, List<TypeName> superclassConstraints) {
_superclassConstraints =
new NodeListImpl<TypeName>(this, superclassConstraints);
}
@override
Token get beginToken => onKeyword;
@override
// TODO(paulberry): add commas.
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(onKeyword)
..addAll(superclassConstraints);
@override
Token get endToken => _superclassConstraints.endToken;
@override
NodeList<TypeName> get superclassConstraints => _superclassConstraints;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitOnClause(this);
@override
void visitChildren(AstVisitor visitor) {
_superclassConstraints.accept(visitor);
}
}
/// A parenthesized expression.
///
/// parenthesizedExpression ::=
/// '(' [Expression] ')'
class ParenthesizedExpressionImpl extends ExpressionImpl
implements ParenthesizedExpression {
/// The left parenthesis.
Token leftParenthesis;
/// The expression within the parentheses.
ExpressionImpl _expression;
/// The right parenthesis.
Token rightParenthesis;
/// Initialize a newly created parenthesized expression.
ParenthesizedExpressionImpl(
this.leftParenthesis, ExpressionImpl expression, this.rightParenthesis) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken => leftParenthesis;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(leftParenthesis)
..add(_expression)
..add(rightParenthesis);
@override
Token get endToken => rightParenthesis;
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.primary;
@override
Expression get unParenthesized {
// This is somewhat inefficient, but it avoids a stack overflow in the
// degenerate case.
Expression expression = _expression;
while (expression is ParenthesizedExpressionImpl) {
expression = (expression as ParenthesizedExpressionImpl)._expression;
}
return expression;
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitParenthesizedExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// A part directive.
///
/// partDirective ::=
/// [Annotation] 'part' [StringLiteral] ';'
class PartDirectiveImpl extends UriBasedDirectiveImpl implements PartDirective {
/// The token representing the 'part' keyword.
@override
Token partKeyword;
/// The semicolon terminating the directive.
@override
Token semicolon;
/// Initialize a newly created part directive. Either or both of the [comment]
/// and [metadata] can be `null` if the directive does not have the
/// corresponding attribute.
PartDirectiveImpl(CommentImpl comment, List<Annotation> metadata,
this.partKeyword, StringLiteralImpl partUri, this.semicolon)
: super(comment, metadata, partUri);
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(partKeyword)..add(_uri)..add(semicolon);
@override
Token get endToken => semicolon;
@override
Token get firstTokenAfterCommentAndMetadata => partKeyword;
@override
Token get keyword => partKeyword;
@override
CompilationUnitElement get uriElement => element as CompilationUnitElement;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitPartDirective(this);
}
/// A part-of directive.
///
/// partOfDirective ::=
/// [Annotation] 'part' 'of' [Identifier] ';'
class PartOfDirectiveImpl extends DirectiveImpl implements PartOfDirective {
/// The token representing the 'part' keyword.
@override
Token partKeyword;
/// The token representing the 'of' keyword.
@override
Token ofKeyword;
/// The URI of the library that the containing compilation unit is part of.
StringLiteralImpl _uri;
/// The name of the library that the containing compilation unit is part of,
/// or `null` if no name was given (typically because a library URI was
/// provided).
LibraryIdentifierImpl _libraryName;
/// The semicolon terminating the directive.
@override
Token semicolon;
/// Initialize a newly created part-of directive. Either or both of the
/// [comment] and [metadata] can be `null` if the directive does not have the
/// corresponding attribute.
PartOfDirectiveImpl(
CommentImpl comment,
List<Annotation> metadata,
this.partKeyword,
this.ofKeyword,
StringLiteralImpl uri,
LibraryIdentifierImpl libraryName,
this.semicolon)
: super(comment, metadata) {
_uri = _becomeParentOf(uri);
_libraryName = _becomeParentOf(libraryName);
}
@override
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(partKeyword)
..add(ofKeyword)
..add(_uri)
..add(_libraryName)
..add(semicolon);
@override
Token get endToken => semicolon;
@override
Token get firstTokenAfterCommentAndMetadata => partKeyword;
@override
Token get keyword => partKeyword;
@override
LibraryIdentifier get libraryName => _libraryName;
@override
void set libraryName(LibraryIdentifier libraryName) {
_libraryName = _becomeParentOf(libraryName as LibraryIdentifierImpl);
}
@override
StringLiteral get uri => _uri;
@override
void set uri(StringLiteral uri) {
_uri = _becomeParentOf(uri as StringLiteralImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitPartOfDirective(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_libraryName?.accept(visitor);
_uri?.accept(visitor);
}
}
/// A postfix unary expression.
///
/// postfixExpression ::=
/// [Expression] [Token]
class PostfixExpressionImpl extends ExpressionImpl
implements PostfixExpression {
/// The expression computing the operand for the operator.
ExpressionImpl _operand;
/// The postfix operator being applied to the operand.
@override
Token operator;
/// The element associated with the operator based on the static type of the
/// operand, or `null` if the AST structure has not been resolved, if the
/// operator is not user definable, or if the operator could not be resolved.
@override
MethodElement staticElement;
/// Initialize a newly created postfix expression.
PostfixExpressionImpl(ExpressionImpl operand, this.operator) {
_operand = _becomeParentOf(operand);
}
@override
Token get beginToken => _operand.beginToken;
@override
@deprecated
MethodElement get bestElement => staticElement;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_operand)..add(operator);
@override
Token get endToken => operator;
@override
Expression get operand => _operand;
@override
void set operand(Expression expression) {
_operand = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.postfix;
@deprecated
@override
MethodElement get propagatedElement => null;
@deprecated
@override
set propagatedElement(MethodElement element) {}
/// If the AST structure has been resolved, and the function being invoked is
/// known based on static type information, then return the parameter element
/// representing the parameter to which the value of the operand will be
/// bound. Otherwise, return `null`.
ParameterElement get _staticParameterElementForOperand {
if (staticElement == null) {
return null;
}
List<ParameterElement> parameters = staticElement.parameters;
if (parameters.isEmpty) {
return null;
}
return parameters[0];
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitPostfixExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_operand?.accept(visitor);
}
}
/// An identifier that is prefixed or an access to an object property where the
/// target of the property access is a simple identifier.
///
/// prefixedIdentifier ::=
/// [SimpleIdentifier] '.' [SimpleIdentifier]
class PrefixedIdentifierImpl extends IdentifierImpl
implements PrefixedIdentifier {
/// The prefix associated with the library in which the identifier is defined.
SimpleIdentifierImpl _prefix;
/// The period used to separate the prefix from the identifier.
Token period;
/// The identifier being prefixed.
SimpleIdentifierImpl _identifier;
/// Initialize a newly created prefixed identifier.
PrefixedIdentifierImpl(SimpleIdentifierImpl prefix, this.period,
SimpleIdentifierImpl identifier) {
_prefix = _becomeParentOf(prefix);
_identifier = _becomeParentOf(identifier);
}
/// Initialize a newly created prefixed identifier that does not take
/// ownership of the components. The resulting node is only for temporary use,
/// such as by resolution.
PrefixedIdentifierImpl.temp(this._prefix, this._identifier) : period = null;
@override
Token get beginToken => _prefix.beginToken;
@override
@deprecated
Element get bestElement {
if (_identifier == null) {
return null;
}
return _identifier.staticElement;
}
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_prefix)..add(period)..add(_identifier);
@override
Token get endToken => _identifier.endToken;
@override
SimpleIdentifier get identifier => _identifier;
@override
void set identifier(SimpleIdentifier identifier) {
_identifier = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
bool get isDeferred {
Element element = _prefix.staticElement;
if (element is PrefixElement) {
List<ImportElement> imports =
element.enclosingElement.getImportsWithPrefix(element);
if (imports.length != 1) {
return false;
}
return imports[0].isDeferred;
}
return false;
}
@override
String get name => "${_prefix.name}.${_identifier.name}";
@override
Precedence get precedence => Precedence.postfix;
@override
SimpleIdentifier get prefix => _prefix;
@override
void set prefix(SimpleIdentifier identifier) {
_prefix = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@deprecated
@override
Element get propagatedElement => null;
@override
Element get staticElement {
if (_identifier == null) {
return null;
}
return _identifier.staticElement;
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitPrefixedIdentifier(this);
@override
void visitChildren(AstVisitor visitor) {
_prefix?.accept(visitor);
_identifier?.accept(visitor);
}
}
/// A prefix unary expression.
///
/// prefixExpression ::=
/// [Token] [Expression]
class PrefixExpressionImpl extends ExpressionImpl implements PrefixExpression {
/// The prefix operator being applied to the operand.
Token operator;
/// The expression computing the operand for the operator.
ExpressionImpl _operand;
/// The element associated with the operator based on the static type of the
/// operand, or `null` if the AST structure has not been resolved, if the
/// operator is not user definable, or if the operator could not be resolved.
MethodElement staticElement;
/// Initialize a newly created prefix expression.
PrefixExpressionImpl(this.operator, ExpressionImpl operand) {
_operand = _becomeParentOf(operand);
}
@override
Token get beginToken => operator;
@override
@deprecated
MethodElement get bestElement => staticElement;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(operator)..add(_operand);
@override
Token get endToken => _operand.endToken;
@override
Expression get operand => _operand;
@override
void set operand(Expression expression) {
_operand = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.prefix;
@deprecated
@override
MethodElement get propagatedElement => null;
@deprecated
@override
set propagatedElement(MethodElement element) {}
/// If the AST structure has been resolved, and the function being invoked is
/// known based on static type information, then return the parameter element
/// representing the parameter to which the value of the operand will be
/// bound. Otherwise, return `null`.
ParameterElement get _staticParameterElementForOperand {
if (staticElement == null) {
return null;
}
List<ParameterElement> parameters = staticElement.parameters;
if (parameters.isEmpty) {
return null;
}
return parameters[0];
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitPrefixExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_operand?.accept(visitor);
}
}
/// The access of a property of an object.
///
/// Note, however, that accesses to properties of objects can also be
/// represented as [PrefixedIdentifier] nodes in cases where the target is also
/// a simple identifier.
///
/// propertyAccess ::=
/// [Expression] '.' [SimpleIdentifier]
class PropertyAccessImpl extends ExpressionImpl implements PropertyAccess {
/// The expression computing the object defining the property being accessed.
ExpressionImpl _target;
/// The property access operator.
Token operator;
/// The name of the property being accessed.
SimpleIdentifierImpl _propertyName;
/// Initialize a newly created property access expression.
PropertyAccessImpl(
ExpressionImpl target, this.operator, SimpleIdentifierImpl propertyName) {
_target = _becomeParentOf(target);
_propertyName = _becomeParentOf(propertyName);
}
@override
Token get beginToken {
if (_target != null) {
return _target.beginToken;
}
return operator;
}
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_target)..add(operator)..add(_propertyName);
@override
Token get endToken => _propertyName.endToken;
@override
bool get isAssignable => true;
@override
bool get isCascaded =>
operator != null &&
(operator.type == TokenType.PERIOD_PERIOD ||
operator.type == TokenType.QUESTION_PERIOD_PERIOD);
@override
bool get isNullAware =>
operator != null && operator.type == TokenType.QUESTION_PERIOD;
@override
Precedence get precedence => Precedence.postfix;
@override
SimpleIdentifier get propertyName => _propertyName;
@override
void set propertyName(SimpleIdentifier identifier) {
_propertyName = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
Expression get realTarget {
if (isCascaded) {
AstNode ancestor = parent;
while (ancestor is! CascadeExpression) {
if (ancestor == null) {
return _target;
}
ancestor = ancestor.parent;
}
return (ancestor as CascadeExpression).target;
}
return _target;
}
@override
Expression get target => _target;
@override
void set target(Expression expression) {
_target = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitPropertyAccess(this);
@override
void visitChildren(AstVisitor visitor) {
_target?.accept(visitor);
_propertyName?.accept(visitor);
}
}
/// The invocation of a constructor in the same class from within a
/// constructor's initialization list.
///
/// redirectingConstructorInvocation ::=
/// 'this' ('.' identifier)? arguments
class RedirectingConstructorInvocationImpl extends ConstructorInitializerImpl
implements RedirectingConstructorInvocation {
/// The token for the 'this' keyword.
Token thisKeyword;
/// The token for the period before the name of the constructor that is being
/// invoked, or `null` if the unnamed constructor is being invoked.
Token period;
/// The name of the constructor that is being invoked, or `null` if the
/// unnamed constructor is being invoked.
SimpleIdentifierImpl _constructorName;
/// The list of arguments to the constructor.
ArgumentListImpl _argumentList;
/// The element associated with the constructor based on static type
/// information, or `null` if the AST structure has not been resolved or if
/// the constructor could not be resolved.
ConstructorElement staticElement;
/// Initialize a newly created redirecting invocation to invoke the
/// constructor with the given name with the given arguments. The
/// [constructorName] can be `null` if the constructor being invoked is the
/// unnamed constructor.
RedirectingConstructorInvocationImpl(this.thisKeyword, this.period,
SimpleIdentifierImpl constructorName, ArgumentListImpl argumentList) {
_constructorName = _becomeParentOf(constructorName);
_argumentList = _becomeParentOf(argumentList);
}
@override
ArgumentList get argumentList => _argumentList;
@override
void set argumentList(ArgumentList argumentList) {
_argumentList = _becomeParentOf(argumentList as ArgumentListImpl);
}
@override
Token get beginToken => thisKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(thisKeyword)
..add(period)
..add(_constructorName)
..add(_argumentList);
@override
SimpleIdentifier get constructorName => _constructorName;
@override
void set constructorName(SimpleIdentifier identifier) {
_constructorName = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
Token get endToken => _argumentList.endToken;
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitRedirectingConstructorInvocation(this);
@override
void visitChildren(AstVisitor visitor) {
_constructorName?.accept(visitor);
_argumentList?.accept(visitor);
}
}
/// A rethrow expression.
///
/// rethrowExpression ::=
/// 'rethrow'
class RethrowExpressionImpl extends ExpressionImpl
implements RethrowExpression {
/// The token representing the 'rethrow' keyword.
Token rethrowKeyword;
/// Initialize a newly created rethrow expression.
RethrowExpressionImpl(this.rethrowKeyword);
@override
Token get beginToken => rethrowKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(rethrowKeyword);
@override
Token get endToken => rethrowKeyword;
@override
Precedence get precedence => Precedence.assignment;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitRethrowExpression(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// A return statement.
///
/// returnStatement ::=
/// 'return' [Expression]? ';'
class ReturnStatementImpl extends StatementImpl implements ReturnStatement {
/// The token representing the 'return' keyword.
Token returnKeyword;
/// The expression computing the value to be returned, or `null` if no
/// explicit value was provided.
ExpressionImpl _expression;
/// The semicolon terminating the statement.
Token semicolon;
/// Initialize a newly created return statement. The [expression] can be
/// `null` if no explicit value was provided.
ReturnStatementImpl(
this.returnKeyword, ExpressionImpl expression, this.semicolon) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken => returnKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(returnKeyword)..add(_expression)..add(semicolon);
@override
Token get endToken => semicolon;
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitReturnStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// A script tag that can optionally occur at the beginning of a compilation
/// unit.
///
/// scriptTag ::=
/// '#!' (~NEWLINE)* NEWLINE
class ScriptTagImpl extends AstNodeImpl implements ScriptTag {
/// The token representing this script tag.
Token scriptTag;
/// Initialize a newly created script tag.
ScriptTagImpl(this.scriptTag);
@override
Token get beginToken => scriptTag;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(scriptTag);
@override
Token get endToken => scriptTag;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitScriptTag(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
class SetOrMapLiteralImpl extends TypedLiteralImpl implements SetOrMapLiteral {
@override
Token leftBracket;
/// The syntactic elements in the set.
NodeList<CollectionElement> _elements;
@override
Token rightBracket;
/// A representation of whether this literal represents a map or a set, or
/// whether the kind has not or cannot be determined.
_SetOrMapKind _resolvedKind;
/// The context type computed by
/// [ResolverVisitor._computeSetOrMapContextType].
///
/// Note that this is not the same as the context pushed down by type
/// inference (which can be obtained via [InferenceContext.getContext]). For
/// example, in the following code:
///
/// var m = {};
///
/// The context pushed down by type inference is null, whereas the
/// `contextType` is `Map<dynamic, dynamic>`.
InterfaceType contextType;
/// Initialize a newly created set or map literal. The [constKeyword] can be
/// `null` if the literal is not a constant. The [typeArguments] can be `null`
/// if no type arguments were declared. The [elements] can be `null` if the
/// set is empty.
SetOrMapLiteralImpl(Token constKeyword, TypeArgumentListImpl typeArguments,
this.leftBracket, List<CollectionElement> elements, this.rightBracket)
: super(constKeyword, typeArguments) {
_elements = new NodeListImpl<CollectionElement>(this, elements);
_resolvedKind = _SetOrMapKind.unresolved;
}
@override
Token get beginToken {
if (constKeyword != null) {
return constKeyword;
}
TypeArgumentList typeArguments = this.typeArguments;
if (typeArguments != null) {
return typeArguments.beginToken;
}
return leftBracket;
}
@override
// TODO(paulberry): add commas.
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(leftBracket)
..addAll(elements)
..add(rightBracket);
@override
NodeList<CollectionElement> get elements => _elements;
@override
Token get endToken => rightBracket;
@override
bool get isMap => _resolvedKind == _SetOrMapKind.map;
@override
bool get isSet => _resolvedKind == _SetOrMapKind.set;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitSetOrMapLiteral(this);
void becomeMap() {
assert(_resolvedKind == _SetOrMapKind.unresolved ||
_resolvedKind == _SetOrMapKind.map);
_resolvedKind = _SetOrMapKind.map;
}
void becomeSet() {
assert(_resolvedKind == _SetOrMapKind.unresolved ||
_resolvedKind == _SetOrMapKind.set);
_resolvedKind = _SetOrMapKind.set;
}
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_elements.accept(visitor);
}
}
/// A combinator that restricts the names being imported to those in a given
/// list.
///
/// showCombinator ::=
/// 'show' [SimpleIdentifier] (',' [SimpleIdentifier])*
class ShowCombinatorImpl extends CombinatorImpl implements ShowCombinator {
/// The list of names from the library that are made visible by this
/// combinator.
NodeList<SimpleIdentifier> _shownNames;
/// Initialize a newly created import show combinator.
ShowCombinatorImpl(Token keyword, List<SimpleIdentifier> shownNames)
: super(keyword) {
_shownNames = new NodeListImpl<SimpleIdentifier>(this, shownNames);
}
@override
// TODO(paulberry): add commas.
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(keyword)
..addAll(_shownNames);
@override
Token get endToken => _shownNames.endToken;
@override
NodeList<SimpleIdentifier> get shownNames => _shownNames;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitShowCombinator(this);
@override
void visitChildren(AstVisitor visitor) {
_shownNames.accept(visitor);
}
}
/// A simple formal parameter.
///
/// simpleFormalParameter ::=
/// ('final' [TypeName] | 'var' | [TypeName])? [SimpleIdentifier]
class SimpleFormalParameterImpl extends NormalFormalParameterImpl
implements SimpleFormalParameter {
/// The token representing either the 'final', 'const' or 'var' keyword, or
/// `null` if no keyword was used.
Token keyword;
/// The name of the declared type of the parameter, or `null` if the parameter
/// does not have a declared type.
TypeAnnotationImpl _type;
@override
// TODO(brianwilkerson) This overrides a concrete implementation in which the
// element is assumed to be stored in the `identifier`, but there is no
// corresponding inherited setter. This seems inconsistent and error prone.
ParameterElement declaredElement;
/// Initialize a newly created formal parameter. Either or both of the
/// [comment] and [metadata] can be `null` if the parameter does not have the
/// corresponding attribute. The [keyword] can be `null` if a type was
/// specified. The [type] must be `null` if the keyword is 'var'.
SimpleFormalParameterImpl(
CommentImpl comment,
List<Annotation> metadata,
Token covariantKeyword,
Token requiredKeyword,
this.keyword,
TypeAnnotationImpl type,
SimpleIdentifierImpl identifier)
: super(
comment, metadata, covariantKeyword, requiredKeyword, identifier) {
_type = _becomeParentOf(type);
}
@override
Token get beginToken {
NodeList<Annotation> metadata = this.metadata;
if (metadata.isNotEmpty) {
return metadata.beginToken;
} else if (covariantKeyword != null) {
return covariantKeyword;
} else if (keyword != null) {
return keyword;
} else if (_type != null) {
return _type.beginToken;
}
return identifier?.beginToken;
}
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(keyword)..add(_type)..add(identifier);
@override
Token get endToken => identifier?.endToken ?? type?.endToken;
@override
bool get isConst => keyword?.keyword == Keyword.CONST;
@override
bool get isFinal => keyword?.keyword == Keyword.FINAL;
@override
TypeAnnotation get type => _type;
@override
void set type(TypeAnnotation type) {
_type = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitSimpleFormalParameter(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_type?.accept(visitor);
identifier?.accept(visitor);
}
}
/// A simple identifier.
///
/// simpleIdentifier ::=
/// initialCharacter internalCharacter*
///
/// initialCharacter ::= '_' | '$' | letter
///
/// internalCharacter ::= '_' | '$' | letter | digit
class SimpleIdentifierImpl extends IdentifierImpl implements SimpleIdentifier {
/// The token representing the identifier.
Token token;
/// The element associated with this identifier based on static type
/// information, or `null` if the AST structure has not been resolved or if
/// this identifier could not be resolved.
Element _staticElement;
/// If this expression is both in a getter and setter context, the
/// [AuxiliaryElements] will be set to hold onto the static element from the
/// getter context.
AuxiliaryElements auxiliaryElements;
@override
List<DartType> tearOffTypeArgumentTypes;
/// Initialize a newly created identifier.
SimpleIdentifierImpl(this.token);
@override
Token get beginToken => token;
@override
@deprecated
Element get bestElement => _staticElement;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(token);
@override
Token get endToken => token;
@override
bool get isQualified {
AstNode parent = this.parent;
if (parent is PrefixedIdentifier) {
return identical(parent.identifier, this);
} else if (parent is PropertyAccess) {
return identical(parent.propertyName, this);
} else if (parent is MethodInvocation) {
MethodInvocation invocation = parent;
return identical(invocation.methodName, this) &&
invocation.realTarget != null;
}
return false;
}
@override
bool get isSynthetic => token.isSynthetic;
@override
String get name => token.lexeme;
@override
Precedence get precedence => Precedence.primary;
@deprecated
@override
Element get propagatedElement => null;
@deprecated
@override
void set propagatedElement(Element element) {}
@override
Element get staticElement => _staticElement;
@override
void set staticElement(Element element) {
_staticElement = element;
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitSimpleIdentifier(this);
@override
bool inDeclarationContext() => false;
@override
bool inGetterContext() {
// TODO(brianwilkerson) Convert this to a getter.
AstNode initialParent = this.parent;
AstNode parent = initialParent;
AstNode target = this;
// skip prefix
if (initialParent is PrefixedIdentifier) {
if (identical(initialParent.prefix, this)) {
return true;
}
parent = initialParent.parent;
target = initialParent;
} else if (initialParent is PropertyAccess) {
if (identical(initialParent.target, this)) {
return true;
}
parent = initialParent.parent;
target = initialParent;
}
// skip label
if (parent is Label) {
return false;
}
// analyze usage
if (parent is AssignmentExpression) {
if (identical(parent.leftHandSide, target) &&
parent.operator.type == TokenType.EQ) {
return false;
}
}
if (parent is ConstructorFieldInitializer &&
identical(parent.fieldName, target)) {
return false;
}
if (parent is ForEachPartsWithIdentifier) {
if (identical(parent.identifier, target)) {
return false;
}
}
if (parent is FieldFormalParameter) {
if (identical(parent.identifier, target)) {
return false;
}
}
if (parent is VariableDeclaration) {
if (identical(parent.name, target)) {
return false;
}
}
return true;
}
@override
bool inSetterContext() {
// TODO(brianwilkerson) Convert this to a getter.
AstNode initialParent = this.parent;
AstNode parent = initialParent;
AstNode target = this;
// skip prefix
if (initialParent is PrefixedIdentifier) {
// if this is the prefix, then return false
if (identical(initialParent.prefix, this)) {
return false;
}
parent = initialParent.parent;
target = initialParent;
} else if (initialParent is PropertyAccess) {
if (identical(initialParent.target, this)) {
return false;
}
parent = initialParent.parent;
target = initialParent;
}
// analyze usage
if (parent is PrefixExpression) {
return parent.operator.type.isIncrementOperator;
} else if (parent is PostfixExpression) {
return true;
} else if (parent is AssignmentExpression) {
return identical(parent.leftHandSide, target);
} else if (parent is ForEachPartsWithIdentifier) {
return identical(parent.identifier, target);
}
return false;
}
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// A string literal expression that does not contain any interpolations.
///
/// simpleStringLiteral ::=
/// rawStringLiteral
/// | basicStringLiteral
///
/// rawStringLiteral ::=
/// 'r' basicStringLiteral
///
/// simpleStringLiteral ::=
/// multiLineStringLiteral
/// | singleLineStringLiteral
///
/// multiLineStringLiteral ::=
/// "'''" characters "'''"
/// | '"""' characters '"""'
///
/// singleLineStringLiteral ::=
/// "'" characters "'"
/// | '"' characters '"'
class SimpleStringLiteralImpl extends SingleStringLiteralImpl
implements SimpleStringLiteral {
/// The token representing the literal.
Token literal;
/// The value of the literal.
String _value;
/// Initialize a newly created simple string literal.
SimpleStringLiteralImpl(this.literal, String value) {
_value = StringUtilities.intern(value);
}
@override
Token get beginToken => literal;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(literal);
@override
int get contentsEnd => offset + _helper.end;
@override
int get contentsOffset => offset + _helper.start;
@override
Token get endToken => literal;
@override
bool get isMultiline => _helper.isMultiline;
@override
bool get isRaw => _helper.isRaw;
@override
bool get isSingleQuoted => _helper.isSingleQuoted;
@override
bool get isSynthetic => literal.isSynthetic;
@override
String get value => _value;
@override
void set value(String string) {
_value = StringUtilities.intern(_value);
}
StringLexemeHelper get _helper {
return new StringLexemeHelper(literal.lexeme, true, true);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitSimpleStringLiteral(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
@override
void _appendStringValue(StringBuffer buffer) {
buffer.write(value);
}
}
/// A single string literal expression.
///
/// singleStringLiteral ::=
/// [SimpleStringLiteral]
/// | [StringInterpolation]
abstract class SingleStringLiteralImpl extends StringLiteralImpl
implements SingleStringLiteral {}
class SpreadElementImpl extends AstNodeImpl
implements CollectionElementImpl, SpreadElement {
Token spreadOperator;
ExpressionImpl _expression;
SpreadElementImpl(this.spreadOperator, ExpressionImpl expression) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken => spreadOperator;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(spreadOperator)..add(_expression);
@override
Token get endToken => _expression.endToken;
@override
Expression get expression => _expression;
set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
bool get isNullAware =>
spreadOperator.type == TokenType.PERIOD_PERIOD_PERIOD_QUESTION;
@override
E accept<E>(AstVisitor<E> visitor) {
return visitor.visitSpreadElement(this);
}
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// A node that represents a statement.
///
/// statement ::=
/// [Block]
/// | [VariableDeclarationStatement]
/// | [ForStatement]
/// | [ForEachStatement]
/// | [WhileStatement]
/// | [DoStatement]
/// | [SwitchStatement]
/// | [IfStatement]
/// | [TryStatement]
/// | [BreakStatement]
/// | [ContinueStatement]
/// | [ReturnStatement]
/// | [ExpressionStatement]
/// | [FunctionDeclarationStatement]
abstract class StatementImpl extends AstNodeImpl implements Statement {
@override
Statement get unlabeled => this;
}
/// A string interpolation literal.
///
/// stringInterpolation ::=
/// ''' [InterpolationElement]* '''
/// | '"' [InterpolationElement]* '"'
class StringInterpolationImpl extends SingleStringLiteralImpl
implements StringInterpolation {
/// The elements that will be composed to produce the resulting string.
NodeList<InterpolationElement> _elements;
/// Initialize a newly created string interpolation expression.
StringInterpolationImpl(List<InterpolationElement> elements) {
_elements = new NodeListImpl<InterpolationElement>(this, elements);
}
@override
Token get beginToken => _elements.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..addAll(_elements);
@override
int get contentsEnd {
InterpolationString element = _elements.last;
return element.contentsEnd;
}
@override
int get contentsOffset {
InterpolationString element = _elements.first;
return element.contentsOffset;
}
/// Return the elements that will be composed to produce the resulting string.
NodeList<InterpolationElement> get elements => _elements;
@override
Token get endToken => _elements.endToken;
@override
bool get isMultiline => _firstHelper.isMultiline;
@override
bool get isRaw => false;
@override
bool get isSingleQuoted => _firstHelper.isSingleQuoted;
StringLexemeHelper get _firstHelper {
InterpolationString lastString = _elements.first;
String lexeme = lastString.contents.lexeme;
return new StringLexemeHelper(lexeme, true, false);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitStringInterpolation(this);
@override
void visitChildren(AstVisitor visitor) {
_elements.accept(visitor);
}
@override
void _appendStringValue(StringBuffer buffer) {
throw new ArgumentError();
}
}
/// A helper for analyzing string lexemes.
class StringLexemeHelper {
final String lexeme;
final bool isFirst;
final bool isLast;
bool isRaw = false;
bool isSingleQuoted = false;
bool isMultiline = false;
int start = 0;
int end;
StringLexemeHelper(this.lexeme, this.isFirst, this.isLast) {
if (isFirst) {
isRaw = StringUtilities.startsWithChar(lexeme, 0x72);
if (isRaw) {
start++;
}
if (StringUtilities.startsWith3(lexeme, start, 0x27, 0x27, 0x27)) {
isSingleQuoted = true;
isMultiline = true;
start += 3;
start = _trimInitialWhitespace(start);
} else if (StringUtilities.startsWith3(lexeme, start, 0x22, 0x22, 0x22)) {
isSingleQuoted = false;
isMultiline = true;
start += 3;
start = _trimInitialWhitespace(start);
} else if (start < lexeme.length && lexeme.codeUnitAt(start) == 0x27) {
isSingleQuoted = true;
isMultiline = false;
start++;
} else if (start < lexeme.length && lexeme.codeUnitAt(start) == 0x22) {
isSingleQuoted = false;
isMultiline = false;
start++;
}
}
end = lexeme.length;
if (isLast) {
if (start + 3 <= end &&
(StringUtilities.endsWith3(lexeme, 0x22, 0x22, 0x22) ||
StringUtilities.endsWith3(lexeme, 0x27, 0x27, 0x27))) {
end -= 3;
} else if (start + 1 <= end &&
(StringUtilities.endsWithChar(lexeme, 0x22) ||
StringUtilities.endsWithChar(lexeme, 0x27))) {
end -= 1;
}
}
}
/// Given the [lexeme] for a multi-line string whose content begins at the
/// given [start] index, return the index of the first character that is
/// included in the value of the string. According to the specification:
///
/// If the first line of a multiline string consists solely of the whitespace
/// characters defined by the production WHITESPACE 20.1), possibly prefixed
/// by \, then that line is ignored, including the new line at its end.
int _trimInitialWhitespace(int start) {
int length = lexeme.length;
int index = start;
while (index < length) {
int currentChar = lexeme.codeUnitAt(index);
if (currentChar == 0x0D) {
if (index + 1 < length && lexeme.codeUnitAt(index + 1) == 0x0A) {
return index + 2;
}
return index + 1;
} else if (currentChar == 0x0A) {
return index + 1;
} else if (currentChar == 0x5C) {
if (index + 1 >= length) {
return start;
}
currentChar = lexeme.codeUnitAt(index + 1);
if (currentChar != 0x0D &&
currentChar != 0x0A &&
currentChar != 0x09 &&
currentChar != 0x20) {
return start;
}
} else if (currentChar != 0x09 && currentChar != 0x20) {
return start;
}
index++;
}
return start;
}
}
/// A string literal expression.
///
/// stringLiteral ::=
/// [SimpleStringLiteral]
/// | [AdjacentStrings]
/// | [StringInterpolation]
abstract class StringLiteralImpl extends LiteralImpl implements StringLiteral {
@override
String get stringValue {
StringBuffer buffer = new StringBuffer();
try {
_appendStringValue(buffer);
} on ArgumentError {
return null;
}
return buffer.toString();
}
/// Append the value of this string literal to the given [buffer]. Throw an
/// [ArgumentError] if the string is not a constant string without any
/// string interpolation.
void _appendStringValue(StringBuffer buffer);
}
/// The invocation of a superclass' constructor from within a constructor's
/// initialization list.
///
/// superInvocation ::=
/// 'super' ('.' [SimpleIdentifier])? [ArgumentList]
class SuperConstructorInvocationImpl extends ConstructorInitializerImpl
implements SuperConstructorInvocation {
/// The token for the 'super' keyword.
Token superKeyword;
/// The token for the period before the name of the constructor that is being
/// invoked, or `null` if the unnamed constructor is being invoked.
Token period;
/// The name of the constructor that is being invoked, or `null` if the
/// unnamed constructor is being invoked.
SimpleIdentifierImpl _constructorName;
/// The list of arguments to the constructor.
ArgumentListImpl _argumentList;
/// The element associated with the constructor based on static type
/// information, or `null` if the AST structure has not been resolved or if
/// the constructor could not be resolved.
ConstructorElement staticElement;
/// Initialize a newly created super invocation to invoke the inherited
/// constructor with the given name with the given arguments. The [period] and
/// [constructorName] can be `null` if the constructor being invoked is the
/// unnamed constructor.
SuperConstructorInvocationImpl(this.superKeyword, this.period,
SimpleIdentifierImpl constructorName, ArgumentListImpl argumentList) {
_constructorName = _becomeParentOf(constructorName);
_argumentList = _becomeParentOf(argumentList);
}
@override
ArgumentList get argumentList => _argumentList;
@override
void set argumentList(ArgumentList argumentList) {
_argumentList = _becomeParentOf(argumentList as ArgumentListImpl);
}
@override
Token get beginToken => superKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(superKeyword)
..add(period)
..add(_constructorName)
..add(_argumentList);
@override
SimpleIdentifier get constructorName => _constructorName;
@override
void set constructorName(SimpleIdentifier identifier) {
_constructorName = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
Token get endToken => _argumentList.endToken;
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitSuperConstructorInvocation(this);
@override
void visitChildren(AstVisitor visitor) {
_constructorName?.accept(visitor);
_argumentList?.accept(visitor);
}
}
/// A super expression.
///
/// superExpression ::=
/// 'super'
class SuperExpressionImpl extends ExpressionImpl implements SuperExpression {
/// The token representing the 'super' keyword.
Token superKeyword;
/// Initialize a newly created super expression.
SuperExpressionImpl(this.superKeyword);
@override
Token get beginToken => superKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(superKeyword);
@override
Token get endToken => superKeyword;
@override
Precedence get precedence => Precedence.primary;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitSuperExpression(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// A case in a switch statement.
///
/// switchCase ::=
/// [SimpleIdentifier]* 'case' [Expression] ':' [Statement]*
class SwitchCaseImpl extends SwitchMemberImpl implements SwitchCase {
/// The expression controlling whether the statements will be executed.
ExpressionImpl _expression;
/// Initialize a newly created switch case. The list of [labels] can be `null`
/// if there are no labels.
SwitchCaseImpl(List<Label> labels, Token keyword, ExpressionImpl expression,
Token colon, List<Statement> statements)
: super(labels, keyword, colon, statements) {
_expression = _becomeParentOf(expression);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..addAll(labels)
..add(keyword)
..add(_expression)
..add(colon)
..addAll(statements);
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitSwitchCase(this);
@override
void visitChildren(AstVisitor visitor) {
labels.accept(visitor);
_expression?.accept(visitor);
statements.accept(visitor);
}
}
/// The default case in a switch statement.
///
/// switchDefault ::=
/// [SimpleIdentifier]* 'default' ':' [Statement]*
class SwitchDefaultImpl extends SwitchMemberImpl implements SwitchDefault {
/// Initialize a newly created switch default. The list of [labels] can be
/// `null` if there are no labels.
SwitchDefaultImpl(List<Label> labels, Token keyword, Token colon,
List<Statement> statements)
: super(labels, keyword, colon, statements);
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..addAll(labels)
..add(keyword)
..add(colon)
..addAll(statements);
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitSwitchDefault(this);
@override
void visitChildren(AstVisitor visitor) {
labels.accept(visitor);
statements.accept(visitor);
}
}
/// An element within a switch statement.
///
/// switchMember ::=
/// switchCase
/// | switchDefault
abstract class SwitchMemberImpl extends AstNodeImpl implements SwitchMember {
/// The labels associated with the switch member.
NodeList<Label> _labels;
/// The token representing the 'case' or 'default' keyword.
Token keyword;
/// The colon separating the keyword or the expression from the statements.
Token colon;
/// The statements that will be executed if this switch member is selected.
NodeList<Statement> _statements;
/// Initialize a newly created switch member. The list of [labels] can be
/// `null` if there are no labels.
SwitchMemberImpl(List<Label> labels, this.keyword, this.colon,
List<Statement> statements) {
_labels = new NodeListImpl<Label>(this, labels);
_statements = new NodeListImpl<Statement>(this, statements);
}
@override
Token get beginToken {
if (_labels.isNotEmpty) {
return _labels.beginToken;
}
return keyword;
}
@override
Token get endToken {
if (_statements.isNotEmpty) {
return _statements.endToken;
}
return colon;
}
@override
NodeList<Label> get labels => _labels;
@override
NodeList<Statement> get statements => _statements;
}
/// A switch statement.
///
/// switchStatement ::=
/// 'switch' '(' [Expression] ')' '{' [SwitchCase]* [SwitchDefault]? '}'
class SwitchStatementImpl extends StatementImpl implements SwitchStatement {
/// The token representing the 'switch' keyword.
Token switchKeyword;
/// The left parenthesis.
Token leftParenthesis;
/// The expression used to determine which of the switch members will be
/// selected.
ExpressionImpl _expression;
/// The right parenthesis.
Token rightParenthesis;
/// The left curly bracket.
Token leftBracket;
/// The switch members that can be selected by the expression.
NodeList<SwitchMember> _members;
/// The right curly bracket.
Token rightBracket;
/// Initialize a newly created switch statement. The list of [members] can be
/// `null` if there are no switch members.
SwitchStatementImpl(
this.switchKeyword,
this.leftParenthesis,
ExpressionImpl expression,
this.rightParenthesis,
this.leftBracket,
List<SwitchMember> members,
this.rightBracket) {
_expression = _becomeParentOf(expression);
_members = new NodeListImpl<SwitchMember>(this, members);
}
@override
Token get beginToken => switchKeyword;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(switchKeyword)
..add(leftParenthesis)
..add(_expression)
..add(rightParenthesis)
..add(leftBracket)
..addAll(_members)
..add(rightBracket);
@override
Token get endToken => rightBracket;
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
NodeList<SwitchMember> get members => _members;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitSwitchStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
_members.accept(visitor);
}
}
/// A symbol literal expression.
///
/// symbolLiteral ::=
/// '#' (operator | (identifier ('.' identifier)*))
class SymbolLiteralImpl extends LiteralImpl implements SymbolLiteral {
/// The token introducing the literal.
Token poundSign;
/// The components of the literal.
final List<Token> components;
/// Initialize a newly created symbol literal.
SymbolLiteralImpl(this.poundSign, this.components);
@override
Token get beginToken => poundSign;
@override
// TODO(paulberry): add "." tokens.
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(poundSign)
..addAll(components);
@override
Token get endToken => components[components.length - 1];
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitSymbolLiteral(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// A this expression.
///
/// thisExpression ::=
/// 'this'
class ThisExpressionImpl extends ExpressionImpl implements ThisExpression {
/// The token representing the 'this' keyword.
Token thisKeyword;
/// Initialize a newly created this expression.
ThisExpressionImpl(this.thisKeyword);
@override
Token get beginToken => thisKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(thisKeyword);
@override
Token get endToken => thisKeyword;
@override
Precedence get precedence => Precedence.primary;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitThisExpression(this);
@override
void visitChildren(AstVisitor visitor) {
// There are no children to visit.
}
}
/// A throw expression.
///
/// throwExpression ::=
/// 'throw' [Expression]
class ThrowExpressionImpl extends ExpressionImpl implements ThrowExpression {
/// The token representing the 'throw' keyword.
Token throwKeyword;
/// The expression computing the exception to be thrown.
ExpressionImpl _expression;
/// Initialize a newly created throw expression.
ThrowExpressionImpl(this.throwKeyword, ExpressionImpl expression) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken => throwKeyword;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(throwKeyword)..add(_expression);
@override
Token get endToken {
if (_expression != null) {
return _expression.endToken;
}
return throwKeyword;
}
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
Precedence get precedence => Precedence.assignment;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitThrowExpression(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// The declaration of one or more top-level variables of the same type.
///
/// topLevelVariableDeclaration ::=
/// ('final' | 'const') type? staticFinalDeclarationList ';'
/// | variableDeclaration ';'
class TopLevelVariableDeclarationImpl extends CompilationUnitMemberImpl
implements TopLevelVariableDeclaration {
/// The top-level variables being declared.
VariableDeclarationListImpl _variableList;
/// The semicolon terminating the declaration.
Token semicolon;
/// Initialize a newly created top-level variable declaration. Either or both
/// of the [comment] and [metadata] can be `null` if the variable does not
/// have the corresponding attribute.
TopLevelVariableDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
VariableDeclarationListImpl variableList,
this.semicolon)
: super(comment, metadata) {
_variableList = _becomeParentOf(variableList);
}
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(_variableList)..add(semicolon);
@override
Element get declaredElement => null;
@deprecated
@override
Element get element => null;
@override
Token get endToken => semicolon;
@override
Token get firstTokenAfterCommentAndMetadata => _variableList.beginToken;
@override
VariableDeclarationList get variables => _variableList;
@override
void set variables(VariableDeclarationList variables) {
_variableList = _becomeParentOf(variables as VariableDeclarationListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitTopLevelVariableDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_variableList?.accept(visitor);
}
}
/// A try statement.
///
/// tryStatement ::=
/// 'try' [Block] ([CatchClause]+ finallyClause? | finallyClause)
///
/// finallyClause ::=
/// 'finally' [Block]
class TryStatementImpl extends StatementImpl implements TryStatement {
/// The token representing the 'try' keyword.
Token tryKeyword;
/// The body of the statement.
BlockImpl _body;
/// The catch clauses contained in the try statement.
NodeList<CatchClause> _catchClauses;
/// The token representing the 'finally' keyword, or `null` if the statement
/// does not contain a finally clause.
Token finallyKeyword;
/// The finally block contained in the try statement, or `null` if the
/// statement does not contain a finally clause.
BlockImpl _finallyBlock;
/// Initialize a newly created try statement. The list of [catchClauses] can
/// be`null` if there are no catch clauses. The [finallyKeyword] and
/// [finallyBlock] can be `null` if there is no finally clause.
TryStatementImpl(
this.tryKeyword,
BlockImpl body,
List<CatchClause> catchClauses,
this.finallyKeyword,
BlockImpl finallyBlock) {
_body = _becomeParentOf(body);
_catchClauses = new NodeListImpl<CatchClause>(this, catchClauses);
_finallyBlock = _becomeParentOf(finallyBlock);
}
@override
Token get beginToken => tryKeyword;
@override
Block get body => _body;
@override
void set body(Block block) {
_body = _becomeParentOf(block as BlockImpl);
}
@override
NodeList<CatchClause> get catchClauses => _catchClauses;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(tryKeyword)
..add(_body)
..addAll(_catchClauses)
..add(finallyKeyword)
..add(_finallyBlock);
@override
Token get endToken {
if (_finallyBlock != null) {
return _finallyBlock.endToken;
} else if (finallyKeyword != null) {
return finallyKeyword;
} else if (_catchClauses.isNotEmpty) {
return _catchClauses.endToken;
}
return _body.endToken;
}
@override
Block get finallyBlock => _finallyBlock;
@override
void set finallyBlock(Block block) {
_finallyBlock = _becomeParentOf(block as BlockImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitTryStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_body?.accept(visitor);
_catchClauses.accept(visitor);
_finallyBlock?.accept(visitor);
}
}
/// The declaration of a type alias.
///
/// typeAlias ::=
/// 'typedef' typeAliasBody
///
/// typeAliasBody ::=
/// classTypeAlias
/// | functionTypeAlias
abstract class TypeAliasImpl extends NamedCompilationUnitMemberImpl
implements TypeAlias {
/// The token representing the 'typedef' keyword.
Token typedefKeyword;
/// The semicolon terminating the declaration.
Token semicolon;
/// Initialize a newly created type alias. Either or both of the [comment] and
/// [metadata] can be `null` if the declaration does not have the
/// corresponding attribute.
TypeAliasImpl(CommentImpl comment, List<Annotation> metadata,
this.typedefKeyword, SimpleIdentifierImpl name, this.semicolon)
: super(comment, metadata, name);
@override
Token get endToken => semicolon;
@override
Token get firstTokenAfterCommentAndMetadata => typedefKeyword;
}
/// A type annotation.
///
/// type ::=
/// [NamedType]
/// | [GenericFunctionType]
abstract class TypeAnnotationImpl extends AstNodeImpl
implements TypeAnnotation {}
/// A list of type arguments.
///
/// typeArguments ::=
/// '<' typeName (',' typeName)* '>'
class TypeArgumentListImpl extends AstNodeImpl implements TypeArgumentList {
/// The left bracket.
Token leftBracket;
/// The type arguments associated with the type.
NodeList<TypeAnnotation> _arguments;
/// The right bracket.
Token rightBracket;
/// Initialize a newly created list of type arguments.
TypeArgumentListImpl(
this.leftBracket, List<TypeAnnotation> arguments, this.rightBracket) {
_arguments = new NodeListImpl<TypeAnnotation>(this, arguments);
}
@override
NodeList<TypeAnnotation> get arguments => _arguments;
@override
Token get beginToken => leftBracket;
@override
// TODO(paulberry): Add commas.
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(leftBracket)
..addAll(_arguments)
..add(rightBracket);
@override
Token get endToken => rightBracket;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitTypeArgumentList(this);
@override
void visitChildren(AstVisitor visitor) {
_arguments.accept(visitor);
}
}
/// A literal that has a type associated with it.
///
/// typedLiteral ::=
/// [ListLiteral]
/// | [MapLiteral]
abstract class TypedLiteralImpl extends LiteralImpl implements TypedLiteral {
/// The token representing the 'const' keyword, or `null` if the literal is
/// not a constant.
Token constKeyword;
/// The type argument associated with this literal, or `null` if no type
/// arguments were declared.
TypeArgumentListImpl _typeArguments;
/// Initialize a newly created typed literal. The [constKeyword] can be
/// `null` if the literal is not a constant. The [typeArguments] can be `null`
/// if no type arguments were declared.
TypedLiteralImpl(this.constKeyword, TypeArgumentListImpl typeArguments) {
_typeArguments = _becomeParentOf(typeArguments);
}
@override
bool get isConst {
return constKeyword != null || inConstantContext;
}
@override
TypeArgumentList get typeArguments => _typeArguments;
@override
void set typeArguments(TypeArgumentList typeArguments) {
_typeArguments = _becomeParentOf(typeArguments as TypeArgumentListImpl);
}
ChildEntities get _childEntities =>
new ChildEntities()..add(constKeyword)..add(_typeArguments);
@override
void visitChildren(AstVisitor visitor) {
_typeArguments?.accept(visitor);
}
}
/// The name of a type, which can optionally include type arguments.
///
/// typeName ::=
/// [Identifier] typeArguments? '?'?
class TypeNameImpl extends TypeAnnotationImpl implements TypeName {
/// The name of the type.
IdentifierImpl _name;
/// The type arguments associated with the type, or `null` if there are no
/// type arguments.
TypeArgumentListImpl _typeArguments;
@override
Token question;
/// The type being named, or `null` if the AST structure has not been
/// resolved.
DartType type;
/// Initialize a newly created type name. The [typeArguments] can be `null` if
/// there are no type arguments.
TypeNameImpl(IdentifierImpl name, TypeArgumentListImpl typeArguments,
{this.question}) {
_name = _becomeParentOf(name);
_typeArguments = _becomeParentOf(typeArguments);
}
@override
Token get beginToken => _name.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_name)..add(_typeArguments)..add(question);
@override
Token get endToken => question ?? _typeArguments?.endToken ?? _name.endToken;
@override
bool get isDeferred {
Identifier identifier = name;
if (identifier is! PrefixedIdentifier) {
return false;
}
return (identifier as PrefixedIdentifier).isDeferred;
}
@override
bool get isSynthetic => _name.isSynthetic && _typeArguments == null;
@override
Identifier get name => _name;
@override
void set name(Identifier identifier) {
_name = _becomeParentOf(identifier as IdentifierImpl);
}
@override
TypeArgumentList get typeArguments => _typeArguments;
@override
void set typeArguments(TypeArgumentList typeArguments) {
_typeArguments = _becomeParentOf(typeArguments as TypeArgumentListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitTypeName(this);
@override
void visitChildren(AstVisitor visitor) {
_name?.accept(visitor);
_typeArguments?.accept(visitor);
}
}
/// A type parameter.
///
/// typeParameter ::=
/// [SimpleIdentifier] ('extends' [TypeName])?
class TypeParameterImpl extends DeclarationImpl implements TypeParameter {
/// The name of the type parameter.
SimpleIdentifierImpl _name;
/// The token representing the 'extends' keyword, or `null` if there is no
/// explicit upper bound.
Token extendsKeyword;
/// The name of the upper bound for legal arguments, or `null` if there is no
/// explicit upper bound.
TypeAnnotationImpl _bound;
/// Initialize a newly created type parameter. Either or both of the [comment]
/// and [metadata] can be `null` if the parameter does not have the
/// corresponding attribute. The [extendsKeyword] and [bound] can be `null` if
/// the parameter does not have an upper bound.
TypeParameterImpl(CommentImpl comment, List<Annotation> metadata,
SimpleIdentifierImpl name, this.extendsKeyword, TypeAnnotationImpl bound)
: super(comment, metadata) {
_name = _becomeParentOf(name);
_bound = _becomeParentOf(bound);
}
@override
TypeAnnotation get bound => _bound;
@override
void set bound(TypeAnnotation type) {
_bound = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(_name)..add(extendsKeyword)..add(_bound);
@override
TypeParameterElement get declaredElement =>
_name?.staticElement as TypeParameterElement;
@deprecated
@override
TypeParameterElement get element => declaredElement;
@override
Token get endToken {
if (_bound == null) {
return _name.endToken;
}
return _bound.endToken;
}
@override
Token get firstTokenAfterCommentAndMetadata => _name.beginToken;
@override
SimpleIdentifier get name => _name;
@override
void set name(SimpleIdentifier identifier) {
_name = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitTypeParameter(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_name?.accept(visitor);
_bound?.accept(visitor);
}
}
/// Type parameters within a declaration.
///
/// typeParameterList ::=
/// '<' [TypeParameter] (',' [TypeParameter])* '>'
class TypeParameterListImpl extends AstNodeImpl implements TypeParameterList {
/// The left angle bracket.
final Token leftBracket;
/// The type parameters in the list.
NodeList<TypeParameter> _typeParameters;
/// The right angle bracket.
final Token rightBracket;
/// Initialize a newly created list of type parameters.
TypeParameterListImpl(
this.leftBracket, List<TypeParameter> typeParameters, this.rightBracket) {
_typeParameters = new NodeListImpl<TypeParameter>(this, typeParameters);
}
@override
Token get beginToken => leftBracket;
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(leftBracket)
..addAll(_typeParameters)
..add(rightBracket);
@override
Token get endToken => rightBracket;
@override
NodeList<TypeParameter> get typeParameters => _typeParameters;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitTypeParameterList(this);
@override
void visitChildren(AstVisitor visitor) {
_typeParameters.accept(visitor);
}
}
/// A directive that references a URI.
///
/// uriBasedDirective ::=
/// [ExportDirective]
/// | [ImportDirective]
/// | [PartDirective]
abstract class UriBasedDirectiveImpl extends DirectiveImpl
implements UriBasedDirective {
/// The prefix of a URI using the `dart-ext` scheme to reference a native code
/// library.
static String _DART_EXT_SCHEME = "dart-ext:";
/// The URI referenced by this directive.
StringLiteralImpl _uri;
@override
String uriContent;
@override
Source uriSource;
/// Initialize a newly create URI-based directive. Either or both of the
/// [comment] and [metadata] can be `null` if the directive does not have the
/// corresponding attribute.
UriBasedDirectiveImpl(
CommentImpl comment, List<Annotation> metadata, StringLiteralImpl uri)
: super(comment, metadata) {
_uri = _becomeParentOf(uri);
}
@deprecated
@override
Source get source => uriSource;
@deprecated
@override
void set source(Source source) {
uriSource = source;
}
@override
StringLiteral get uri => _uri;
@override
void set uri(StringLiteral uri) {
_uri = _becomeParentOf(uri as StringLiteralImpl);
}
UriValidationCode validate() {
return validateUri(this is ImportDirective, uri, uriContent);
}
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_uri?.accept(visitor);
}
/// Validate this directive, but do not check for existence. Return a code
/// indicating the problem if there is one, or `null` no problem.
static UriValidationCode validateUri(
bool isImport, StringLiteral uriLiteral, String uriContent) {
if (uriLiteral is StringInterpolation) {
return UriValidationCode.URI_WITH_INTERPOLATION;
}
if (uriContent == null) {
return UriValidationCode.INVALID_URI;
}
if (isImport && uriContent.startsWith(_DART_EXT_SCHEME)) {
return UriValidationCode.URI_WITH_DART_EXT_SCHEME;
}
Uri uri;
try {
uri = Uri.parse(Uri.encodeFull(uriContent));
} on FormatException {
return UriValidationCode.INVALID_URI;
}
if (uri.path.isEmpty) {
return UriValidationCode.INVALID_URI;
}
return null;
}
}
/// Validation codes returned by [UriBasedDirective.validate].
class UriValidationCode {
static const UriValidationCode INVALID_URI =
const UriValidationCode('INVALID_URI');
static const UriValidationCode URI_WITH_INTERPOLATION =
const UriValidationCode('URI_WITH_INTERPOLATION');
static const UriValidationCode URI_WITH_DART_EXT_SCHEME =
const UriValidationCode('URI_WITH_DART_EXT_SCHEME');
/// The name of the validation code.
final String name;
/// Initialize a newly created validation code to have the given [name].
const UriValidationCode(this.name);
@override
String toString() => name;
}
/// An identifier that has an initial value associated with it. Instances of
/// this class are always children of the class [VariableDeclarationList].
///
/// variableDeclaration ::=
/// [SimpleIdentifier] ('=' [Expression])?
///
/// TODO(paulberry): the grammar does not allow metadata to be associated with
/// a VariableDeclaration, and currently we don't record comments for it either.
/// Consider changing the class hierarchy so that [VariableDeclaration] does not
/// extend [Declaration].
class VariableDeclarationImpl extends DeclarationImpl
implements VariableDeclaration {
/// The name of the variable being declared.
SimpleIdentifierImpl _name;
/// The equal sign separating the variable name from the initial value, or
/// `null` if the initial value was not specified.
Token equals;
/// The expression used to compute the initial value for the variable, or
/// `null` if the initial value was not specified.
ExpressionImpl _initializer;
/// Initialize a newly created variable declaration. The [equals] and
/// [initializer] can be `null` if there is no initializer.
VariableDeclarationImpl(
SimpleIdentifierImpl name, this.equals, ExpressionImpl initializer)
: super(null, null) {
_name = _becomeParentOf(name);
_initializer = _becomeParentOf(initializer);
}
@override
Iterable<SyntacticEntity> get childEntities =>
super._childEntities..add(_name)..add(equals)..add(_initializer);
@override
VariableElement get declaredElement =>
_name?.staticElement as VariableElement;
/// This overridden implementation of [documentationComment] looks in the
/// grandparent node for Dartdoc comments if no documentation is specifically
/// available on the node.
@override
Comment get documentationComment {
Comment comment = super.documentationComment;
if (comment == null) {
AstNode node = parent?.parent;
if (node is AnnotatedNode) {
return node.documentationComment;
}
}
return comment;
}
@deprecated
@override
VariableElement get element => declaredElement;
@override
Token get endToken {
if (_initializer != null) {
return _initializer.endToken;
}
return _name.endToken;
}
@override
Token get firstTokenAfterCommentAndMetadata => _name.beginToken;
@override
Expression get initializer => _initializer;
@override
void set initializer(Expression expression) {
_initializer = _becomeParentOf(expression as ExpressionImpl);
}
@override
bool get isConst {
AstNode parent = this.parent;
return parent is VariableDeclarationList && parent.isConst;
}
@override
bool get isFinal {
AstNode parent = this.parent;
return parent is VariableDeclarationList && parent.isFinal;
}
@override
bool get isLate {
AstNode parent = this.parent;
return parent is VariableDeclarationList && parent.isLate;
}
@override
SimpleIdentifier get name => _name;
@override
void set name(SimpleIdentifier identifier) {
_name = _becomeParentOf(identifier as SimpleIdentifierImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitVariableDeclaration(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_name?.accept(visitor);
_initializer?.accept(visitor);
}
}
/// The declaration of one or more variables of the same type.
///
/// variableDeclarationList ::=
/// finalConstVarOrType [VariableDeclaration]
/// (',' [VariableDeclaration])*
///
/// finalConstVarOrType ::=
/// 'final' 'late'? [TypeAnnotation]?
/// | 'const' [TypeAnnotation]?
/// | 'var'
/// | 'late'? [TypeAnnotation]
class VariableDeclarationListImpl extends AnnotatedNodeImpl
implements VariableDeclarationList {
/// The token representing the 'final', 'const' or 'var' keyword, or `null` if
/// no keyword was included.
Token keyword;
/// The token representing the 'late' keyword, or `null` if the late modifier
/// was not included.
Token lateKeyword;
/// The type of the variables being declared, or `null` if no type was
/// provided.
TypeAnnotationImpl _type;
/// A list containing the individual variables being declared.
NodeList<VariableDeclaration> _variables;
/// Initialize a newly created variable declaration list. Either or both of
/// the [comment] and [metadata] can be `null` if the variable list does not
/// have the corresponding attribute. The [keyword] can be `null` if a type
/// was specified. The [type] must be `null` if the keyword is 'var'.
VariableDeclarationListImpl(
CommentImpl comment,
List<Annotation> metadata,
this.lateKeyword,
this.keyword,
TypeAnnotationImpl type,
List<VariableDeclaration> variables)
: super(comment, metadata) {
_type = _becomeParentOf(type);
_variables = new NodeListImpl<VariableDeclaration>(this, variables);
}
@override
// TODO(paulberry): include commas.
Iterable<SyntacticEntity> get childEntities => super._childEntities
..add(keyword)
..add(_type)
..addAll(_variables);
@override
Token get endToken => _variables.endToken;
@override
Token get firstTokenAfterCommentAndMetadata {
if (keyword != null) {
return keyword;
} else if (_type != null) {
return _type.beginToken;
}
return _variables.beginToken;
}
@override
bool get isConst => keyword?.keyword == Keyword.CONST;
@override
bool get isFinal => keyword?.keyword == Keyword.FINAL;
@override
bool get isLate => lateKeyword != null;
@override
TypeAnnotation get type => _type;
@override
void set type(TypeAnnotation type) {
_type = _becomeParentOf(type as TypeAnnotationImpl);
}
@override
NodeList<VariableDeclaration> get variables => _variables;
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitVariableDeclarationList(this);
@override
void visitChildren(AstVisitor visitor) {
super.visitChildren(visitor);
_type?.accept(visitor);
_variables.accept(visitor);
}
}
/// A list of variables that are being declared in a context where a statement
/// is required.
///
/// variableDeclarationStatement ::=
/// [VariableDeclarationList] ';'
class VariableDeclarationStatementImpl extends StatementImpl
implements VariableDeclarationStatement {
/// The variables being declared.
VariableDeclarationListImpl _variableList;
/// The semicolon terminating the statement.
Token semicolon;
/// Initialize a newly created variable declaration statement.
VariableDeclarationStatementImpl(
VariableDeclarationListImpl variableList, this.semicolon) {
_variableList = _becomeParentOf(variableList);
}
@override
Token get beginToken => _variableList.beginToken;
@override
Iterable<SyntacticEntity> get childEntities =>
new ChildEntities()..add(_variableList)..add(semicolon);
@override
Token get endToken => semicolon;
@override
VariableDeclarationList get variables => _variableList;
@override
void set variables(VariableDeclarationList variables) {
_variableList = _becomeParentOf(variables as VariableDeclarationListImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) =>
visitor.visitVariableDeclarationStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_variableList?.accept(visitor);
}
}
/// A while statement.
///
/// whileStatement ::=
/// 'while' '(' [Expression] ')' [Statement]
class WhileStatementImpl extends StatementImpl implements WhileStatement {
/// The token representing the 'while' keyword.
Token whileKeyword;
/// The left parenthesis.
Token leftParenthesis;
/// The expression used to determine whether to execute the body of the loop.
ExpressionImpl _condition;
/// The right parenthesis.
Token rightParenthesis;
/// The body of the loop.
StatementImpl _body;
/// Initialize a newly created while statement.
WhileStatementImpl(this.whileKeyword, this.leftParenthesis,
ExpressionImpl condition, this.rightParenthesis, StatementImpl body) {
_condition = _becomeParentOf(condition);
_body = _becomeParentOf(body);
}
@override
Token get beginToken => whileKeyword;
@override
Statement get body => _body;
@override
void set body(Statement statement) {
_body = _becomeParentOf(statement as StatementImpl);
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(whileKeyword)
..add(leftParenthesis)
..add(_condition)
..add(rightParenthesis)
..add(_body);
@override
Expression get condition => _condition;
@override
void set condition(Expression expression) {
_condition = _becomeParentOf(expression as ExpressionImpl);
}
@override
Token get endToken => _body.endToken;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitWhileStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_condition?.accept(visitor);
_body?.accept(visitor);
}
}
/// The with clause in a class declaration.
///
/// withClause ::=
/// 'with' [TypeName] (',' [TypeName])*
class WithClauseImpl extends AstNodeImpl implements WithClause {
/// The token representing the 'with' keyword.
Token withKeyword;
/// The names of the mixins that were specified.
NodeList<TypeName> _mixinTypes;
/// Initialize a newly created with clause.
WithClauseImpl(this.withKeyword, List<TypeName> mixinTypes) {
_mixinTypes = new NodeListImpl<TypeName>(this, mixinTypes);
}
@override
Token get beginToken => withKeyword;
@override
// TODO(paulberry): add commas.
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(withKeyword)
..addAll(_mixinTypes);
@override
Token get endToken => _mixinTypes.endToken;
@override
NodeList<TypeName> get mixinTypes => _mixinTypes;
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitWithClause(this);
@override
void visitChildren(AstVisitor visitor) {
_mixinTypes.accept(visitor);
}
}
/// A yield statement.
///
/// yieldStatement ::=
/// 'yield' '*'? [Expression] ‘;’
class YieldStatementImpl extends StatementImpl implements YieldStatement {
/// The 'yield' keyword.
Token yieldKeyword;
/// The star optionally following the 'yield' keyword.
Token star;
/// The expression whose value will be yielded.
ExpressionImpl _expression;
/// The semicolon following the expression.
Token semicolon;
/// Initialize a newly created yield expression. The [star] can be `null` if
/// no star was provided.
YieldStatementImpl(
this.yieldKeyword, this.star, ExpressionImpl expression, this.semicolon) {
_expression = _becomeParentOf(expression);
}
@override
Token get beginToken {
if (yieldKeyword != null) {
return yieldKeyword;
}
return _expression.beginToken;
}
@override
Iterable<SyntacticEntity> get childEntities => new ChildEntities()
..add(yieldKeyword)
..add(star)
..add(_expression)
..add(semicolon);
@override
Token get endToken {
if (semicolon != null) {
return semicolon;
}
return _expression.endToken;
}
@override
Expression get expression => _expression;
@override
void set expression(Expression expression) {
_expression = _becomeParentOf(expression as ExpressionImpl);
}
@override
E accept<E>(AstVisitor<E> visitor) => visitor.visitYieldStatement(this);
@override
void visitChildren(AstVisitor visitor) {
_expression?.accept(visitor);
}
}
/// An indication of the resolved kind of a [SetOrMapLiteral].
enum _SetOrMapKind {
/// Indicates that the literal represents a map.
map,
/// Indicates that the literal represents a set.
set,
/// Indicates that either
/// - the literal is syntactically ambiguous and resolution has not yet been
/// performed, or
/// - the literal is invalid because resolution was not able to resolve the
/// ambiguity.
unresolved
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/ast/resolution_map.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/resolution_map.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
/**
* Concrete implementation of [ResolutionMap] based on the standard AST
* implementation.
*/
class ResolutionMapImpl implements ResolutionMap {
@deprecated
@override
ExecutableElement bestElementForFunctionExpressionInvocation(
FunctionExpressionInvocation node) =>
node.staticElement;
@deprecated
@override
Element bestElementForIdentifier(Identifier node) => node.staticElement;
@deprecated
@override
MethodElement bestElementForMethodReference(MethodReferenceExpression node) =>
node.staticElement;
@deprecated
@override
ParameterElement bestParameterElementForExpression(Expression node) =>
node.staticParameterElement;
@deprecated
@override
DartType bestTypeForExpression(Expression node) => node.staticType;
@override
ElementAnnotation elementAnnotationForAnnotation(Annotation node) =>
node.elementAnnotation;
@override
ClassElement elementDeclaredByClassDeclaration(ClassDeclaration node) =>
node.declaredElement;
@override
CompilationUnitElement elementDeclaredByCompilationUnit(
CompilationUnit node) =>
node.declaredElement;
@override
ConstructorElement elementDeclaredByConstructorDeclaration(
ConstructorDeclaration node) =>
node.declaredElement;
@override
Element elementDeclaredByDeclaration(Declaration node) =>
node.declaredElement;
@override
LocalVariableElement elementDeclaredByDeclaredIdentifier(
DeclaredIdentifier node) =>
node.declaredElement;
@override
Element elementDeclaredByDirective(Directive node) => node.element;
@override
ClassElement elementDeclaredByEnumDeclaration(EnumDeclaration node) =>
node.declaredElement;
@override
ParameterElement elementDeclaredByFormalParameter(FormalParameter node) =>
node.declaredElement;
@override
ExecutableElement elementDeclaredByFunctionDeclaration(
FunctionDeclaration node) =>
node.declaredElement;
@override
ExecutableElement elementDeclaredByFunctionExpression(
FunctionExpression node) =>
node.declaredElement;
@override
ExecutableElement elementDeclaredByMethodDeclaration(
MethodDeclaration node) =>
node.declaredElement;
@override
ClassElement elementDeclaredByMixinDeclaration(MixinDeclaration node) =>
node.declaredElement;
@override
VariableElement elementDeclaredByVariableDeclaration(
VariableDeclaration node) =>
node.declaredElement;
@override
Element elementForAnnotation(Annotation node) => node.element;
@override
ParameterElement elementForNamedExpression(NamedExpression node) =>
node.element;
@override
List<ParameterElement> parameterElementsForFormalParameterList(
FormalParameterList node) =>
node.parameterElements;
@deprecated
@override
ExecutableElement propagatedElementForFunctionExpressionInvocation(
FunctionExpressionInvocation node) =>
null;
@deprecated
@override
Element propagatedElementForIdentifier(Identifier node) => null;
@deprecated
@override
MethodElement propagatedElementForMethodReference(
MethodReferenceExpression node) =>
null;
@deprecated
@override
ParameterElement propagatedParameterElementForExpression(Expression node) =>
null;
@deprecated
@override
DartType propagatedTypeForExpression(Expression node) => null;
@override
ConstructorElement staticElementForConstructorReference(
ConstructorReferenceNode node) =>
node.staticElement;
@override
ExecutableElement staticElementForFunctionExpressionInvocation(
FunctionExpressionInvocation node) =>
node.staticElement;
@override
Element staticElementForIdentifier(Identifier node) => node.staticElement;
@override
MethodElement staticElementForMethodReference(
MethodReferenceExpression node) =>
node.staticElement;
@override
DartType staticInvokeTypeForInvocationExpression(InvocationExpression node) =>
node.staticInvokeType;
@override
ParameterElement staticParameterElementForExpression(Expression node) =>
node.staticParameterElement;
@override
DartType staticTypeForExpression(Expression node) => node.staticType;
@override
DartType typeForTypeName(TypeAnnotation node) => node.type;
@override
Element uriElementForDirective(UriBasedDirective node) => node.uriElement;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/ast/element_locator.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:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
/// An object used to locate the [Element] associated with a given [AstNode].
class ElementLocator {
/// Return the element associated with the given [node], or `null` if there
/// is no element associated with the node.
static Element locate(AstNode node) {
if (node == null) return null;
var mapper = new _ElementMapper();
return node.accept(mapper);
}
}
/// Visitor that maps nodes to elements.
class _ElementMapper extends GeneralizingAstVisitor<Element> {
@override
Element visitAnnotation(Annotation node) {
return node.element;
}
@override
Element visitAssignmentExpression(AssignmentExpression node) {
return node.staticElement;
}
@override
Element visitBinaryExpression(BinaryExpression node) {
return node.staticElement;
}
@override
Element visitClassDeclaration(ClassDeclaration node) {
return node.declaredElement;
}
@override
Element visitCompilationUnit(CompilationUnit node) {
return node.declaredElement;
}
@override
Element visitConstructorDeclaration(ConstructorDeclaration node) {
return node.declaredElement;
}
@override
Element visitExportDirective(ExportDirective node) {
return node.element;
}
@override
Element visitFunctionDeclaration(FunctionDeclaration node) {
return node.declaredElement;
}
@override
Element visitIdentifier(Identifier node) {
var parent = node.parent;
if (parent is Annotation) {
// Type name in Annotation
if (identical(parent.name, node) && parent.constructorName == null) {
return parent.element;
}
} else if (parent is ConstructorDeclaration) {
// Extra work to map Constructor Declarations to their associated
// Constructor Elements
var returnType = parent.returnType;
if (identical(returnType, node)) {
var name = parent.name;
if (name != null) {
return name.staticElement;
}
var element = node.staticElement;
if (element is ClassElement) {
return element.unnamedConstructor;
}
}
} else if (parent is LibraryIdentifier) {
var grandParent = parent.parent;
if (grandParent is PartOfDirective) {
var element = grandParent.element;
if (element is LibraryElement) {
return element.definingCompilationUnit;
}
} else if (grandParent is LibraryDirective) {
return grandParent.element;
}
}
return node.staticElement;
}
@override
Element visitImportDirective(ImportDirective node) {
return node.element;
}
@override
Element visitIndexExpression(IndexExpression node) {
return node.staticElement;
}
@override
Element visitInstanceCreationExpression(InstanceCreationExpression node) {
return node.staticElement;
}
@override
Element visitLibraryDirective(LibraryDirective node) {
return node.element;
}
@override
Element visitMethodDeclaration(MethodDeclaration node) {
return node.declaredElement;
}
@override
Element visitMethodInvocation(MethodInvocation node) {
return node.methodName.staticElement;
}
@override
Element visitPartOfDirective(PartOfDirective node) {
return node.element;
}
@override
Element visitPostfixExpression(PostfixExpression node) {
return node.staticElement;
}
@override
Element visitPrefixedIdentifier(PrefixedIdentifier node) {
return node.staticElement;
}
@override
Element visitPrefixExpression(PrefixExpression node) {
return node.staticElement;
}
@override
Element visitStringLiteral(StringLiteral node) {
var parent = node.parent;
if (parent is UriBasedDirective) {
return parent.uriElement;
}
return null;
}
@override
Element visitVariableDeclaration(VariableDeclaration node) {
return node.declaredElement;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/ast/utilities.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/standard_ast_factory.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisEngine;
import 'package:analyzer/src/generated/java_core.dart';
import 'package:meta/meta.dart';
export 'package:analyzer/src/dart/ast/constant_evaluator.dart';
/**
* A function used to handle exceptions that are thrown by delegates while using
* an [ExceptionHandlingDelegatingAstVisitor].
*/
typedef void ExceptionInDelegateHandler(
AstNode node, AstVisitor visitor, dynamic exception, StackTrace stackTrace);
/**
* An AST visitor that will clone any AST structure that it visits. The cloner
* will only clone the structure, it will not preserve any resolution results or
* properties associated with the nodes.
*/
class AstCloner implements AstVisitor<AstNode> {
/**
* A flag indicating whether tokens should be cloned while cloning an AST
* structure.
*/
final bool cloneTokens;
/**
* Mapping from original tokes to cloned.
*/
final Map<Token, Token> _clonedTokens = new Map<Token, Token>.identity();
/**
* The next original token to clone.
*/
Token _nextToClone;
/**
* The last cloned token.
*/
Token _lastCloned;
/**
* The offset of the last cloned token.
*/
int _lastClonedOffset = -1;
/**
* Initialize a newly created AST cloner to optionally clone tokens while
* cloning AST nodes if [cloneTokens] is `true`.
*
* TODO(brianwilkerson) Change this to be a named parameter.
*/
AstCloner([this.cloneTokens = false]);
/**
* Return a clone of the given [node].
*/
E cloneNode<E extends AstNode>(E node) {
if (node == null) {
return null;
}
return node.accept(this) as E;
}
/**
* Return a list containing cloned versions of the nodes in the given list of
* [nodes].
*/
List<E> cloneNodeList<E extends AstNode>(List<E> nodes) {
int count = nodes.length;
List<E> clonedNodes = new List<E>();
for (int i = 0; i < count; i++) {
clonedNodes.add((nodes[i]).accept(this) as E);
}
return clonedNodes;
}
/**
* Clone the given [token] if tokens are supposed to be cloned.
*/
Token cloneToken(Token token) {
if (cloneTokens) {
if (token == null) {
return null;
}
if (_lastClonedOffset <= token.offset) {
_cloneTokens(_nextToClone ?? token, token.offset);
}
Token clone = _clonedTokens[token];
assert(clone != null);
return clone;
} else {
return token;
}
}
/**
* Clone the given [tokens] if tokens are supposed to be cloned.
*/
List<Token> cloneTokenList(List<Token> tokens) {
if (cloneTokens) {
return tokens.map(cloneToken).toList();
}
return tokens;
}
@override
AdjacentStrings visitAdjacentStrings(AdjacentStrings node) =>
astFactory.adjacentStrings(cloneNodeList(node.strings));
@override
Annotation visitAnnotation(Annotation node) => astFactory.annotation(
cloneToken(node.atSign),
cloneNode(node.name),
cloneToken(node.period),
cloneNode(node.constructorName),
cloneNode(node.arguments));
@override
ArgumentList visitArgumentList(ArgumentList node) => astFactory.argumentList(
cloneToken(node.leftParenthesis),
cloneNodeList(node.arguments),
cloneToken(node.rightParenthesis));
@override
AsExpression visitAsExpression(AsExpression node) => astFactory.asExpression(
cloneNode(node.expression),
cloneToken(node.asOperator),
cloneNode(node.type));
@override
AstNode visitAssertInitializer(AssertInitializer node) =>
astFactory.assertInitializer(
cloneToken(node.assertKeyword),
cloneToken(node.leftParenthesis),
cloneNode(node.condition),
cloneToken(node.comma),
cloneNode(node.message),
cloneToken(node.rightParenthesis));
@override
AstNode visitAssertStatement(AssertStatement node) =>
astFactory.assertStatement(
cloneToken(node.assertKeyword),
cloneToken(node.leftParenthesis),
cloneNode(node.condition),
cloneToken(node.comma),
cloneNode(node.message),
cloneToken(node.rightParenthesis),
cloneToken(node.semicolon));
@override
AssignmentExpression visitAssignmentExpression(AssignmentExpression node) =>
astFactory.assignmentExpression(cloneNode(node.leftHandSide),
cloneToken(node.operator), cloneNode(node.rightHandSide));
@override
AwaitExpression visitAwaitExpression(AwaitExpression node) =>
astFactory.awaitExpression(
cloneToken(node.awaitKeyword), cloneNode(node.expression));
@override
BinaryExpression visitBinaryExpression(BinaryExpression node) =>
astFactory.binaryExpression(cloneNode(node.leftOperand),
cloneToken(node.operator), cloneNode(node.rightOperand));
@override
Block visitBlock(Block node) => astFactory.block(cloneToken(node.leftBracket),
cloneNodeList(node.statements), cloneToken(node.rightBracket));
@override
BlockFunctionBody visitBlockFunctionBody(BlockFunctionBody node) =>
astFactory.blockFunctionBody(cloneToken(node.keyword),
cloneToken(node.star), cloneNode(node.block));
@override
BooleanLiteral visitBooleanLiteral(BooleanLiteral node) =>
astFactory.booleanLiteral(cloneToken(node.literal), node.value);
@override
BreakStatement visitBreakStatement(BreakStatement node) =>
astFactory.breakStatement(cloneToken(node.breakKeyword),
cloneNode(node.label), cloneToken(node.semicolon));
@override
CascadeExpression visitCascadeExpression(CascadeExpression node) =>
astFactory.cascadeExpression(
cloneNode(node.target), cloneNodeList(node.cascadeSections));
@override
CatchClause visitCatchClause(CatchClause node) => astFactory.catchClause(
cloneToken(node.onKeyword),
cloneNode(node.exceptionType),
cloneToken(node.catchKeyword),
cloneToken(node.leftParenthesis),
cloneNode(node.exceptionParameter),
cloneToken(node.comma),
cloneNode(node.stackTraceParameter),
cloneToken(node.rightParenthesis),
cloneNode(node.body));
@override
ClassDeclaration visitClassDeclaration(ClassDeclaration node) {
ClassDeclaration copy = astFactory.classDeclaration(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.abstractKeyword),
cloneToken(node.classKeyword),
cloneNode(node.name),
cloneNode(node.typeParameters),
cloneNode(node.extendsClause),
cloneNode(node.withClause),
cloneNode(node.implementsClause),
cloneToken(node.leftBracket),
cloneNodeList(node.members),
cloneToken(node.rightBracket));
copy.nativeClause = cloneNode(node.nativeClause);
return copy;
}
@override
ClassTypeAlias visitClassTypeAlias(ClassTypeAlias node) {
cloneToken(node.abstractKeyword);
return astFactory.classTypeAlias(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.typedefKeyword),
cloneNode(node.name),
cloneNode(node.typeParameters),
cloneToken(node.equals),
cloneToken(node.abstractKeyword),
cloneNode(node.superclass),
cloneNode(node.withClause),
cloneNode(node.implementsClause),
cloneToken(node.semicolon));
}
@override
Comment visitComment(Comment node) {
if (node.isDocumentation) {
return astFactory.documentationComment(
cloneTokenList(node.tokens), cloneNodeList(node.references));
} else if (node.isBlock) {
return astFactory.blockComment(cloneTokenList(node.tokens));
}
return astFactory.endOfLineComment(cloneTokenList(node.tokens));
}
@override
CommentReference visitCommentReference(CommentReference node) {
// Comment references have a token stream
// separate from the compilation unit's token stream.
// Clone the tokens in that stream here and add them to _clondedTokens
// for use when cloning the comment reference.
Token token = node.beginToken;
Token lastCloned = new Token.eof(-1);
while (token != null) {
Token clone = token.copy();
_clonedTokens[token] = clone;
lastCloned.setNext(clone);
lastCloned = clone;
if (token.isEof) {
break;
}
token = token.next;
}
return astFactory.commentReference(
cloneToken(node.newKeyword), cloneNode(node.identifier));
}
@override
CompilationUnit visitCompilationUnit(CompilationUnit node) {
CompilationUnit clone = astFactory.compilationUnit(
beginToken: cloneToken(node.beginToken),
scriptTag: cloneNode(node.scriptTag),
directives: cloneNodeList(node.directives),
declarations: cloneNodeList(node.declarations),
endToken: cloneToken(node.endToken),
featureSet: node.featureSet);
clone.lineInfo = node.lineInfo;
return clone;
}
@override
ConditionalExpression visitConditionalExpression(
ConditionalExpression node) =>
astFactory.conditionalExpression(
cloneNode(node.condition),
cloneToken(node.question),
cloneNode(node.thenExpression),
cloneToken(node.colon),
cloneNode(node.elseExpression));
@override
Configuration visitConfiguration(Configuration node) =>
astFactory.configuration(
cloneToken(node.ifKeyword),
cloneToken(node.leftParenthesis),
cloneNode(node.name),
cloneToken(node.equalToken),
cloneNode(node.value),
cloneToken(node.rightParenthesis),
cloneNode(node.uri));
@override
ConstructorDeclaration visitConstructorDeclaration(
ConstructorDeclaration node) =>
astFactory.constructorDeclaration(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.externalKeyword),
cloneToken(node.constKeyword),
cloneToken(node.factoryKeyword),
cloneNode(node.returnType),
cloneToken(node.period),
cloneNode(node.name),
cloneNode(node.parameters),
cloneToken(node.separator),
cloneNodeList(node.initializers),
cloneNode(node.redirectedConstructor),
cloneNode(node.body));
@override
ConstructorFieldInitializer visitConstructorFieldInitializer(
ConstructorFieldInitializer node) =>
astFactory.constructorFieldInitializer(
cloneToken(node.thisKeyword),
cloneToken(node.period),
cloneNode(node.fieldName),
cloneToken(node.equals),
cloneNode(node.expression));
@override
ConstructorName visitConstructorName(ConstructorName node) =>
astFactory.constructorName(
cloneNode(node.type), cloneToken(node.period), cloneNode(node.name));
@override
ContinueStatement visitContinueStatement(ContinueStatement node) =>
astFactory.continueStatement(cloneToken(node.continueKeyword),
cloneNode(node.label), cloneToken(node.semicolon));
@override
DeclaredIdentifier visitDeclaredIdentifier(DeclaredIdentifier node) =>
astFactory.declaredIdentifier(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.keyword),
cloneNode(node.type),
cloneNode(node.identifier));
@override
DefaultFormalParameter visitDefaultFormalParameter(
DefaultFormalParameter node) =>
// ignore: deprecated_member_use_from_same_package
astFactory.defaultFormalParameter(cloneNode(node.parameter), node.kind,
cloneToken(node.separator), cloneNode(node.defaultValue));
@override
DoStatement visitDoStatement(DoStatement node) => astFactory.doStatement(
cloneToken(node.doKeyword),
cloneNode(node.body),
cloneToken(node.whileKeyword),
cloneToken(node.leftParenthesis),
cloneNode(node.condition),
cloneToken(node.rightParenthesis),
cloneToken(node.semicolon));
@override
DottedName visitDottedName(DottedName node) =>
astFactory.dottedName(cloneNodeList(node.components));
@override
DoubleLiteral visitDoubleLiteral(DoubleLiteral node) =>
astFactory.doubleLiteral(cloneToken(node.literal), node.value);
@override
EmptyFunctionBody visitEmptyFunctionBody(EmptyFunctionBody node) =>
astFactory.emptyFunctionBody(cloneToken(node.semicolon));
@override
EmptyStatement visitEmptyStatement(EmptyStatement node) =>
astFactory.emptyStatement(cloneToken(node.semicolon));
@override
AstNode visitEnumConstantDeclaration(EnumConstantDeclaration node) =>
astFactory.enumConstantDeclaration(cloneNode(node.documentationComment),
cloneNodeList(node.metadata), cloneNode(node.name));
@override
EnumDeclaration visitEnumDeclaration(EnumDeclaration node) =>
astFactory.enumDeclaration(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.enumKeyword),
cloneNode(node.name),
cloneToken(node.leftBracket),
cloneNodeList(node.constants),
cloneToken(node.rightBracket));
@override
ExportDirective visitExportDirective(ExportDirective node) {
ExportDirectiveImpl directive = astFactory.exportDirective(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.keyword),
cloneNode(node.uri),
cloneNodeList(node.configurations),
cloneNodeList(node.combinators),
cloneToken(node.semicolon));
directive.selectedUriContent = node.selectedUriContent;
directive.selectedSource = node.selectedSource;
directive.uriSource = node.uriSource;
directive.uriContent = node.uriContent;
return directive;
}
@override
ExpressionFunctionBody visitExpressionFunctionBody(
ExpressionFunctionBody node) =>
astFactory.expressionFunctionBody(
cloneToken(node.keyword),
cloneToken(node.functionDefinition),
cloneNode(node.expression),
cloneToken(node.semicolon));
@override
ExpressionStatement visitExpressionStatement(ExpressionStatement node) =>
astFactory.expressionStatement(
cloneNode(node.expression), cloneToken(node.semicolon));
@override
ExtendsClause visitExtendsClause(ExtendsClause node) =>
astFactory.extendsClause(
cloneToken(node.extendsKeyword), cloneNode(node.superclass));
@override
ExtensionDeclaration visitExtensionDeclaration(ExtensionDeclaration node) =>
astFactory.extensionDeclaration(
comment: cloneNode(node.documentationComment),
metadata: cloneNodeList(node.metadata),
extensionKeyword: cloneToken(node.extensionKeyword),
name: cloneNode(node.name),
typeParameters: cloneNode(node.typeParameters),
onKeyword: cloneToken(node.onKeyword),
extendedType: cloneNode(node.extendedType),
leftBracket: cloneToken(node.leftBracket),
members: cloneNodeList(node.members),
rightBracket: cloneToken(node.rightBracket));
@override
ExtensionOverride visitExtensionOverride(ExtensionOverride node) =>
astFactory.extensionOverride(
extensionName: cloneNode(node.extensionName),
typeArguments: cloneNode(node.typeArguments),
argumentList: cloneNode(node.argumentList));
@override
FieldDeclaration visitFieldDeclaration(FieldDeclaration node) =>
astFactory.fieldDeclaration2(
comment: cloneNode(node.documentationComment),
metadata: cloneNodeList(node.metadata),
covariantKeyword: cloneToken(node.covariantKeyword),
staticKeyword: cloneToken(node.staticKeyword),
fieldList: cloneNode(node.fields),
semicolon: cloneToken(node.semicolon));
@override
FieldFormalParameter visitFieldFormalParameter(FieldFormalParameter node) =>
astFactory.fieldFormalParameter2(
comment: cloneNode(node.documentationComment),
metadata: cloneNodeList(node.metadata),
covariantKeyword: cloneToken(node.covariantKeyword),
keyword: cloneToken(node.keyword),
type: cloneNode(node.type),
thisKeyword: cloneToken(node.thisKeyword),
period: cloneToken(node.period),
identifier: cloneNode(node.identifier),
typeParameters: cloneNode(node.typeParameters),
parameters: cloneNode(node.parameters));
@override
ForEachPartsWithDeclaration visitForEachPartsWithDeclaration(
ForEachPartsWithDeclaration node) =>
astFactory.forEachPartsWithDeclaration(
loopVariable: cloneNode(node.loopVariable),
inKeyword: cloneToken(node.inKeyword),
iterable: cloneNode(node.iterable));
@override
ForEachPartsWithIdentifier visitForEachPartsWithIdentifier(
ForEachPartsWithIdentifier node) =>
astFactory.forEachPartsWithIdentifier(
identifier: cloneNode(node.identifier),
inKeyword: cloneToken(node.inKeyword),
iterable: cloneNode(node.iterable));
@override
ForElement visitForElement(ForElement node) => astFactory.forElement(
awaitKeyword: cloneToken(node.awaitKeyword),
forKeyword: cloneToken(node.forKeyword),
leftParenthesis: cloneToken(node.leftParenthesis),
forLoopParts: cloneNode(node.forLoopParts),
rightParenthesis: cloneToken(node.rightParenthesis),
body: cloneNode(node.body));
@override
FormalParameterList visitFormalParameterList(FormalParameterList node) =>
astFactory.formalParameterList(
cloneToken(node.leftParenthesis),
cloneNodeList(node.parameters),
cloneToken(node.leftDelimiter),
cloneToken(node.rightDelimiter),
cloneToken(node.rightParenthesis));
@override
ForPartsWithDeclarations visitForPartsWithDeclarations(
ForPartsWithDeclarations node) =>
astFactory.forPartsWithDeclarations(
variables: cloneNode(node.variables),
leftSeparator: cloneToken(node.leftSeparator),
condition: cloneNode(node.condition),
rightSeparator: cloneToken(node.rightSeparator),
updaters: cloneNodeList(node.updaters));
@override
ForPartsWithExpression visitForPartsWithExpression(
ForPartsWithExpression node) =>
astFactory.forPartsWithExpression(
initialization: cloneNode(node.initialization),
leftSeparator: cloneToken(node.leftSeparator),
condition: cloneNode(node.condition),
rightSeparator: cloneToken(node.rightSeparator),
updaters: cloneNodeList(node.updaters));
@override
ForStatement visitForStatement(ForStatement node) => astFactory.forStatement(
awaitKeyword: cloneToken(node.awaitKeyword),
forKeyword: cloneToken(node.forKeyword),
leftParenthesis: cloneToken(node.leftParenthesis),
forLoopParts: cloneNode(node.forLoopParts),
rightParenthesis: cloneToken(node.rightParenthesis),
body: cloneNode(node.body));
@override
FunctionDeclaration visitFunctionDeclaration(FunctionDeclaration node) =>
astFactory.functionDeclaration(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.externalKeyword),
cloneNode(node.returnType),
cloneToken(node.propertyKeyword),
cloneNode(node.name),
cloneNode(node.functionExpression));
@override
FunctionDeclarationStatement visitFunctionDeclarationStatement(
FunctionDeclarationStatement node) =>
astFactory
.functionDeclarationStatement(cloneNode(node.functionDeclaration));
@override
FunctionExpression visitFunctionExpression(FunctionExpression node) =>
astFactory.functionExpression(cloneNode(node.typeParameters),
cloneNode(node.parameters), cloneNode(node.body));
@override
FunctionExpressionInvocation visitFunctionExpressionInvocation(
FunctionExpressionInvocation node) =>
astFactory.functionExpressionInvocation(cloneNode(node.function),
cloneNode(node.typeArguments), cloneNode(node.argumentList));
@override
FunctionTypeAlias visitFunctionTypeAlias(FunctionTypeAlias node) =>
astFactory.functionTypeAlias(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.typedefKeyword),
cloneNode(node.returnType),
cloneNode(node.name),
cloneNode(node.typeParameters),
cloneNode(node.parameters),
cloneToken(node.semicolon));
@override
FunctionTypedFormalParameter visitFunctionTypedFormalParameter(
FunctionTypedFormalParameter node) =>
astFactory.functionTypedFormalParameter2(
comment: cloneNode(node.documentationComment),
metadata: cloneNodeList(node.metadata),
covariantKeyword: cloneToken(node.covariantKeyword),
returnType: cloneNode(node.returnType),
identifier: cloneNode(node.identifier),
typeParameters: cloneNode(node.typeParameters),
parameters: cloneNode(node.parameters),
question: cloneToken(node.question));
@override
AstNode visitGenericFunctionType(GenericFunctionType node) =>
astFactory.genericFunctionType(
cloneNode(node.returnType),
cloneToken(node.functionKeyword),
cloneNode(node.typeParameters),
cloneNode(node.parameters),
question: cloneToken(node.question));
@override
AstNode visitGenericTypeAlias(GenericTypeAlias node) =>
astFactory.genericTypeAlias(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.typedefKeyword),
cloneNode(node.name),
cloneNode(node.typeParameters),
cloneToken(node.equals),
cloneNode(node.functionType),
cloneToken(node.semicolon));
@override
HideCombinator visitHideCombinator(HideCombinator node) =>
astFactory.hideCombinator(
cloneToken(node.keyword), cloneNodeList(node.hiddenNames));
@override
IfElement visitIfElement(IfElement node) => astFactory.ifElement(
ifKeyword: cloneToken(node.ifKeyword),
leftParenthesis: cloneToken(node.leftParenthesis),
condition: cloneNode(node.condition),
rightParenthesis: cloneToken(node.rightParenthesis),
thenElement: cloneNode(node.thenElement),
elseKeyword: cloneToken(node.elseKeyword),
elseElement: cloneNode(node.elseElement));
@override
IfStatement visitIfStatement(IfStatement node) => astFactory.ifStatement(
cloneToken(node.ifKeyword),
cloneToken(node.leftParenthesis),
cloneNode(node.condition),
cloneToken(node.rightParenthesis),
cloneNode(node.thenStatement),
cloneToken(node.elseKeyword),
cloneNode(node.elseStatement));
@override
ImplementsClause visitImplementsClause(ImplementsClause node) =>
astFactory.implementsClause(
cloneToken(node.implementsKeyword), cloneNodeList(node.interfaces));
@override
ImportDirective visitImportDirective(ImportDirective node) {
ImportDirectiveImpl directive = astFactory.importDirective(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.keyword),
cloneNode(node.uri),
cloneNodeList(node.configurations),
cloneToken(node.deferredKeyword),
cloneToken(node.asKeyword),
cloneNode(node.prefix),
cloneNodeList(node.combinators),
cloneToken(node.semicolon));
directive.selectedUriContent = node.selectedUriContent;
directive.selectedSource = node.selectedSource;
directive.uriSource = node.uriSource;
directive.uriContent = node.uriContent;
return directive;
}
@override
IndexExpression visitIndexExpression(IndexExpression node) {
Token period = node.period;
if (period == null) {
return astFactory.indexExpressionForTarget(
cloneNode(node.target),
cloneToken(node.leftBracket),
cloneNode(node.index),
cloneToken(node.rightBracket));
} else {
return astFactory.indexExpressionForCascade(
cloneToken(period),
cloneToken(node.leftBracket),
cloneNode(node.index),
cloneToken(node.rightBracket));
}
}
@override
InstanceCreationExpression visitInstanceCreationExpression(
InstanceCreationExpression node) =>
astFactory.instanceCreationExpression(cloneToken(node.keyword),
cloneNode(node.constructorName), cloneNode(node.argumentList));
@override
IntegerLiteral visitIntegerLiteral(IntegerLiteral node) =>
astFactory.integerLiteral(cloneToken(node.literal), node.value);
@override
InterpolationExpression visitInterpolationExpression(
InterpolationExpression node) =>
astFactory.interpolationExpression(cloneToken(node.leftBracket),
cloneNode(node.expression), cloneToken(node.rightBracket));
@override
InterpolationString visitInterpolationString(InterpolationString node) =>
astFactory.interpolationString(cloneToken(node.contents), node.value);
@override
IsExpression visitIsExpression(IsExpression node) => astFactory.isExpression(
cloneNode(node.expression),
cloneToken(node.isOperator),
cloneToken(node.notOperator),
cloneNode(node.type));
@override
Label visitLabel(Label node) =>
astFactory.label(cloneNode(node.label), cloneToken(node.colon));
@override
LabeledStatement visitLabeledStatement(LabeledStatement node) => astFactory
.labeledStatement(cloneNodeList(node.labels), cloneNode(node.statement));
@override
LibraryDirective visitLibraryDirective(LibraryDirective node) =>
astFactory.libraryDirective(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.libraryKeyword),
cloneNode(node.name),
cloneToken(node.semicolon));
@override
LibraryIdentifier visitLibraryIdentifier(LibraryIdentifier node) =>
astFactory.libraryIdentifier(cloneNodeList(node.components));
@override
ListLiteral visitListLiteral(ListLiteral node) => astFactory.listLiteral(
cloneToken(node.constKeyword),
cloneNode(node.typeArguments),
cloneToken(node.leftBracket),
cloneNodeList(node.elements),
cloneToken(node.rightBracket));
@override
MapLiteralEntry visitMapLiteralEntry(MapLiteralEntry node) =>
astFactory.mapLiteralEntry(cloneNode(node.key),
cloneToken(node.separator), cloneNode(node.value));
@override
MethodDeclaration visitMethodDeclaration(MethodDeclaration node) =>
astFactory.methodDeclaration(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.externalKeyword),
cloneToken(node.modifierKeyword),
cloneNode(node.returnType),
cloneToken(node.propertyKeyword),
cloneToken(node.operatorKeyword),
cloneNode(node.name),
cloneNode(node.typeParameters),
cloneNode(node.parameters),
cloneNode(node.body));
@override
MethodInvocation visitMethodInvocation(MethodInvocation node) =>
astFactory.methodInvocation(
cloneNode(node.target),
cloneToken(node.operator),
cloneNode(node.methodName),
cloneNode(node.typeArguments),
cloneNode(node.argumentList));
@override
AstNode visitMixinDeclaration(MixinDeclaration node) =>
astFactory.mixinDeclaration(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.mixinKeyword),
cloneNode(node.name),
cloneNode(node.typeParameters),
cloneNode(node.onClause),
cloneNode(node.implementsClause),
cloneToken(node.leftBracket),
cloneNodeList(node.members),
cloneToken(node.rightBracket));
@override
NamedExpression visitNamedExpression(NamedExpression node) => astFactory
.namedExpression(cloneNode(node.name), cloneNode(node.expression));
@override
AstNode visitNativeClause(NativeClause node) => astFactory.nativeClause(
cloneToken(node.nativeKeyword), cloneNode(node.name));
@override
NativeFunctionBody visitNativeFunctionBody(NativeFunctionBody node) =>
astFactory.nativeFunctionBody(cloneToken(node.nativeKeyword),
cloneNode(node.stringLiteral), cloneToken(node.semicolon));
@override
NullLiteral visitNullLiteral(NullLiteral node) =>
astFactory.nullLiteral(cloneToken(node.literal));
@override
AstNode visitOnClause(OnClause node) => astFactory.onClause(
cloneToken(node.onKeyword), cloneNodeList(node.superclassConstraints));
@override
ParenthesizedExpression visitParenthesizedExpression(
ParenthesizedExpression node) =>
astFactory.parenthesizedExpression(cloneToken(node.leftParenthesis),
cloneNode(node.expression), cloneToken(node.rightParenthesis));
@override
PartDirective visitPartDirective(PartDirective node) {
PartDirective directive = astFactory.partDirective(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.partKeyword),
cloneNode(node.uri),
cloneToken(node.semicolon));
directive.uriSource = node.uriSource;
directive.uriContent = node.uriContent;
return directive;
}
@override
PartOfDirective visitPartOfDirective(PartOfDirective node) =>
astFactory.partOfDirective(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.partKeyword),
cloneToken(node.ofKeyword),
cloneNode(node.uri),
cloneNode(node.libraryName),
cloneToken(node.semicolon));
@override
PostfixExpression visitPostfixExpression(PostfixExpression node) => astFactory
.postfixExpression(cloneNode(node.operand), cloneToken(node.operator));
@override
PrefixedIdentifier visitPrefixedIdentifier(PrefixedIdentifier node) =>
astFactory.prefixedIdentifier(cloneNode(node.prefix),
cloneToken(node.period), cloneNode(node.identifier));
@override
PrefixExpression visitPrefixExpression(PrefixExpression node) => astFactory
.prefixExpression(cloneToken(node.operator), cloneNode(node.operand));
@override
PropertyAccess visitPropertyAccess(PropertyAccess node) =>
astFactory.propertyAccess(cloneNode(node.target),
cloneToken(node.operator), cloneNode(node.propertyName));
@override
RedirectingConstructorInvocation visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) =>
astFactory.redirectingConstructorInvocation(
cloneToken(node.thisKeyword),
cloneToken(node.period),
cloneNode(node.constructorName),
cloneNode(node.argumentList));
@override
RethrowExpression visitRethrowExpression(RethrowExpression node) =>
astFactory.rethrowExpression(cloneToken(node.rethrowKeyword));
@override
ReturnStatement visitReturnStatement(ReturnStatement node) =>
astFactory.returnStatement(cloneToken(node.returnKeyword),
cloneNode(node.expression), cloneToken(node.semicolon));
@override
ScriptTag visitScriptTag(ScriptTag node) =>
astFactory.scriptTag(cloneToken(node.scriptTag));
@override
SetOrMapLiteral visitSetOrMapLiteral(SetOrMapLiteral node) {
var result = astFactory.setOrMapLiteral(
constKeyword: cloneToken(node.constKeyword),
typeArguments: cloneNode(node.typeArguments),
leftBracket: cloneToken(node.leftBracket),
elements: cloneNodeList(node.elements),
rightBracket: cloneToken(node.rightBracket));
if (node.isMap) {
(result as SetOrMapLiteralImpl).becomeMap();
} else if (node.isSet) {
(result as SetOrMapLiteralImpl).becomeSet();
}
return result;
}
@override
ShowCombinator visitShowCombinator(ShowCombinator node) => astFactory
.showCombinator(cloneToken(node.keyword), cloneNodeList(node.shownNames));
@override
SimpleFormalParameter visitSimpleFormalParameter(
SimpleFormalParameter node) =>
astFactory.simpleFormalParameter2(
comment: cloneNode(node.documentationComment),
metadata: cloneNodeList(node.metadata),
covariantKeyword: cloneToken(node.covariantKeyword),
keyword: cloneToken(node.keyword),
type: cloneNode(node.type),
identifier: cloneNode(node.identifier));
@override
SimpleIdentifier visitSimpleIdentifier(SimpleIdentifier node) =>
astFactory.simpleIdentifier(cloneToken(node.token),
isDeclaration: node.inDeclarationContext());
@override
SimpleStringLiteral visitSimpleStringLiteral(SimpleStringLiteral node) =>
astFactory.simpleStringLiteral(cloneToken(node.literal), node.value);
@override
SpreadElement visitSpreadElement(SpreadElement node) =>
astFactory.spreadElement(
spreadOperator: cloneToken(node.spreadOperator),
expression: cloneNode(node.expression));
@override
StringInterpolation visitStringInterpolation(StringInterpolation node) =>
astFactory.stringInterpolation(cloneNodeList(node.elements));
@override
SuperConstructorInvocation visitSuperConstructorInvocation(
SuperConstructorInvocation node) =>
astFactory.superConstructorInvocation(
cloneToken(node.superKeyword),
cloneToken(node.period),
cloneNode(node.constructorName),
cloneNode(node.argumentList));
@override
SuperExpression visitSuperExpression(SuperExpression node) =>
astFactory.superExpression(cloneToken(node.superKeyword));
@override
SwitchCase visitSwitchCase(SwitchCase node) => astFactory.switchCase(
cloneNodeList(node.labels),
cloneToken(node.keyword),
cloneNode(node.expression),
cloneToken(node.colon),
cloneNodeList(node.statements));
@override
SwitchDefault visitSwitchDefault(SwitchDefault node) =>
astFactory.switchDefault(
cloneNodeList(node.labels),
cloneToken(node.keyword),
cloneToken(node.colon),
cloneNodeList(node.statements));
@override
SwitchStatement visitSwitchStatement(SwitchStatement node) =>
astFactory.switchStatement(
cloneToken(node.switchKeyword),
cloneToken(node.leftParenthesis),
cloneNode(node.expression),
cloneToken(node.rightParenthesis),
cloneToken(node.leftBracket),
cloneNodeList(node.members),
cloneToken(node.rightBracket));
@override
SymbolLiteral visitSymbolLiteral(SymbolLiteral node) =>
astFactory.symbolLiteral(
cloneToken(node.poundSign), cloneTokenList(node.components));
@override
ThisExpression visitThisExpression(ThisExpression node) =>
astFactory.thisExpression(cloneToken(node.thisKeyword));
@override
ThrowExpression visitThrowExpression(ThrowExpression node) =>
astFactory.throwExpression(
cloneToken(node.throwKeyword), cloneNode(node.expression));
@override
TopLevelVariableDeclaration visitTopLevelVariableDeclaration(
TopLevelVariableDeclaration node) =>
astFactory.topLevelVariableDeclaration(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneNode(node.variables),
cloneToken(node.semicolon));
@override
TryStatement visitTryStatement(TryStatement node) => astFactory.tryStatement(
cloneToken(node.tryKeyword),
cloneNode(node.body),
cloneNodeList(node.catchClauses),
cloneToken(node.finallyKeyword),
cloneNode(node.finallyBlock));
@override
TypeArgumentList visitTypeArgumentList(TypeArgumentList node) =>
astFactory.typeArgumentList(cloneToken(node.leftBracket),
cloneNodeList(node.arguments), cloneToken(node.rightBracket));
@override
TypeName visitTypeName(TypeName node) =>
astFactory.typeName(cloneNode(node.name), cloneNode(node.typeArguments),
question: cloneToken(node.question));
@override
TypeParameter visitTypeParameter(TypeParameter node) =>
astFactory.typeParameter(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneNode(node.name),
cloneToken(node.extendsKeyword),
cloneNode(node.bound));
@override
TypeParameterList visitTypeParameterList(TypeParameterList node) =>
astFactory.typeParameterList(cloneToken(node.leftBracket),
cloneNodeList(node.typeParameters), cloneToken(node.rightBracket));
@override
VariableDeclaration visitVariableDeclaration(VariableDeclaration node) =>
astFactory.variableDeclaration(cloneNode(node.name),
cloneToken(node.equals), cloneNode(node.initializer));
@override
VariableDeclarationList visitVariableDeclarationList(
VariableDeclarationList node) =>
astFactory.variableDeclarationList(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.keyword),
cloneNode(node.type),
cloneNodeList(node.variables));
@override
VariableDeclarationStatement visitVariableDeclarationStatement(
VariableDeclarationStatement node) =>
astFactory.variableDeclarationStatement(
cloneNode(node.variables), cloneToken(node.semicolon));
@override
WhileStatement visitWhileStatement(WhileStatement node) =>
astFactory.whileStatement(
cloneToken(node.whileKeyword),
cloneToken(node.leftParenthesis),
cloneNode(node.condition),
cloneToken(node.rightParenthesis),
cloneNode(node.body));
@override
WithClause visitWithClause(WithClause node) => astFactory.withClause(
cloneToken(node.withKeyword), cloneNodeList(node.mixinTypes));
@override
YieldStatement visitYieldStatement(YieldStatement node) =>
astFactory.yieldStatement(
cloneToken(node.yieldKeyword),
cloneToken(node.star),
cloneNode(node.expression),
cloneToken(node.semicolon));
/**
* Clone all token starting from the given [token] up to a token that has
* offset greater then [stopAfter], and put mapping from originals to clones
* into [_clonedTokens].
*
* We cannot clone tokens as we visit nodes because not every token is a part
* of a node, E.g. commas in argument lists are not represented in AST. But
* we need to the sequence of tokens that is identical to the original one.
*/
void _cloneTokens(Token token, int stopAfter) {
if (token == null) {
return;
}
Token nonComment(Token token) {
return token is CommentToken ? token.parent : token;
}
token = nonComment(token);
if (_lastCloned == null) {
_lastCloned = new Token.eof(-1);
}
while (token != null) {
Token clone = token.copy();
{
CommentToken c1 = token.precedingComments;
CommentToken c2 = clone.precedingComments;
while (c1 != null && c2 != null) {
_clonedTokens[c1] = c2;
c1 = c1.next;
c2 = c2.next;
}
}
_clonedTokens[token] = clone;
_lastCloned.setNext(clone);
_lastCloned = clone;
if (token.type == TokenType.EOF) {
break;
}
if (token.offset > stopAfter) {
_nextToClone = token.next;
_lastClonedOffset = token.offset;
break;
}
token = token.next;
}
}
/**
* Return a clone of the given [node].
*/
static AstNode clone(AstNode node) {
return node.accept(new AstCloner());
}
}
/**
* An AstVisitor that compares the structure of two AstNodes to see whether they
* are equal.
*/
class AstComparator implements AstVisitor<bool> {
/**
* The AST node with which the node being visited is to be compared. This is
* only valid at the beginning of each visit method (until [isEqualNodes] is
* invoked).
*/
AstNode _other;
/**
* Notify that [first] and second have different length.
* This implementation returns `false`. Subclasses can override and throw.
*/
bool failDifferentLength(List first, List second) {
return false;
}
/**
* Check whether the values of the [first] and [second] nodes are [equal].
* Subclasses can override to throw.
*/
bool failIfNotEqual(
AstNode first, Object firstValue, AstNode second, Object secondValue) {
return firstValue == secondValue;
}
/**
* Check whether [second] is null. Subclasses can override to throw.
*/
bool failIfNotNull(Object first, Object second) {
return second == null;
}
/**
* Notify that [first] is not `null` while [second] one is `null`.
* This implementation returns `false`. Subclasses can override and throw.
*/
bool failIsNull(Object first, Object second) {
return false;
}
/**
* Notify that [first] and [second] have different types.
* This implementation returns `false`. Subclasses can override and throw.
*/
bool failRuntimeType(Object first, Object second) {
return false;
}
/**
* Return `true` if the [first] node and the [second] node have the same
* structure.
*
* *Note:* This method is only visible for testing purposes and should not be
* used by clients.
*/
bool isEqualNodes(AstNode first, AstNode second) {
if (first == null) {
return failIfNotNull(first, second);
} else if (second == null) {
return failIsNull(first, second);
} else if (first.runtimeType != second.runtimeType) {
return failRuntimeType(first, second);
}
_other = second;
return first.accept(this);
}
/**
* Return `true` if the [first] token and the [second] token have the same
* structure.
*
* *Note:* This method is only visible for testing purposes and should not be
* used by clients.
*/
bool isEqualTokens(Token first, Token second) {
if (first == null) {
return failIfNotNull(first, second);
} else if (second == null) {
return failIsNull(first, second);
} else if (identical(first, second)) {
return true;
}
return isEqualTokensNotNull(first, second);
}
/**
* Return `true` if the [first] token and the [second] token have the same
* structure. Both [first] and [second] are not `null`.
*/
bool isEqualTokensNotNull(Token first, Token second) =>
first.offset == second.offset &&
first.length == second.length &&
first.lexeme == second.lexeme;
@override
bool visitAdjacentStrings(AdjacentStrings node) {
AdjacentStrings other = _other as AdjacentStrings;
return _isEqualNodeLists(node.strings, other.strings);
}
@override
bool visitAnnotation(Annotation node) {
Annotation other = _other as Annotation;
return isEqualTokens(node.atSign, other.atSign) &&
isEqualNodes(node.name, other.name) &&
isEqualTokens(node.period, other.period) &&
isEqualNodes(node.constructorName, other.constructorName) &&
isEqualNodes(node.arguments, other.arguments);
}
@override
bool visitArgumentList(ArgumentList node) {
ArgumentList other = _other as ArgumentList;
return isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
_isEqualNodeLists(node.arguments, other.arguments) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis);
}
@override
bool visitAsExpression(AsExpression node) {
AsExpression other = _other as AsExpression;
return isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.asOperator, other.asOperator) &&
isEqualNodes(node.type, other.type);
}
@override
bool visitAssertInitializer(AssertInitializer node) {
AssertInitializer other = _other as AssertInitializer;
return isEqualTokens(node.assertKeyword, other.assertKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.comma, other.comma) &&
isEqualNodes(node.message, other.message) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis);
}
@override
bool visitAssertStatement(AssertStatement node) {
AssertStatement other = _other as AssertStatement;
return isEqualTokens(node.assertKeyword, other.assertKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.comma, other.comma) &&
isEqualNodes(node.message, other.message) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitAssignmentExpression(AssignmentExpression node) {
AssignmentExpression other = _other as AssignmentExpression;
return isEqualNodes(node.leftHandSide, other.leftHandSide) &&
isEqualTokens(node.operator, other.operator) &&
isEqualNodes(node.rightHandSide, other.rightHandSide);
}
@override
bool visitAwaitExpression(AwaitExpression node) {
AwaitExpression other = _other as AwaitExpression;
return isEqualTokens(node.awaitKeyword, other.awaitKeyword) &&
isEqualNodes(node.expression, other.expression);
}
@override
bool visitBinaryExpression(BinaryExpression node) {
BinaryExpression other = _other as BinaryExpression;
return isEqualNodes(node.leftOperand, other.leftOperand) &&
isEqualTokens(node.operator, other.operator) &&
isEqualNodes(node.rightOperand, other.rightOperand);
}
@override
bool visitBlock(Block node) {
Block other = _other as Block;
return isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.statements, other.statements) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitBlockFunctionBody(BlockFunctionBody node) {
BlockFunctionBody other = _other as BlockFunctionBody;
return isEqualNodes(node.block, other.block);
}
@override
bool visitBooleanLiteral(BooleanLiteral node) {
BooleanLiteral other = _other as BooleanLiteral;
return isEqualTokens(node.literal, other.literal) &&
failIfNotEqual(node, node.value, other, other.value);
}
@override
bool visitBreakStatement(BreakStatement node) {
BreakStatement other = _other as BreakStatement;
return isEqualTokens(node.breakKeyword, other.breakKeyword) &&
isEqualNodes(node.label, other.label) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitCascadeExpression(CascadeExpression node) {
CascadeExpression other = _other as CascadeExpression;
return isEqualNodes(node.target, other.target) &&
_isEqualNodeLists(node.cascadeSections, other.cascadeSections);
}
@override
bool visitCatchClause(CatchClause node) {
CatchClause other = _other as CatchClause;
return isEqualTokens(node.onKeyword, other.onKeyword) &&
isEqualNodes(node.exceptionType, other.exceptionType) &&
isEqualTokens(node.catchKeyword, other.catchKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.exceptionParameter, other.exceptionParameter) &&
isEqualTokens(node.comma, other.comma) &&
isEqualNodes(node.stackTraceParameter, other.stackTraceParameter) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualNodes(node.body, other.body);
}
@override
bool visitClassDeclaration(ClassDeclaration node) {
ClassDeclaration other = _other as ClassDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.abstractKeyword, other.abstractKeyword) &&
isEqualTokens(node.classKeyword, other.classKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.typeParameters, other.typeParameters) &&
isEqualNodes(node.extendsClause, other.extendsClause) &&
isEqualNodes(node.withClause, other.withClause) &&
isEqualNodes(node.implementsClause, other.implementsClause) &&
isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.members, other.members) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitClassTypeAlias(ClassTypeAlias node) {
ClassTypeAlias other = _other as ClassTypeAlias;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.typedefKeyword, other.typedefKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.typeParameters, other.typeParameters) &&
isEqualTokens(node.equals, other.equals) &&
isEqualTokens(node.abstractKeyword, other.abstractKeyword) &&
isEqualNodes(node.superclass, other.superclass) &&
isEqualNodes(node.withClause, other.withClause) &&
isEqualNodes(node.implementsClause, other.implementsClause) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitComment(Comment node) {
Comment other = _other as Comment;
return _isEqualNodeLists(node.references, other.references);
}
@override
bool visitCommentReference(CommentReference node) {
CommentReference other = _other as CommentReference;
return isEqualTokens(node.newKeyword, other.newKeyword) &&
isEqualNodes(node.identifier, other.identifier);
}
@override
bool visitCompilationUnit(CompilationUnit node) {
CompilationUnit other = _other as CompilationUnit;
return isEqualTokens(node.beginToken, other.beginToken) &&
isEqualNodes(node.scriptTag, other.scriptTag) &&
_isEqualNodeLists(node.directives, other.directives) &&
_isEqualNodeLists(node.declarations, other.declarations) &&
isEqualTokens(node.endToken, other.endToken);
}
@override
bool visitConditionalExpression(ConditionalExpression node) {
ConditionalExpression other = _other as ConditionalExpression;
return isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.question, other.question) &&
isEqualNodes(node.thenExpression, other.thenExpression) &&
isEqualTokens(node.colon, other.colon) &&
isEqualNodes(node.elseExpression, other.elseExpression);
}
@override
bool visitConfiguration(Configuration node) {
Configuration other = _other as Configuration;
return isEqualTokens(node.ifKeyword, other.ifKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.name, other.name) &&
isEqualTokens(node.equalToken, other.equalToken) &&
isEqualNodes(node.value, other.value) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualNodes(node.uri, other.uri);
}
@override
bool visitConstructorDeclaration(ConstructorDeclaration node) {
ConstructorDeclaration other = _other as ConstructorDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.externalKeyword, other.externalKeyword) &&
isEqualTokens(node.constKeyword, other.constKeyword) &&
isEqualTokens(node.factoryKeyword, other.factoryKeyword) &&
isEqualNodes(node.returnType, other.returnType) &&
isEqualTokens(node.period, other.period) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.parameters, other.parameters) &&
isEqualTokens(node.separator, other.separator) &&
_isEqualNodeLists(node.initializers, other.initializers) &&
isEqualNodes(node.redirectedConstructor, other.redirectedConstructor) &&
isEqualNodes(node.body, other.body);
}
@override
bool visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
ConstructorFieldInitializer other = _other as ConstructorFieldInitializer;
return isEqualTokens(node.thisKeyword, other.thisKeyword) &&
isEqualTokens(node.period, other.period) &&
isEqualNodes(node.fieldName, other.fieldName) &&
isEqualTokens(node.equals, other.equals) &&
isEqualNodes(node.expression, other.expression);
}
@override
bool visitConstructorName(ConstructorName node) {
ConstructorName other = _other as ConstructorName;
return isEqualNodes(node.type, other.type) &&
isEqualTokens(node.period, other.period) &&
isEqualNodes(node.name, other.name);
}
@override
bool visitContinueStatement(ContinueStatement node) {
ContinueStatement other = _other as ContinueStatement;
return isEqualTokens(node.continueKeyword, other.continueKeyword) &&
isEqualNodes(node.label, other.label) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitDeclaredIdentifier(DeclaredIdentifier node) {
DeclaredIdentifier other = _other as DeclaredIdentifier;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.keyword, other.keyword) &&
isEqualNodes(node.type, other.type) &&
isEqualNodes(node.identifier, other.identifier);
}
@override
bool visitDefaultFormalParameter(DefaultFormalParameter node) {
DefaultFormalParameter other = _other as DefaultFormalParameter;
return isEqualNodes(node.parameter, other.parameter) &&
// ignore: deprecated_member_use_from_same_package
node.kind == other.kind &&
isEqualTokens(node.separator, other.separator) &&
isEqualNodes(node.defaultValue, other.defaultValue);
}
@override
bool visitDoStatement(DoStatement node) {
DoStatement other = _other as DoStatement;
return isEqualTokens(node.doKeyword, other.doKeyword) &&
isEqualNodes(node.body, other.body) &&
isEqualTokens(node.whileKeyword, other.whileKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitDottedName(DottedName node) {
DottedName other = _other as DottedName;
return _isEqualNodeLists(node.components, other.components);
}
@override
bool visitDoubleLiteral(DoubleLiteral node) {
DoubleLiteral other = _other as DoubleLiteral;
return isEqualTokens(node.literal, other.literal) &&
failIfNotEqual(node, node.value, other, other.value);
}
@override
bool visitEmptyFunctionBody(EmptyFunctionBody node) {
EmptyFunctionBody other = _other as EmptyFunctionBody;
return isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitEmptyStatement(EmptyStatement node) {
EmptyStatement other = _other as EmptyStatement;
return isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitEnumConstantDeclaration(EnumConstantDeclaration node) {
EnumConstantDeclaration other = _other as EnumConstantDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualNodes(node.name, other.name);
}
@override
bool visitEnumDeclaration(EnumDeclaration node) {
EnumDeclaration other = _other as EnumDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.enumKeyword, other.enumKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.constants, other.constants) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitExportDirective(ExportDirective node) {
ExportDirective other = _other as ExportDirective;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.keyword, other.keyword) &&
isEqualNodes(node.uri, other.uri) &&
_isEqualNodeLists(node.combinators, other.combinators) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitExpressionFunctionBody(ExpressionFunctionBody node) {
ExpressionFunctionBody other = _other as ExpressionFunctionBody;
return isEqualTokens(node.functionDefinition, other.functionDefinition) &&
isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitExpressionStatement(ExpressionStatement node) {
ExpressionStatement other = _other as ExpressionStatement;
return isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitExtendsClause(ExtendsClause node) {
ExtendsClause other = _other as ExtendsClause;
return isEqualTokens(node.extendsKeyword, other.extendsKeyword) &&
isEqualNodes(node.superclass, other.superclass);
}
@override
bool visitExtensionDeclaration(ExtensionDeclaration node) {
ExtensionDeclaration other = _other as ExtensionDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.extensionKeyword, other.extensionKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.typeParameters, other.typeParameters) &&
isEqualTokens(node.onKeyword, other.onKeyword) &&
isEqualNodes(node.extendedType, other.extendedType) &&
isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.members, other.members) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitExtensionOverride(ExtensionOverride node) {
ExtensionOverride other = _other as ExtensionOverride;
return isEqualNodes(node.extensionName, other.extensionName) &&
isEqualNodes(node.typeArguments, other.typeArguments) &&
isEqualNodes(node.argumentList, other.argumentList);
}
@override
bool visitFieldDeclaration(FieldDeclaration node) {
FieldDeclaration other = _other as FieldDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.staticKeyword, other.staticKeyword) &&
isEqualNodes(node.fields, other.fields) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitFieldFormalParameter(FieldFormalParameter node) {
FieldFormalParameter other = _other as FieldFormalParameter;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.keyword, other.keyword) &&
isEqualNodes(node.type, other.type) &&
isEqualTokens(node.thisKeyword, other.thisKeyword) &&
isEqualTokens(node.period, other.period) &&
isEqualNodes(node.identifier, other.identifier);
}
@override
bool visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) {
ForEachPartsWithDeclaration other = _other as ForEachPartsWithDeclaration;
return isEqualNodes(node.loopVariable, other.loopVariable) &&
isEqualTokens(node.inKeyword, other.inKeyword) &&
isEqualNodes(node.iterable, other.iterable);
}
@override
bool visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) {
ForEachPartsWithIdentifier other = _other as ForEachPartsWithIdentifier;
return isEqualNodes(node.identifier, other.identifier) &&
isEqualTokens(node.inKeyword, other.inKeyword) &&
isEqualNodes(node.iterable, other.iterable);
}
@override
bool visitForElement(ForElement node) {
ForElement other = _other as ForElement;
return isEqualTokens(node.awaitKeyword, other.awaitKeyword) &&
isEqualTokens(node.forKeyword, other.forKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.forLoopParts, other.forLoopParts) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualNodes(node.body, other.body);
}
@override
bool visitFormalParameterList(FormalParameterList node) {
FormalParameterList other = _other as FormalParameterList;
return isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
_isEqualNodeLists(node.parameters, other.parameters) &&
isEqualTokens(node.leftDelimiter, other.leftDelimiter) &&
isEqualTokens(node.rightDelimiter, other.rightDelimiter) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis);
}
@override
bool visitForPartsWithDeclarations(ForPartsWithDeclarations node) {
ForPartsWithDeclarations other = _other as ForPartsWithDeclarations;
return isEqualNodes(node.variables, other.variables) &&
isEqualTokens(node.leftSeparator, other.leftSeparator) &&
isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.rightSeparator, other.rightSeparator) &&
_isEqualNodeLists(node.updaters, other.updaters);
}
@override
bool visitForPartsWithExpression(ForPartsWithExpression node) {
ForPartsWithExpression other = _other as ForPartsWithExpression;
return isEqualNodes(node.initialization, other.initialization) &&
isEqualTokens(node.leftSeparator, other.leftSeparator) &&
isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.rightSeparator, other.rightSeparator) &&
_isEqualNodeLists(node.updaters, other.updaters);
}
@override
bool visitForStatement(ForStatement node) {
ForStatement other = _other as ForStatement;
return isEqualTokens(node.forKeyword, other.forKeyword) &&
isEqualTokens(node.awaitKeyword, other.awaitKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.forLoopParts, other.forLoopParts) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualNodes(node.body, other.body);
}
@override
bool visitFunctionDeclaration(FunctionDeclaration node) {
FunctionDeclaration other = _other as FunctionDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.externalKeyword, other.externalKeyword) &&
isEqualNodes(node.returnType, other.returnType) &&
isEqualTokens(node.propertyKeyword, other.propertyKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.functionExpression, other.functionExpression);
}
@override
bool visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
FunctionDeclarationStatement other = _other as FunctionDeclarationStatement;
return isEqualNodes(node.functionDeclaration, other.functionDeclaration);
}
@override
bool visitFunctionExpression(FunctionExpression node) {
FunctionExpression other = _other as FunctionExpression;
return isEqualNodes(node.parameters, other.parameters) &&
isEqualNodes(node.body, other.body);
}
@override
bool visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
FunctionExpressionInvocation other = _other as FunctionExpressionInvocation;
return isEqualNodes(node.function, other.function) &&
isEqualNodes(node.argumentList, other.argumentList);
}
@override
bool visitFunctionTypeAlias(FunctionTypeAlias node) {
FunctionTypeAlias other = _other as FunctionTypeAlias;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.typedefKeyword, other.typedefKeyword) &&
isEqualNodes(node.returnType, other.returnType) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.typeParameters, other.typeParameters) &&
isEqualNodes(node.parameters, other.parameters) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
FunctionTypedFormalParameter other = _other as FunctionTypedFormalParameter;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualNodes(node.returnType, other.returnType) &&
isEqualNodes(node.identifier, other.identifier) &&
isEqualNodes(node.parameters, other.parameters);
}
@override
bool visitGenericFunctionType(GenericFunctionType node) {
GenericFunctionType other = _other as GenericFunctionType;
return isEqualNodes(node.returnType, other.returnType) &&
isEqualTokens(node.functionKeyword, other.functionKeyword) &&
isEqualNodes(node.typeParameters, other.typeParameters) &&
isEqualNodes(node.parameters, other.parameters) &&
isEqualTokens(node.question, other.question);
}
@override
bool visitGenericTypeAlias(GenericTypeAlias node) {
GenericTypeAlias other = _other as GenericTypeAlias;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.typedefKeyword, other.typedefKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.typeParameters, other.typeParameters) &&
isEqualTokens(node.equals, other.equals) &&
isEqualNodes(node.functionType, other.functionType);
}
@override
bool visitHideCombinator(HideCombinator node) {
HideCombinator other = _other as HideCombinator;
return isEqualTokens(node.keyword, other.keyword) &&
_isEqualNodeLists(node.hiddenNames, other.hiddenNames);
}
@override
bool visitIfElement(IfElement node) {
IfElement other = _other as IfElement;
return isEqualTokens(node.ifKeyword, other.ifKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualNodes(node.thenElement, other.thenElement) &&
isEqualTokens(node.elseKeyword, other.elseKeyword) &&
isEqualNodes(node.elseElement, other.elseElement);
}
@override
bool visitIfStatement(IfStatement node) {
IfStatement other = _other as IfStatement;
return isEqualTokens(node.ifKeyword, other.ifKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualNodes(node.thenStatement, other.thenStatement) &&
isEqualTokens(node.elseKeyword, other.elseKeyword) &&
isEqualNodes(node.elseStatement, other.elseStatement);
}
@override
bool visitImplementsClause(ImplementsClause node) {
ImplementsClause other = _other as ImplementsClause;
return isEqualTokens(node.implementsKeyword, other.implementsKeyword) &&
_isEqualNodeLists(node.interfaces, other.interfaces);
}
@override
bool visitImportDirective(ImportDirective node) {
ImportDirective other = _other as ImportDirective;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.keyword, other.keyword) &&
isEqualNodes(node.uri, other.uri) &&
_isEqualNodeLists(node.configurations, other.configurations) &&
isEqualTokens(node.deferredKeyword, other.deferredKeyword) &&
isEqualTokens(node.asKeyword, other.asKeyword) &&
isEqualNodes(node.prefix, other.prefix) &&
_isEqualNodeLists(node.combinators, other.combinators) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitIndexExpression(IndexExpression node) {
IndexExpression other = _other as IndexExpression;
return isEqualNodes(node.target, other.target) &&
isEqualTokens(node.leftBracket, other.leftBracket) &&
isEqualNodes(node.index, other.index) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitInstanceCreationExpression(InstanceCreationExpression node) {
InstanceCreationExpression other = _other as InstanceCreationExpression;
return isEqualTokens(node.keyword, other.keyword) &&
isEqualNodes(node.constructorName, other.constructorName) &&
isEqualNodes(node.argumentList, other.argumentList);
}
@override
bool visitIntegerLiteral(IntegerLiteral node) {
IntegerLiteral other = _other as IntegerLiteral;
return isEqualTokens(node.literal, other.literal) &&
failIfNotEqual(node, node.value, other, other.value);
}
@override
bool visitInterpolationExpression(InterpolationExpression node) {
InterpolationExpression other = _other as InterpolationExpression;
return isEqualTokens(node.leftBracket, other.leftBracket) &&
isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitInterpolationString(InterpolationString node) {
InterpolationString other = _other as InterpolationString;
return isEqualTokens(node.contents, other.contents) &&
failIfNotEqual(node, node.value, other, other.value);
}
@override
bool visitIsExpression(IsExpression node) {
IsExpression other = _other as IsExpression;
return isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.isOperator, other.isOperator) &&
isEqualTokens(node.notOperator, other.notOperator) &&
isEqualNodes(node.type, other.type);
}
@override
bool visitLabel(Label node) {
Label other = _other as Label;
return isEqualNodes(node.label, other.label) &&
isEqualTokens(node.colon, other.colon);
}
@override
bool visitLabeledStatement(LabeledStatement node) {
LabeledStatement other = _other as LabeledStatement;
return _isEqualNodeLists(node.labels, other.labels) &&
isEqualNodes(node.statement, other.statement);
}
@override
bool visitLibraryDirective(LibraryDirective node) {
LibraryDirective other = _other as LibraryDirective;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.libraryKeyword, other.libraryKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitLibraryIdentifier(LibraryIdentifier node) {
LibraryIdentifier other = _other as LibraryIdentifier;
return _isEqualNodeLists(node.components, other.components);
}
@override
bool visitListLiteral(ListLiteral node) {
ListLiteral other = _other as ListLiteral;
return isEqualTokens(node.constKeyword, other.constKeyword) &&
isEqualNodes(node.typeArguments, other.typeArguments) &&
isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.elements, other.elements) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitMapLiteralEntry(MapLiteralEntry node) {
MapLiteralEntry other = _other as MapLiteralEntry;
return isEqualNodes(node.key, other.key) &&
isEqualTokens(node.separator, other.separator) &&
isEqualNodes(node.value, other.value);
}
@override
bool visitMethodDeclaration(MethodDeclaration node) {
MethodDeclaration other = _other as MethodDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.externalKeyword, other.externalKeyword) &&
isEqualTokens(node.modifierKeyword, other.modifierKeyword) &&
isEqualNodes(node.returnType, other.returnType) &&
isEqualTokens(node.propertyKeyword, other.propertyKeyword) &&
isEqualTokens(node.operatorKeyword, other.operatorKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.parameters, other.parameters) &&
isEqualNodes(node.body, other.body);
}
@override
bool visitMethodInvocation(MethodInvocation node) {
MethodInvocation other = _other as MethodInvocation;
return isEqualNodes(node.target, other.target) &&
isEqualTokens(node.operator, other.operator) &&
isEqualNodes(node.methodName, other.methodName) &&
isEqualNodes(node.argumentList, other.argumentList);
}
@override
bool visitMixinDeclaration(MixinDeclaration node) {
MixinDeclaration other = _other as MixinDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.mixinKeyword, other.mixinKeyword) &&
isEqualNodes(node.name, other.name) &&
isEqualNodes(node.typeParameters, other.typeParameters) &&
isEqualNodes(node.onClause, other.onClause) &&
isEqualNodes(node.implementsClause, other.implementsClause) &&
isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.members, other.members) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitNamedExpression(NamedExpression node) {
NamedExpression other = _other as NamedExpression;
return isEqualNodes(node.name, other.name) &&
isEqualNodes(node.expression, other.expression);
}
@override
bool visitNativeClause(NativeClause node) {
NativeClause other = _other as NativeClause;
return isEqualTokens(node.nativeKeyword, other.nativeKeyword) &&
isEqualNodes(node.name, other.name);
}
@override
bool visitNativeFunctionBody(NativeFunctionBody node) {
NativeFunctionBody other = _other as NativeFunctionBody;
return isEqualTokens(node.nativeKeyword, other.nativeKeyword) &&
isEqualNodes(node.stringLiteral, other.stringLiteral) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitNullLiteral(NullLiteral node) {
NullLiteral other = _other as NullLiteral;
return isEqualTokens(node.literal, other.literal);
}
@override
bool visitOnClause(OnClause node) {
OnClause other = _other as OnClause;
return isEqualTokens(node.onKeyword, other.onKeyword) &&
_isEqualNodeLists(
node.superclassConstraints, other.superclassConstraints);
}
@override
bool visitParenthesizedExpression(ParenthesizedExpression node) {
ParenthesizedExpression other = _other as ParenthesizedExpression;
return isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis);
}
@override
bool visitPartDirective(PartDirective node) {
PartDirective other = _other as PartDirective;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.partKeyword, other.partKeyword) &&
isEqualNodes(node.uri, other.uri) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitPartOfDirective(PartOfDirective node) {
PartOfDirective other = _other as PartOfDirective;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.partKeyword, other.partKeyword) &&
isEqualTokens(node.ofKeyword, other.ofKeyword) &&
isEqualNodes(node.libraryName, other.libraryName) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitPostfixExpression(PostfixExpression node) {
PostfixExpression other = _other as PostfixExpression;
return isEqualNodes(node.operand, other.operand) &&
isEqualTokens(node.operator, other.operator);
}
@override
bool visitPrefixedIdentifier(PrefixedIdentifier node) {
PrefixedIdentifier other = _other as PrefixedIdentifier;
return isEqualNodes(node.prefix, other.prefix) &&
isEqualTokens(node.period, other.period) &&
isEqualNodes(node.identifier, other.identifier);
}
@override
bool visitPrefixExpression(PrefixExpression node) {
PrefixExpression other = _other as PrefixExpression;
return isEqualTokens(node.operator, other.operator) &&
isEqualNodes(node.operand, other.operand);
}
@override
bool visitPropertyAccess(PropertyAccess node) {
PropertyAccess other = _other as PropertyAccess;
return isEqualNodes(node.target, other.target) &&
isEqualTokens(node.operator, other.operator) &&
isEqualNodes(node.propertyName, other.propertyName);
}
@override
bool visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
RedirectingConstructorInvocation other =
_other as RedirectingConstructorInvocation;
return isEqualTokens(node.thisKeyword, other.thisKeyword) &&
isEqualTokens(node.period, other.period) &&
isEqualNodes(node.constructorName, other.constructorName) &&
isEqualNodes(node.argumentList, other.argumentList);
}
@override
bool visitRethrowExpression(RethrowExpression node) {
RethrowExpression other = _other as RethrowExpression;
return isEqualTokens(node.rethrowKeyword, other.rethrowKeyword);
}
@override
bool visitReturnStatement(ReturnStatement node) {
ReturnStatement other = _other as ReturnStatement;
return isEqualTokens(node.returnKeyword, other.returnKeyword) &&
isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitScriptTag(ScriptTag node) {
ScriptTag other = _other as ScriptTag;
return isEqualTokens(node.scriptTag, other.scriptTag);
}
@override
bool visitSetOrMapLiteral(SetOrMapLiteral node) {
SetOrMapLiteral other = _other as SetOrMapLiteral;
return isEqualTokens(node.constKeyword, other.constKeyword) &&
isEqualNodes(node.typeArguments, other.typeArguments) &&
isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.elements, other.elements) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitShowCombinator(ShowCombinator node) {
ShowCombinator other = _other as ShowCombinator;
return isEqualTokens(node.keyword, other.keyword) &&
_isEqualNodeLists(node.shownNames, other.shownNames);
}
@override
bool visitSimpleFormalParameter(SimpleFormalParameter node) {
SimpleFormalParameter other = _other as SimpleFormalParameter;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.keyword, other.keyword) &&
isEqualNodes(node.type, other.type) &&
isEqualNodes(node.identifier, other.identifier);
}
@override
bool visitSimpleIdentifier(SimpleIdentifier node) {
SimpleIdentifier other = _other as SimpleIdentifier;
return isEqualTokens(node.token, other.token);
}
@override
bool visitSimpleStringLiteral(SimpleStringLiteral node) {
SimpleStringLiteral other = _other as SimpleStringLiteral;
return isEqualTokens(node.literal, other.literal) &&
failIfNotEqual(node, node.value, other, other.value);
}
@override
bool visitSpreadElement(SpreadElement node) {
SpreadElement other = _other as SpreadElement;
return isEqualTokens(node.spreadOperator, other.spreadOperator) &&
isEqualNodes(node.expression, other.expression);
}
@override
bool visitStringInterpolation(StringInterpolation node) {
StringInterpolation other = _other as StringInterpolation;
return _isEqualNodeLists(node.elements, other.elements);
}
@override
bool visitSuperConstructorInvocation(SuperConstructorInvocation node) {
SuperConstructorInvocation other = _other as SuperConstructorInvocation;
return isEqualTokens(node.superKeyword, other.superKeyword) &&
isEqualTokens(node.period, other.period) &&
isEqualNodes(node.constructorName, other.constructorName) &&
isEqualNodes(node.argumentList, other.argumentList);
}
@override
bool visitSuperExpression(SuperExpression node) {
SuperExpression other = _other as SuperExpression;
return isEqualTokens(node.superKeyword, other.superKeyword);
}
@override
bool visitSwitchCase(SwitchCase node) {
SwitchCase other = _other as SwitchCase;
return _isEqualNodeLists(node.labels, other.labels) &&
isEqualTokens(node.keyword, other.keyword) &&
isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.colon, other.colon) &&
_isEqualNodeLists(node.statements, other.statements);
}
@override
bool visitSwitchDefault(SwitchDefault node) {
SwitchDefault other = _other as SwitchDefault;
return _isEqualNodeLists(node.labels, other.labels) &&
isEqualTokens(node.keyword, other.keyword) &&
isEqualTokens(node.colon, other.colon) &&
_isEqualNodeLists(node.statements, other.statements);
}
@override
bool visitSwitchStatement(SwitchStatement node) {
SwitchStatement other = _other as SwitchStatement;
return isEqualTokens(node.switchKeyword, other.switchKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.members, other.members) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitSymbolLiteral(SymbolLiteral node) {
SymbolLiteral other = _other as SymbolLiteral;
return isEqualTokens(node.poundSign, other.poundSign) &&
_isEqualTokenLists(node.components, other.components);
}
@override
bool visitThisExpression(ThisExpression node) {
ThisExpression other = _other as ThisExpression;
return isEqualTokens(node.thisKeyword, other.thisKeyword);
}
@override
bool visitThrowExpression(ThrowExpression node) {
ThrowExpression other = _other as ThrowExpression;
return isEqualTokens(node.throwKeyword, other.throwKeyword) &&
isEqualNodes(node.expression, other.expression);
}
@override
bool visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
TopLevelVariableDeclaration other = _other as TopLevelVariableDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualNodes(node.variables, other.variables) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitTryStatement(TryStatement node) {
TryStatement other = _other as TryStatement;
return isEqualTokens(node.tryKeyword, other.tryKeyword) &&
isEqualNodes(node.body, other.body) &&
_isEqualNodeLists(node.catchClauses, other.catchClauses) &&
isEqualTokens(node.finallyKeyword, other.finallyKeyword) &&
isEqualNodes(node.finallyBlock, other.finallyBlock);
}
@override
bool visitTypeArgumentList(TypeArgumentList node) {
TypeArgumentList other = _other as TypeArgumentList;
return isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.arguments, other.arguments) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitTypeName(TypeName node) {
TypeName other = _other as TypeName;
return isEqualNodes(node.name, other.name) &&
isEqualNodes(node.typeArguments, other.typeArguments) &&
isEqualTokens(node.question, other.question);
}
@override
bool visitTypeParameter(TypeParameter node) {
TypeParameter other = _other as TypeParameter;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualNodes(node.name, other.name) &&
isEqualTokens(node.extendsKeyword, other.extendsKeyword) &&
isEqualNodes(node.bound, other.bound);
}
@override
bool visitTypeParameterList(TypeParameterList node) {
TypeParameterList other = _other as TypeParameterList;
return isEqualTokens(node.leftBracket, other.leftBracket) &&
_isEqualNodeLists(node.typeParameters, other.typeParameters) &&
isEqualTokens(node.rightBracket, other.rightBracket);
}
@override
bool visitVariableDeclaration(VariableDeclaration node) {
VariableDeclaration other = _other as VariableDeclaration;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualNodes(node.name, other.name) &&
isEqualTokens(node.equals, other.equals) &&
isEqualNodes(node.initializer, other.initializer);
}
@override
bool visitVariableDeclarationList(VariableDeclarationList node) {
VariableDeclarationList other = _other as VariableDeclarationList;
return isEqualNodes(
node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.keyword, other.keyword) &&
isEqualNodes(node.type, other.type) &&
_isEqualNodeLists(node.variables, other.variables);
}
@override
bool visitVariableDeclarationStatement(VariableDeclarationStatement node) {
VariableDeclarationStatement other = _other as VariableDeclarationStatement;
return isEqualNodes(node.variables, other.variables) &&
isEqualTokens(node.semicolon, other.semicolon);
}
@override
bool visitWhileStatement(WhileStatement node) {
WhileStatement other = _other as WhileStatement;
return isEqualTokens(node.whileKeyword, other.whileKeyword) &&
isEqualTokens(node.leftParenthesis, other.leftParenthesis) &&
isEqualNodes(node.condition, other.condition) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
isEqualNodes(node.body, other.body);
}
@override
bool visitWithClause(WithClause node) {
WithClause other = _other as WithClause;
return isEqualTokens(node.withKeyword, other.withKeyword) &&
_isEqualNodeLists(node.mixinTypes, other.mixinTypes);
}
@override
bool visitYieldStatement(YieldStatement node) {
YieldStatement other = _other as YieldStatement;
return isEqualTokens(node.yieldKeyword, other.yieldKeyword) &&
isEqualNodes(node.expression, other.expression) &&
isEqualTokens(node.semicolon, other.semicolon);
}
/**
* Return `true` if the [first] and [second] lists of AST nodes have the same
* size and corresponding elements are equal.
*/
bool _isEqualNodeLists(NodeList first, NodeList second) {
if (first == null) {
return failIfNotNull(first, second);
} else if (second == null) {
return failIsNull(first, second);
}
int size = first.length;
if (second.length != size) {
return failDifferentLength(first, second);
}
for (int i = 0; i < size; i++) {
if (!isEqualNodes(first[i], second[i])) {
return false;
}
}
return true;
}
/**
* Return `true` if the [first] and [second] lists of tokens have the same
* length and corresponding elements are equal.
*/
bool _isEqualTokenLists(List<Token> first, List<Token> second) {
int length = first.length;
if (second.length != length) {
return failDifferentLength(first, second);
}
for (int i = 0; i < length; i++) {
if (!isEqualTokens(first[i], second[i])) {
return false;
}
}
return true;
}
/**
* Return `true` if the [first] and [second] nodes are equal.
*/
static bool equalNodes(AstNode first, AstNode second) {
AstComparator comparator = new AstComparator();
return comparator.isEqualNodes(first, second);
}
}
/**
* A recursive AST visitor that is used to run over [Expression]s to determine
* whether the expression is composed by at least one deferred
* [PrefixedIdentifier].
*
* See [PrefixedIdentifier.isDeferred].
*/
class DeferredLibraryReferenceDetector extends RecursiveAstVisitor<void> {
/**
* A flag indicating whether an identifier from a deferred library has been
* found.
*/
bool _result = false;
/**
* Return `true` if the visitor found a [PrefixedIdentifier] that returned
* `true` to the [PrefixedIdentifier.isDeferred] query.
*/
bool get result => _result;
@override
void visitPrefixedIdentifier(PrefixedIdentifier node) {
if (!_result) {
if (node.isDeferred) {
_result = true;
}
}
}
}
/**
* A [DelegatingAstVisitor] that will additionally catch all exceptions from the
* delegates without stopping the visiting. A function must be provided that
* will be invoked for each such exception.
*
* Clients may not extend, implement or mix-in this class.
*/
class ExceptionHandlingDelegatingAstVisitor<T> extends DelegatingAstVisitor<T> {
/**
* The function that will be executed for each exception that is thrown by one
* of the visit methods on the delegate.
*/
final ExceptionInDelegateHandler handler;
/**
* Initialize a newly created visitor to use each of the given delegate
* visitors to visit the nodes of an AST structure.
*/
ExceptionHandlingDelegatingAstVisitor(
Iterable<AstVisitor<T>> delegates, this.handler)
: super(delegates) {
if (handler == null) {
throw new ArgumentError('A handler must be provided');
}
}
@override
T visitNode(AstNode node) {
delegates.forEach((delegate) {
try {
node.accept(delegate);
} catch (exception, stackTrace) {
handler(node, delegate, exception, stackTrace);
}
});
node.visitChildren(this);
return null;
}
/**
* A function that can be used with instances of this class to log and then
* ignore any exceptions that are thrown by any of the delegates.
*/
static void logException(
AstNode node, Object visitor, dynamic exception, StackTrace stackTrace) {
StringBuffer buffer = new StringBuffer();
buffer.write('Exception while using a ${visitor.runtimeType} to visit a ');
AstNode currentNode = node;
bool first = true;
while (currentNode != null) {
if (first) {
first = false;
} else {
buffer.write(' in ');
}
buffer.write(currentNode.runtimeType);
currentNode = currentNode.parent;
}
AnalysisEngine.instance.logger.logError(
buffer.toString(), new CaughtException(exception, stackTrace));
}
}
/**
* An object used to locate the [AstNode] associated with a source range, given
* the AST structure built from the source. More specifically, they will return
* the [AstNode] with the shortest length whose source range completely
* encompasses the specified range.
*/
class NodeLocator extends UnifyingAstVisitor<void> {
/**
* The start offset of the range used to identify the node.
*/
int _startOffset = 0;
/**
* The end offset of the range used to identify the node.
*/
int _endOffset = 0;
/**
* The element that was found that corresponds to the given source range, or
* `null` if there is no such element.
*/
AstNode _foundNode;
/**
* Initialize a newly created locator to locate an [AstNode] by locating the
* node within an AST structure that corresponds to the given range of
* characters (between the [startOffset] and [endOffset] in the source.
*/
NodeLocator(int startOffset, [int endOffset])
: this._startOffset = startOffset,
this._endOffset = endOffset ?? startOffset;
/**
* Return the node that was found that corresponds to the given source range
* or `null` if there is no such node.
*/
AstNode get foundNode => _foundNode;
/**
* Search within the given AST [node] for an identifier representing an
* element in the specified source range. Return the element that was found,
* or `null` if no element was found.
*/
AstNode searchWithin(AstNode node) {
if (node == null) {
return null;
}
try {
node.accept(this);
} catch (exception, stackTrace) {
AnalysisEngine.instance.logger.logInformation(
"Unable to locate element at offset ($_startOffset - $_endOffset)",
new CaughtException(exception, stackTrace));
return null;
}
return _foundNode;
}
@override
void visitNode(AstNode node) {
// Don't visit a new tree if the result has been already found.
if (_foundNode != null) {
return;
}
// Check whether the current node covers the selection.
Token beginToken = node.beginToken;
Token endToken = node.endToken;
// Don't include synthetic tokens.
while (endToken != beginToken) {
// Fasta scanner reports unterminated string literal errors
// and generates a synthetic string token with non-zero length.
// Because of this, check for length > 0 rather than !isSynthetic.
if (endToken.type == TokenType.EOF || endToken.length > 0) {
break;
}
endToken = endToken.previous;
}
int end = endToken.end;
int start = node.offset;
if (end < _startOffset || start > _endOffset) {
return;
}
// Check children.
try {
node.visitChildren(this);
} catch (exception, stackTrace) {
// Ignore the exception and proceed in order to visit the rest of the
// structure.
AnalysisEngine.instance.logger.logInformation(
"Exception caught while traversing an AST structure.",
new CaughtException(exception, stackTrace));
}
// Found a child.
if (_foundNode != null) {
return;
}
// Check this node.
if (start <= _startOffset && _endOffset <= end) {
_foundNode = node;
}
}
}
/**
* An object used to locate the [AstNode] associated with a source range.
* More specifically, they will return the deepest [AstNode] which completely
* encompasses the specified range.
*/
class NodeLocator2 extends UnifyingAstVisitor<void> {
/**
* The inclusive start offset of the range used to identify the node.
*/
int _startOffset = 0;
/**
* The inclusive end offset of the range used to identify the node.
*/
int _endOffset = 0;
/**
* The found node or `null` if there is no such node.
*/
AstNode _foundNode;
/**
* Initialize a newly created locator to locate the deepest [AstNode] for
* which `node.offset <= [startOffset]` and `[endOffset] < node.end`.
*
* If [endOffset] is not provided, then it is considered the same as the
* given [startOffset].
*/
NodeLocator2(int startOffset, [int endOffset])
: this._startOffset = startOffset,
this._endOffset = endOffset ?? startOffset;
/**
* Search within the given AST [node] and return the node that was found,
* or `null` if no node was found.
*/
AstNode searchWithin(AstNode node) {
if (node == null) {
return null;
}
try {
node.accept(this);
} catch (exception, stackTrace) {
AnalysisEngine.instance.logger.logInformation(
"Unable to locate element at offset ($_startOffset - $_endOffset)",
new CaughtException(exception, stackTrace));
return null;
}
return _foundNode;
}
@override
void visitNode(AstNode node) {
// Don't visit a new tree if the result has been already found.
if (_foundNode != null) {
return;
}
// Check whether the current node covers the selection.
Token beginToken = node.beginToken;
Token endToken = node.endToken;
// Don't include synthetic tokens.
while (endToken != beginToken) {
// Fasta scanner reports unterminated string literal errors
// and generates a synthetic string token with non-zero length.
// Because of this, check for length > 0 rather than !isSynthetic.
if (endToken.type == TokenType.EOF || endToken.length > 0) {
break;
}
endToken = endToken.previous;
}
int end = endToken.end;
int start = node.offset;
if (end <= _startOffset || start > _endOffset) {
return;
}
// Check children.
try {
node.visitChildren(this);
} catch (exception, stackTrace) {
// Ignore the exception and proceed in order to visit the rest of the
// structure.
AnalysisEngine.instance.logger.logInformation(
"Exception caught while traversing an AST structure.",
new CaughtException(exception, stackTrace));
}
// Found a child.
if (_foundNode != null) {
return;
}
// Check this node.
if (start <= _startOffset && _endOffset < end) {
_foundNode = node;
}
}
}
/**
* An object that will replace one child node in an AST node with another node.
*/
class NodeReplacer implements AstVisitor<bool> {
/**
* The node being replaced.
*/
final AstNode _oldNode;
/**
* The node that is replacing the old node.
*/
final AstNode _newNode;
/**
* Initialize a newly created node locator to replace the [_oldNode] with the
* [_newNode].
*/
NodeReplacer(this._oldNode, this._newNode);
@override
bool visitAdjacentStrings(AdjacentStrings node) {
if (_replaceInList(node.strings)) {
return true;
}
return visitNode(node);
}
bool visitAnnotatedNode(AnnotatedNode node) {
if (identical(node.documentationComment, _oldNode)) {
node.documentationComment = _newNode as Comment;
return true;
} else if (_replaceInList(node.metadata)) {
return true;
}
return visitNode(node);
}
@override
bool visitAnnotation(Annotation node) {
if (identical(node.arguments, _oldNode)) {
node.arguments = _newNode as ArgumentList;
return true;
} else if (identical(node.constructorName, _oldNode)) {
node.constructorName = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.name, _oldNode)) {
node.name = _newNode as Identifier;
return true;
}
return visitNode(node);
}
@override
bool visitArgumentList(ArgumentList node) {
if (_replaceInList(node.arguments)) {
return true;
}
return visitNode(node);
}
@override
bool visitAsExpression(AsExpression node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
} else if (identical(node.type, _oldNode)) {
node.type = _newNode as TypeAnnotation;
return true;
}
return visitNode(node);
}
@override
bool visitAssertInitializer(AssertInitializer node) {
if (identical(node.condition, _oldNode)) {
node.condition = _newNode as Expression;
return true;
}
if (identical(node.message, _oldNode)) {
node.message = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitAssertStatement(AssertStatement node) {
if (identical(node.condition, _oldNode)) {
node.condition = _newNode as Expression;
return true;
}
if (identical(node.message, _oldNode)) {
node.message = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitAssignmentExpression(AssignmentExpression node) {
if (identical(node.leftHandSide, _oldNode)) {
node.leftHandSide = _newNode as Expression;
return true;
} else if (identical(node.rightHandSide, _oldNode)) {
node.rightHandSide = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitAwaitExpression(AwaitExpression node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitBinaryExpression(BinaryExpression node) {
if (identical(node.leftOperand, _oldNode)) {
node.leftOperand = _newNode as Expression;
return true;
} else if (identical(node.rightOperand, _oldNode)) {
node.rightOperand = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitBlock(Block node) {
if (_replaceInList(node.statements)) {
return true;
}
return visitNode(node);
}
@override
bool visitBlockFunctionBody(BlockFunctionBody node) {
if (identical(node.block, _oldNode)) {
node.block = _newNode as Block;
return true;
}
return visitNode(node);
}
@override
bool visitBooleanLiteral(BooleanLiteral node) => visitNode(node);
@override
bool visitBreakStatement(BreakStatement node) {
if (identical(node.label, _oldNode)) {
node.label = _newNode as SimpleIdentifier;
return true;
}
return visitNode(node);
}
@override
bool visitCascadeExpression(CascadeExpression node) {
if (identical(node.target, _oldNode)) {
node.target = _newNode as Expression;
return true;
} else if (_replaceInList(node.cascadeSections)) {
return true;
}
return visitNode(node);
}
@override
bool visitCatchClause(CatchClause node) {
if (identical(node.exceptionType, _oldNode)) {
node.exceptionType = _newNode as TypeAnnotation;
return true;
} else if (identical(node.exceptionParameter, _oldNode)) {
node.exceptionParameter = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.stackTraceParameter, _oldNode)) {
node.stackTraceParameter = _newNode as SimpleIdentifier;
return true;
}
return visitNode(node);
}
@override
bool visitClassDeclaration(ClassDeclaration node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.typeParameters, _oldNode)) {
node.typeParameters = _newNode as TypeParameterList;
return true;
} else if (identical(node.extendsClause, _oldNode)) {
node.extendsClause = _newNode as ExtendsClause;
return true;
} else if (identical(node.withClause, _oldNode)) {
node.withClause = _newNode as WithClause;
return true;
} else if (identical(node.implementsClause, _oldNode)) {
node.implementsClause = _newNode as ImplementsClause;
return true;
} else if (identical(node.nativeClause, _oldNode)) {
node.nativeClause = _newNode as NativeClause;
return true;
} else if (_replaceInList(node.members)) {
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitClassTypeAlias(ClassTypeAlias node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.typeParameters, _oldNode)) {
node.typeParameters = _newNode as TypeParameterList;
return true;
} else if (identical(node.superclass, _oldNode)) {
node.superclass = _newNode as TypeName;
return true;
} else if (identical(node.withClause, _oldNode)) {
node.withClause = _newNode as WithClause;
return true;
} else if (identical(node.implementsClause, _oldNode)) {
node.implementsClause = _newNode as ImplementsClause;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitComment(Comment node) {
if (_replaceInList(node.references)) {
return true;
}
return visitNode(node);
}
@override
bool visitCommentReference(CommentReference node) {
if (identical(node.identifier, _oldNode)) {
node.identifier = _newNode as Identifier;
return true;
}
return visitNode(node);
}
@override
bool visitCompilationUnit(CompilationUnit node) {
if (identical(node.scriptTag, _oldNode)) {
node.scriptTag = _newNode as ScriptTag;
return true;
} else if (_replaceInList(node.directives)) {
return true;
} else if (_replaceInList(node.declarations)) {
return true;
}
return visitNode(node);
}
@override
bool visitConditionalExpression(ConditionalExpression node) {
if (identical(node.condition, _oldNode)) {
node.condition = _newNode as Expression;
return true;
} else if (identical(node.thenExpression, _oldNode)) {
node.thenExpression = _newNode as Expression;
return true;
} else if (identical(node.elseExpression, _oldNode)) {
node.elseExpression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitConfiguration(Configuration node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as DottedName;
return true;
} else if (identical(node.value, _oldNode)) {
node.value = _newNode as StringLiteral;
return true;
} else if (identical(node.uri, _oldNode)) {
node.uri = _newNode as StringLiteral;
return true;
}
return visitNode(node);
}
@override
bool visitConstructorDeclaration(ConstructorDeclaration node) {
if (identical(node.returnType, _oldNode)) {
node.returnType = _newNode as Identifier;
return true;
} else if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.parameters, _oldNode)) {
node.parameters = _newNode as FormalParameterList;
return true;
} else if (identical(node.redirectedConstructor, _oldNode)) {
node.redirectedConstructor = _newNode as ConstructorName;
return true;
} else if (identical(node.body, _oldNode)) {
node.body = _newNode as FunctionBody;
return true;
} else if (_replaceInList(node.initializers)) {
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
if (identical(node.fieldName, _oldNode)) {
node.fieldName = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitConstructorName(ConstructorName node) {
if (identical(node.type, _oldNode)) {
node.type = _newNode as TypeName;
return true;
} else if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
}
return visitNode(node);
}
@override
bool visitContinueStatement(ContinueStatement node) {
if (identical(node.label, _oldNode)) {
node.label = _newNode as SimpleIdentifier;
return true;
}
return visitNode(node);
}
@override
bool visitDeclaredIdentifier(DeclaredIdentifier node) {
if (identical(node.type, _oldNode)) {
node.type = _newNode as TypeAnnotation;
return true;
} else if (identical(node.identifier, _oldNode)) {
node.identifier = _newNode as SimpleIdentifier;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitDefaultFormalParameter(DefaultFormalParameter node) {
if (identical(node.parameter, _oldNode)) {
node.parameter = _newNode as NormalFormalParameter;
return true;
} else if (identical(node.defaultValue, _oldNode)) {
node.defaultValue = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitDoStatement(DoStatement node) {
if (identical(node.body, _oldNode)) {
node.body = _newNode as Statement;
return true;
} else if (identical(node.condition, _oldNode)) {
node.condition = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitDottedName(DottedName node) {
if (_replaceInList(node.components)) {
return true;
}
return visitNode(node);
}
@override
bool visitDoubleLiteral(DoubleLiteral node) => visitNode(node);
@override
bool visitEmptyFunctionBody(EmptyFunctionBody node) => visitNode(node);
@override
bool visitEmptyStatement(EmptyStatement node) => visitNode(node);
@override
bool visitEnumConstantDeclaration(EnumConstantDeclaration node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitEnumDeclaration(EnumDeclaration node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (_replaceInList(node.constants)) {
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitExportDirective(ExportDirective node) =>
visitNamespaceDirective(node);
@override
bool visitExpressionFunctionBody(ExpressionFunctionBody node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitExpressionStatement(ExpressionStatement node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitExtendsClause(ExtendsClause node) {
if (identical(node.superclass, _oldNode)) {
node.superclass = _newNode as TypeName;
return true;
}
return visitNode(node);
}
bool visitExtensionDeclaration(ExtensionDeclaration node) {
if (identical(node.documentationComment, _oldNode)) {
node.documentationComment = _newNode as Comment;
return true;
} else if (_replaceInList(node.metadata)) {
return true;
} else if (identical(node.name, _oldNode)) {
(node as ExtensionDeclarationImpl).name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.typeParameters, _oldNode)) {
(node as ExtensionDeclarationImpl).typeParameters =
_newNode as TypeParameterList;
return true;
} else if (identical(node.extendedType, _oldNode)) {
(node as ExtensionDeclarationImpl).extendedType =
_newNode as TypeAnnotation;
return true;
} else if (_replaceInList(node.members)) {
return true;
}
return visitNode(node);
}
@override
bool visitExtensionOverride(ExtensionOverride node) {
if (identical(node.extensionName, _oldNode)) {
(node as ExtensionOverrideImpl).extensionName = _newNode as Identifier;
return true;
} else if (identical(node.typeArguments, _oldNode)) {
(node as ExtensionOverrideImpl).typeArguments =
_newNode as TypeArgumentList;
return true;
} else if (identical(node.argumentList, _oldNode)) {
(node as ExtensionOverrideImpl).argumentList = _newNode as ArgumentList;
return true;
}
return visitNode(node);
}
@override
bool visitFieldDeclaration(FieldDeclaration node) {
if (identical(node.fields, _oldNode)) {
node.fields = _newNode as VariableDeclarationList;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitFieldFormalParameter(FieldFormalParameter node) {
if (identical(node.type, _oldNode)) {
node.type = _newNode as TypeAnnotation;
return true;
} else if (identical(node.parameters, _oldNode)) {
node.parameters = _newNode as FormalParameterList;
return true;
}
return visitNormalFormalParameter(node);
}
@override
bool visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) {
if (identical(node.loopVariable, _oldNode)) {
(node as ForEachPartsWithDeclarationImpl).loopVariable =
_newNode as DeclaredIdentifier;
return true;
} else if (identical(node.iterable, _oldNode)) {
(node as ForEachPartsWithDeclarationImpl).iterable =
_newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) {
if (identical(node.identifier, _oldNode)) {
(node as ForEachPartsWithIdentifierImpl).identifier =
_newNode as SimpleIdentifier;
return true;
} else if (identical(node.iterable, _oldNode)) {
(node as ForEachPartsWithIdentifierImpl).iterable =
_newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitForElement(ForElement node) {
if (identical(node.forLoopParts, _oldNode)) {
(node as ForElementImpl).forLoopParts = _newNode as ForLoopParts;
return true;
} else if (identical(node.body, _oldNode)) {
(node as ForElementImpl).body = _newNode as CollectionElement;
return true;
}
return visitNode(node);
}
@override
bool visitFormalParameterList(FormalParameterList node) {
if (_replaceInList(node.parameters)) {
return true;
}
return visitNode(node);
}
@override
bool visitForPartsWithDeclarations(ForPartsWithDeclarations node) {
if (identical(node.variables, _oldNode)) {
(node as ForPartsWithDeclarationsImpl).variables =
_newNode as VariableDeclarationList;
return true;
} else if (identical(node.condition, _oldNode)) {
(node as ForPartsWithDeclarationsImpl).condition = _newNode as Expression;
return true;
} else if (_replaceInList(node.updaters)) {
return true;
}
return visitNode(node);
}
@override
bool visitForPartsWithExpression(ForPartsWithExpression node) {
if (identical(node.initialization, _oldNode)) {
(node as ForPartsWithExpressionImpl).initialization =
_newNode as Expression;
return true;
} else if (identical(node.condition, _oldNode)) {
(node as ForPartsWithExpressionImpl).condition = _newNode as Expression;
return true;
} else if (_replaceInList(node.updaters)) {
return true;
}
return visitNode(node);
}
@override
bool visitForStatement(ForStatement node) {
if (identical(node.forLoopParts, _oldNode)) {
(node as ForStatementImpl).forLoopParts = _newNode as ForLoopParts;
return true;
} else if (identical(node.body, _oldNode)) {
(node as ForStatementImpl).body = _newNode as Statement;
return true;
}
return visitNode(node);
}
@override
bool visitFunctionDeclaration(FunctionDeclaration node) {
if (identical(node.returnType, _oldNode)) {
node.returnType = _newNode as TypeAnnotation;
return true;
} else if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.functionExpression, _oldNode)) {
node.functionExpression = _newNode as FunctionExpression;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
if (identical(node.functionDeclaration, _oldNode)) {
node.functionDeclaration = _newNode as FunctionDeclaration;
return true;
}
return visitNode(node);
}
@override
bool visitFunctionExpression(FunctionExpression node) {
if (identical(node.parameters, _oldNode)) {
node.parameters = _newNode as FormalParameterList;
return true;
} else if (identical(node.body, _oldNode)) {
node.body = _newNode as FunctionBody;
return true;
}
return visitNode(node);
}
@override
bool visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
if (identical(node.function, _oldNode)) {
node.function = _newNode as Expression;
return true;
} else if (identical(node.argumentList, _oldNode)) {
node.argumentList = _newNode as ArgumentList;
return true;
}
return visitNode(node);
}
@override
bool visitFunctionTypeAlias(FunctionTypeAlias node) {
if (identical(node.returnType, _oldNode)) {
node.returnType = _newNode as TypeAnnotation;
return true;
} else if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.typeParameters, _oldNode)) {
node.typeParameters = _newNode as TypeParameterList;
return true;
} else if (identical(node.parameters, _oldNode)) {
node.parameters = _newNode as FormalParameterList;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
if (identical(node.returnType, _oldNode)) {
node.returnType = _newNode as TypeAnnotation;
return true;
} else if (identical(node.parameters, _oldNode)) {
node.parameters = _newNode as FormalParameterList;
return true;
}
return visitNormalFormalParameter(node);
}
@override
bool visitGenericFunctionType(GenericFunctionType node) {
if (identical(node.returnType, _oldNode)) {
node.returnType = _newNode as TypeAnnotation;
return true;
} else if (identical(node.typeParameters, _oldNode)) {
node.typeParameters = _newNode as TypeParameterList;
return true;
} else if (identical(node.parameters, _oldNode)) {
node.parameters = _newNode as FormalParameterList;
return true;
}
return null;
}
@override
bool visitGenericTypeAlias(GenericTypeAlias node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.typeParameters, _oldNode)) {
node.typeParameters = _newNode as TypeParameterList;
return true;
} else if (identical(node.functionType, _oldNode)) {
node.functionType = _newNode as GenericFunctionType;
return true;
} else if (_replaceInList(node.metadata)) {
return true;
}
return visitNode(node);
}
@override
bool visitHideCombinator(HideCombinator node) {
if (_replaceInList(node.hiddenNames)) {
return true;
}
return visitNode(node);
}
@override
bool visitIfElement(IfElement node) {
if (identical(node.condition, _oldNode)) {
(node as IfElementImpl).condition = _newNode as Expression;
return true;
} else if (identical(node.thenElement, _oldNode)) {
(node as IfElementImpl).thenElement = _newNode as CollectionElement;
return true;
} else if (identical(node.elseElement, _oldNode)) {
(node as IfElementImpl).elseElement = _newNode as CollectionElement;
return true;
}
return visitNode(node);
}
@override
bool visitIfStatement(IfStatement node) {
if (identical(node.condition, _oldNode)) {
node.condition = _newNode as Expression;
return true;
} else if (identical(node.thenStatement, _oldNode)) {
node.thenStatement = _newNode as Statement;
return true;
} else if (identical(node.elseStatement, _oldNode)) {
node.elseStatement = _newNode as Statement;
return true;
}
return visitNode(node);
}
@override
bool visitImplementsClause(ImplementsClause node) {
if (_replaceInList(node.interfaces)) {
return true;
}
return visitNode(node);
}
@override
bool visitImportDirective(ImportDirective node) {
if (identical(node.prefix, _oldNode)) {
node.prefix = _newNode as SimpleIdentifier;
return true;
}
return visitNamespaceDirective(node);
}
@override
bool visitIndexExpression(IndexExpression node) {
if (identical(node.target, _oldNode)) {
node.target = _newNode as Expression;
return true;
} else if (identical(node.index, _oldNode)) {
node.index = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitInstanceCreationExpression(InstanceCreationExpression node) {
if (identical(node.constructorName, _oldNode)) {
node.constructorName = _newNode as ConstructorName;
return true;
} else if (identical(node.argumentList, _oldNode)) {
node.argumentList = _newNode as ArgumentList;
return true;
}
return visitNode(node);
}
@override
bool visitIntegerLiteral(IntegerLiteral node) => visitNode(node);
@override
bool visitInterpolationExpression(InterpolationExpression node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitInterpolationString(InterpolationString node) => visitNode(node);
@override
bool visitIsExpression(IsExpression node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
} else if (identical(node.type, _oldNode)) {
node.type = _newNode as TypeAnnotation;
return true;
}
return visitNode(node);
}
@override
bool visitLabel(Label node) {
if (identical(node.label, _oldNode)) {
node.label = _newNode as SimpleIdentifier;
return true;
}
return visitNode(node);
}
@override
bool visitLabeledStatement(LabeledStatement node) {
if (identical(node.statement, _oldNode)) {
node.statement = _newNode as Statement;
return true;
} else if (_replaceInList(node.labels)) {
return true;
}
return visitNode(node);
}
@override
bool visitLibraryDirective(LibraryDirective node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as LibraryIdentifier;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitLibraryIdentifier(LibraryIdentifier node) {
if (_replaceInList(node.components)) {
return true;
}
return visitNode(node);
}
@override
bool visitListLiteral(ListLiteral node) {
if (_replaceInList(node.elements)) {
return true;
}
return visitTypedLiteral(node);
}
@override
bool visitMapLiteralEntry(MapLiteralEntry node) {
if (identical(node.key, _oldNode)) {
node.key = _newNode as Expression;
return true;
} else if (identical(node.value, _oldNode)) {
node.value = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitMethodDeclaration(MethodDeclaration node) {
if (identical(node.returnType, _oldNode)) {
node.returnType = _newNode as TypeAnnotation;
return true;
} else if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.parameters, _oldNode)) {
node.parameters = _newNode as FormalParameterList;
return true;
} else if (identical(node.body, _oldNode)) {
node.body = _newNode as FunctionBody;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitMethodInvocation(MethodInvocation node) {
if (identical(node.target, _oldNode)) {
node.target = _newNode as Expression;
return true;
} else if (identical(node.methodName, _oldNode)) {
node.methodName = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.argumentList, _oldNode)) {
node.argumentList = _newNode as ArgumentList;
return true;
}
return visitNode(node);
}
@override
bool visitMixinDeclaration(MixinDeclaration node) {
if (identical(node.documentationComment, _oldNode)) {
node.documentationComment = _newNode as Comment;
return true;
} else if (_replaceInList(node.metadata)) {
return true;
} else if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.typeParameters, _oldNode)) {
(node as MixinDeclarationImpl).typeParameters =
_newNode as TypeParameterList;
return true;
} else if (identical(node.onClause, _oldNode)) {
(node as MixinDeclarationImpl).onClause = _newNode as OnClause;
return true;
} else if (identical(node.implementsClause, _oldNode)) {
(node as MixinDeclarationImpl).implementsClause =
_newNode as ImplementsClause;
return true;
} else if (_replaceInList(node.members)) {
return true;
}
return visitNode(node);
}
@override
bool visitNamedExpression(NamedExpression node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as Label;
return true;
} else if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
bool visitNamespaceDirective(NamespaceDirective node) {
if (_replaceInList(node.combinators)) {
return true;
}
return visitUriBasedDirective(node);
}
@override
bool visitNativeClause(NativeClause node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as StringLiteral;
return true;
}
return visitNode(node);
}
@override
bool visitNativeFunctionBody(NativeFunctionBody node) {
if (identical(node.stringLiteral, _oldNode)) {
node.stringLiteral = _newNode as StringLiteral;
return true;
}
return visitNode(node);
}
bool visitNode(AstNode node) {
throw new ArgumentError("The old node is not a child of it's parent");
}
bool visitNormalFormalParameter(NormalFormalParameter node) {
if (identical(node.documentationComment, _oldNode)) {
node.documentationComment = _newNode as Comment;
return true;
} else if (identical(node.identifier, _oldNode)) {
node.identifier = _newNode as SimpleIdentifier;
return true;
} else if (_replaceInList(node.metadata)) {
return true;
}
return visitNode(node);
}
@override
bool visitNullLiteral(NullLiteral node) => visitNode(node);
@override
bool visitOnClause(OnClause node) {
if (_replaceInList(node.superclassConstraints)) {
return true;
}
return visitNode(node);
}
@override
bool visitParenthesizedExpression(ParenthesizedExpression node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitPartDirective(PartDirective node) => visitUriBasedDirective(node);
@override
bool visitPartOfDirective(PartOfDirective node) {
if (identical(node.libraryName, _oldNode)) {
node.libraryName = _newNode as LibraryIdentifier;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitPostfixExpression(PostfixExpression node) {
if (identical(node.operand, _oldNode)) {
node.operand = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitPrefixedIdentifier(PrefixedIdentifier node) {
if (identical(node.prefix, _oldNode)) {
node.prefix = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.identifier, _oldNode)) {
node.identifier = _newNode as SimpleIdentifier;
return true;
}
return visitNode(node);
}
@override
bool visitPrefixExpression(PrefixExpression node) {
if (identical(node.operand, _oldNode)) {
node.operand = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitPropertyAccess(PropertyAccess node) {
if (identical(node.target, _oldNode)) {
node.target = _newNode as Expression;
return true;
} else if (identical(node.propertyName, _oldNode)) {
node.propertyName = _newNode as SimpleIdentifier;
return true;
}
return visitNode(node);
}
@override
bool visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
if (identical(node.constructorName, _oldNode)) {
node.constructorName = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.argumentList, _oldNode)) {
node.argumentList = _newNode as ArgumentList;
return true;
}
return visitNode(node);
}
@override
bool visitRethrowExpression(RethrowExpression node) => visitNode(node);
@override
bool visitReturnStatement(ReturnStatement node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitScriptTag(ScriptTag scriptTag) => visitNode(scriptTag);
@override
bool visitSetOrMapLiteral(SetOrMapLiteral node) {
if (_replaceInList(node.elements)) {
return true;
}
return visitTypedLiteral(node);
}
@override
bool visitShowCombinator(ShowCombinator node) {
if (_replaceInList(node.shownNames)) {
return true;
}
return visitNode(node);
}
@override
bool visitSimpleFormalParameter(SimpleFormalParameter node) {
if (identical(node.type, _oldNode)) {
node.type = _newNode as TypeAnnotation;
return true;
}
return visitNormalFormalParameter(node);
}
@override
bool visitSimpleIdentifier(SimpleIdentifier node) => visitNode(node);
@override
bool visitSimpleStringLiteral(SimpleStringLiteral node) => visitNode(node);
@override
bool visitSpreadElement(SpreadElement node) {
if (identical(node.expression, _oldNode)) {
(node as SpreadElementImpl).expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitStringInterpolation(StringInterpolation node) {
if (_replaceInList(node.elements)) {
return true;
}
return visitNode(node);
}
@override
bool visitSuperConstructorInvocation(SuperConstructorInvocation node) {
if (identical(node.constructorName, _oldNode)) {
node.constructorName = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.argumentList, _oldNode)) {
node.argumentList = _newNode as ArgumentList;
return true;
}
return visitNode(node);
}
@override
bool visitSuperExpression(SuperExpression node) => visitNode(node);
@override
bool visitSwitchCase(SwitchCase node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitSwitchMember(node);
}
@override
bool visitSwitchDefault(SwitchDefault node) => visitSwitchMember(node);
bool visitSwitchMember(SwitchMember node) {
if (_replaceInList(node.labels)) {
return true;
} else if (_replaceInList(node.statements)) {
return true;
}
return visitNode(node);
}
@override
bool visitSwitchStatement(SwitchStatement node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
} else if (_replaceInList(node.members)) {
return true;
}
return visitNode(node);
}
@override
bool visitSymbolLiteral(SymbolLiteral node) => visitNode(node);
@override
bool visitThisExpression(ThisExpression node) => visitNode(node);
@override
bool visitThrowExpression(ThrowExpression node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
@override
bool visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
if (identical(node.variables, _oldNode)) {
node.variables = _newNode as VariableDeclarationList;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitTryStatement(TryStatement node) {
if (identical(node.body, _oldNode)) {
node.body = _newNode as Block;
return true;
} else if (identical(node.finallyBlock, _oldNode)) {
node.finallyBlock = _newNode as Block;
return true;
} else if (_replaceInList(node.catchClauses)) {
return true;
}
return visitNode(node);
}
@override
bool visitTypeArgumentList(TypeArgumentList node) {
if (_replaceInList(node.arguments)) {
return true;
}
return visitNode(node);
}
bool visitTypedLiteral(TypedLiteral node) {
if (identical(node.typeArguments, _oldNode)) {
node.typeArguments = _newNode as TypeArgumentList;
return true;
}
return visitNode(node);
}
@override
bool visitTypeName(TypeName node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as Identifier;
return true;
} else if (identical(node.typeArguments, _oldNode)) {
node.typeArguments = _newNode as TypeArgumentList;
return true;
}
return visitNode(node);
}
@override
bool visitTypeParameter(TypeParameter node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.bound, _oldNode)) {
node.bound = _newNode as TypeAnnotation;
return true;
}
return visitNode(node);
}
@override
bool visitTypeParameterList(TypeParameterList node) {
if (_replaceInList(node.typeParameters)) {
return true;
}
return visitNode(node);
}
bool visitUriBasedDirective(UriBasedDirective node) {
if (identical(node.uri, _oldNode)) {
node.uri = _newNode as StringLiteral;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitVariableDeclaration(VariableDeclaration node) {
if (identical(node.name, _oldNode)) {
node.name = _newNode as SimpleIdentifier;
return true;
} else if (identical(node.initializer, _oldNode)) {
node.initializer = _newNode as Expression;
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitVariableDeclarationList(VariableDeclarationList node) {
if (identical(node.type, _oldNode)) {
node.type = _newNode as TypeAnnotation;
return true;
} else if (_replaceInList(node.variables)) {
return true;
}
return visitAnnotatedNode(node);
}
@override
bool visitVariableDeclarationStatement(VariableDeclarationStatement node) {
if (identical(node.variables, _oldNode)) {
node.variables = _newNode as VariableDeclarationList;
return true;
}
return visitNode(node);
}
@override
bool visitWhileStatement(WhileStatement node) {
if (identical(node.condition, _oldNode)) {
node.condition = _newNode as Expression;
return true;
} else if (identical(node.body, _oldNode)) {
node.body = _newNode as Statement;
return true;
}
return visitNode(node);
}
@override
bool visitWithClause(WithClause node) {
if (_replaceInList(node.mixinTypes)) {
return true;
}
return visitNode(node);
}
@override
bool visitYieldStatement(YieldStatement node) {
if (identical(node.expression, _oldNode)) {
node.expression = _newNode as Expression;
return true;
}
return visitNode(node);
}
bool _replaceInList(NodeList list) {
int count = list.length;
for (int i = 0; i < count; i++) {
if (identical(_oldNode, list[i])) {
list[i] = _newNode;
return true;
}
}
return false;
}
/**
* Replace the [oldNode] with the [newNode] in the AST structure containing
* the old node. Return `true` if the replacement was successful.
*
* Throws an [ArgumentError] if either node is `null`, if the old node does
* not have a parent node, or if the AST structure has been corrupted.
*/
static bool replace(AstNode oldNode, AstNode newNode) {
if (oldNode == null || newNode == null) {
throw new ArgumentError("The old and new nodes must be non-null");
} else if (identical(oldNode, newNode)) {
return true;
}
AstNode parent = oldNode.parent;
if (parent == null) {
throw new ArgumentError("The old node is not a child of another node");
}
NodeReplacer replacer = new NodeReplacer(oldNode, newNode);
return parent.accept(replacer);
}
}
/**
* An object that copies resolution information from one AST structure to
* another as long as the structures of the corresponding children of a pair of
* nodes are the same.
*/
class ResolutionCopier implements AstVisitor<bool> {
/**
* The AST node with which the node being visited is to be compared. This is
* only valid at the beginning of each visit method (until [isEqualNodes] is
* invoked).
*/
AstNode _toNode;
@override
bool visitAdjacentStrings(AdjacentStrings node) {
AdjacentStrings toNode = this._toNode as AdjacentStrings;
if (_isEqualNodeLists(node.strings, toNode.strings)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitAnnotation(Annotation node) {
Annotation toNode = this._toNode as Annotation;
if (_and(
_isEqualTokens(node.atSign, toNode.atSign),
_isEqualNodes(node.name, toNode.name),
_isEqualTokens(node.period, toNode.period),
_isEqualNodes(node.constructorName, toNode.constructorName),
_isEqualNodes(node.arguments, toNode.arguments))) {
toNode.element = node.element;
return true;
}
return false;
}
@override
bool visitArgumentList(ArgumentList node) {
ArgumentList toNode = this._toNode as ArgumentList;
return _and(
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodeLists(node.arguments, toNode.arguments),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis));
}
@override
bool visitAsExpression(AsExpression node) {
AsExpression toNode = this._toNode as AsExpression;
if (_and(
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.asOperator, toNode.asOperator),
_isEqualNodes(node.type, toNode.type))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitAssertInitializer(AssertInitializer node) {
AssertInitializer toNode = this._toNode as AssertInitializer;
return _and(
_isEqualTokens(node.assertKeyword, toNode.assertKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.comma, toNode.comma),
_isEqualNodes(node.message, toNode.message),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis));
}
@override
bool visitAssertStatement(AssertStatement node) {
AssertStatement toNode = this._toNode as AssertStatement;
return _and(
_isEqualTokens(node.assertKeyword, toNode.assertKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.comma, toNode.comma),
_isEqualNodes(node.message, toNode.message),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitAssignmentExpression(AssignmentExpression node) {
AssignmentExpression toNode = this._toNode as AssignmentExpression;
if (_and(
_isEqualNodes(node.leftHandSide, toNode.leftHandSide),
_isEqualTokens(node.operator, toNode.operator),
_isEqualNodes(node.rightHandSide, toNode.rightHandSide))) {
toNode.staticElement = node.staticElement;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitAwaitExpression(AwaitExpression node) {
AwaitExpression toNode = this._toNode as AwaitExpression;
if (_and(_isEqualTokens(node.awaitKeyword, toNode.awaitKeyword),
_isEqualNodes(node.expression, toNode.expression))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitBinaryExpression(BinaryExpression node) {
BinaryExpression toNode = this._toNode as BinaryExpression;
if (_and(
_isEqualNodes(node.leftOperand, toNode.leftOperand),
_isEqualTokens(node.operator, toNode.operator),
_isEqualNodes(node.rightOperand, toNode.rightOperand))) {
toNode.staticElement = node.staticElement;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitBlock(Block node) {
Block toNode = this._toNode as Block;
return _and(
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.statements, toNode.statements),
_isEqualTokens(node.rightBracket, toNode.rightBracket));
}
@override
bool visitBlockFunctionBody(BlockFunctionBody node) {
BlockFunctionBody toNode = this._toNode as BlockFunctionBody;
return _isEqualNodes(node.block, toNode.block);
}
@override
bool visitBooleanLiteral(BooleanLiteral node) {
BooleanLiteral toNode = this._toNode as BooleanLiteral;
if (_and(_isEqualTokens(node.literal, toNode.literal),
node.value == toNode.value)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitBreakStatement(BreakStatement node) {
BreakStatement toNode = this._toNode as BreakStatement;
if (_and(
_isEqualTokens(node.breakKeyword, toNode.breakKeyword),
_isEqualNodes(node.label, toNode.label),
_isEqualTokens(node.semicolon, toNode.semicolon))) {
// TODO(paulberry): map node.target to toNode.target.
return true;
}
return false;
}
@override
bool visitCascadeExpression(CascadeExpression node) {
CascadeExpression toNode = this._toNode as CascadeExpression;
if (_and(_isEqualNodes(node.target, toNode.target),
_isEqualNodeLists(node.cascadeSections, toNode.cascadeSections))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitCatchClause(CatchClause node) {
CatchClause toNode = this._toNode as CatchClause;
return _and(
_isEqualTokens(node.onKeyword, toNode.onKeyword),
_isEqualNodes(node.exceptionType, toNode.exceptionType),
_isEqualTokens(node.catchKeyword, toNode.catchKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.exceptionParameter, toNode.exceptionParameter),
_isEqualTokens(node.comma, toNode.comma),
_isEqualNodes(node.stackTraceParameter, toNode.stackTraceParameter),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualNodes(node.body, toNode.body));
}
@override
bool visitClassDeclaration(ClassDeclaration node) {
ClassDeclaration toNode = this._toNode as ClassDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.abstractKeyword, toNode.abstractKeyword),
_isEqualTokens(node.classKeyword, toNode.classKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.typeParameters, toNode.typeParameters),
_isEqualNodes(node.extendsClause, toNode.extendsClause),
_isEqualNodes(node.withClause, toNode.withClause),
_isEqualNodes(node.implementsClause, toNode.implementsClause),
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.members, toNode.members),
_isEqualTokens(node.rightBracket, toNode.rightBracket));
}
@override
bool visitClassTypeAlias(ClassTypeAlias node) {
ClassTypeAlias toNode = this._toNode as ClassTypeAlias;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.typedefKeyword, toNode.typedefKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.typeParameters, toNode.typeParameters),
_isEqualTokens(node.equals, toNode.equals),
_isEqualTokens(node.abstractKeyword, toNode.abstractKeyword),
_isEqualNodes(node.superclass, toNode.superclass),
_isEqualNodes(node.withClause, toNode.withClause),
_isEqualNodes(node.implementsClause, toNode.implementsClause),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitComment(Comment node) {
Comment toNode = this._toNode as Comment;
return _isEqualNodeLists(node.references, toNode.references);
}
@override
bool visitCommentReference(CommentReference node) {
CommentReference toNode = this._toNode as CommentReference;
return _and(_isEqualTokens(node.newKeyword, toNode.newKeyword),
_isEqualNodes(node.identifier, toNode.identifier));
}
@override
bool visitCompilationUnit(CompilationUnit node) {
CompilationUnit toNode = this._toNode as CompilationUnit;
if (_and(
_isEqualTokens(node.beginToken, toNode.beginToken),
_isEqualNodes(node.scriptTag, toNode.scriptTag),
_isEqualNodeLists(node.directives, toNode.directives),
_isEqualNodeLists(node.declarations, toNode.declarations),
_isEqualTokens(node.endToken, toNode.endToken))) {
toNode.element = node.declaredElement;
return true;
}
return false;
}
@override
bool visitConditionalExpression(ConditionalExpression node) {
ConditionalExpression toNode = this._toNode as ConditionalExpression;
if (_and(
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.question, toNode.question),
_isEqualNodes(node.thenExpression, toNode.thenExpression),
_isEqualTokens(node.colon, toNode.colon),
_isEqualNodes(node.elseExpression, toNode.elseExpression))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitConfiguration(Configuration node) {
Configuration toNode = this._toNode as Configuration;
if (_and(
_isEqualTokens(node.ifKeyword, toNode.ifKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.name, toNode.name),
_isEqualTokens(node.equalToken, toNode.equalToken),
_isEqualNodes(node.value, toNode.value),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualNodes(node.uri, toNode.uri))) {
return true;
}
return false;
}
@override
bool visitConstructorDeclaration(ConstructorDeclaration node) {
ConstructorDeclarationImpl toNode = this._toNode as ConstructorDeclaration;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.externalKeyword, toNode.externalKeyword),
_isEqualTokens(node.constKeyword, toNode.constKeyword),
_isEqualTokens(node.factoryKeyword, toNode.factoryKeyword),
_isEqualNodes(node.returnType, toNode.returnType),
_isEqualTokens(node.period, toNode.period),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.parameters, toNode.parameters),
_isEqualTokens(node.separator, toNode.separator),
_isEqualNodeLists(node.initializers, toNode.initializers),
_isEqualNodes(node.redirectedConstructor, toNode.redirectedConstructor),
_isEqualNodes(node.body, toNode.body))) {
toNode.declaredElement = node.declaredElement;
return true;
}
return false;
}
@override
bool visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
ConstructorFieldInitializer toNode =
this._toNode as ConstructorFieldInitializer;
return _and(
_isEqualTokens(node.thisKeyword, toNode.thisKeyword),
_isEqualTokens(node.period, toNode.period),
_isEqualNodes(node.fieldName, toNode.fieldName),
_isEqualTokens(node.equals, toNode.equals),
_isEqualNodes(node.expression, toNode.expression));
}
@override
bool visitConstructorName(ConstructorName node) {
ConstructorName toNode = this._toNode as ConstructorName;
if (_and(
_isEqualNodes(node.type, toNode.type),
_isEqualTokens(node.period, toNode.period),
_isEqualNodes(node.name, toNode.name))) {
toNode.staticElement = node.staticElement;
return true;
}
return false;
}
@override
bool visitContinueStatement(ContinueStatement node) {
ContinueStatement toNode = this._toNode as ContinueStatement;
if (_and(
_isEqualTokens(node.continueKeyword, toNode.continueKeyword),
_isEqualNodes(node.label, toNode.label),
_isEqualTokens(node.semicolon, toNode.semicolon))) {
// TODO(paulberry): map node.target to toNode.target.
return true;
}
return false;
}
@override
bool visitDeclaredIdentifier(DeclaredIdentifier node) {
DeclaredIdentifier toNode = this._toNode as DeclaredIdentifier;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodes(node.type, toNode.type),
_isEqualNodes(node.identifier, toNode.identifier));
}
@override
bool visitDefaultFormalParameter(DefaultFormalParameter node) {
DefaultFormalParameter toNode = this._toNode as DefaultFormalParameter;
return _and(
_isEqualNodes(node.parameter, toNode.parameter),
// ignore: deprecated_member_use_from_same_package
node.kind == toNode.kind,
_isEqualTokens(node.separator, toNode.separator),
_isEqualNodes(node.defaultValue, toNode.defaultValue));
}
@override
bool visitDoStatement(DoStatement node) {
DoStatement toNode = this._toNode as DoStatement;
return _and(
_isEqualTokens(node.doKeyword, toNode.doKeyword),
_isEqualNodes(node.body, toNode.body),
_isEqualTokens(node.whileKeyword, toNode.whileKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitDottedName(DottedName node) {
DottedName toNode = this._toNode as DottedName;
return _isEqualNodeLists(node.components, toNode.components);
}
@override
bool visitDoubleLiteral(DoubleLiteral node) {
DoubleLiteral toNode = this._toNode as DoubleLiteral;
if (_and(_isEqualTokens(node.literal, toNode.literal),
node.value == toNode.value)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitEmptyFunctionBody(EmptyFunctionBody node) {
EmptyFunctionBody toNode = this._toNode as EmptyFunctionBody;
return _isEqualTokens(node.semicolon, toNode.semicolon);
}
@override
bool visitEmptyStatement(EmptyStatement node) {
EmptyStatement toNode = this._toNode as EmptyStatement;
return _isEqualTokens(node.semicolon, toNode.semicolon);
}
@override
bool visitEnumConstantDeclaration(EnumConstantDeclaration node) {
EnumConstantDeclaration toNode = this._toNode as EnumConstantDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualNodes(node.name, toNode.name));
}
@override
bool visitEnumDeclaration(EnumDeclaration node) {
EnumDeclaration toNode = this._toNode as EnumDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.enumKeyword, toNode.enumKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.constants, toNode.constants),
_isEqualTokens(node.rightBracket, toNode.rightBracket));
}
@override
bool visitExportDirective(ExportDirective node) {
ExportDirective toNode = this._toNode as ExportDirective;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodes(node.uri, toNode.uri),
_isEqualNodeLists(node.combinators, toNode.combinators),
_isEqualTokens(node.semicolon, toNode.semicolon))) {
toNode.element = node.element;
return true;
}
return false;
}
@override
bool visitExpressionFunctionBody(ExpressionFunctionBody node) {
ExpressionFunctionBody toNode = this._toNode as ExpressionFunctionBody;
return _and(
_isEqualTokens(node.functionDefinition, toNode.functionDefinition),
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitExpressionStatement(ExpressionStatement node) {
ExpressionStatement toNode = this._toNode as ExpressionStatement;
return _and(_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitExtendsClause(ExtendsClause node) {
ExtendsClause toNode = this._toNode as ExtendsClause;
return _and(_isEqualTokens(node.extendsKeyword, toNode.extendsKeyword),
_isEqualNodes(node.superclass, toNode.superclass));
}
@override
bool visitExtensionDeclaration(ExtensionDeclaration node) {
ExtensionDeclaration toNode = this._toNode as ExtensionDeclaration;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.extensionKeyword, toNode.extensionKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.typeParameters, toNode.typeParameters),
_isEqualTokens(node.onKeyword, toNode.onKeyword),
_isEqualNodes(node.extendedType, toNode.extendedType),
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.members, toNode.members),
_isEqualTokens(node.rightBracket, toNode.rightBracket))) {
return true;
}
return false;
}
@override
bool visitExtensionOverride(ExtensionOverride node) {
ExtensionOverride toNode = this._toNode as ExtensionOverride;
return _and(
_isEqualNodes(node.extensionName, toNode.extensionName),
_isEqualNodes(node.typeArguments, toNode.typeArguments),
_isEqualNodes(node.argumentList, toNode.argumentList));
}
@override
bool visitFieldDeclaration(FieldDeclaration node) {
FieldDeclaration toNode = this._toNode as FieldDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.staticKeyword, toNode.staticKeyword),
_isEqualNodes(node.fields, toNode.fields),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitFieldFormalParameter(FieldFormalParameter node) {
FieldFormalParameter toNode = this._toNode as FieldFormalParameter;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodes(node.type, toNode.type),
_isEqualTokens(node.thisKeyword, toNode.thisKeyword),
_isEqualTokens(node.period, toNode.period),
_isEqualNodes(node.identifier, toNode.identifier));
}
@override
bool visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) {
ForEachPartsWithDeclaration toNode =
this._toNode as ForEachPartsWithDeclaration;
return _and(
_isEqualNodes(node.loopVariable, toNode.loopVariable),
_isEqualTokens(node.inKeyword, toNode.inKeyword),
_isEqualNodes(node.iterable, toNode.iterable));
}
@override
bool visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) {
ForEachPartsWithIdentifier toNode =
this._toNode as ForEachPartsWithIdentifier;
return _and(
_isEqualNodes(node.identifier, toNode.identifier),
_isEqualTokens(node.inKeyword, toNode.inKeyword),
_isEqualNodes(node.iterable, toNode.iterable));
}
@override
bool visitForElement(ForElement node) {
ForElement toNode = this._toNode as ForElement;
return _and(
_isEqualTokens(node.awaitKeyword, toNode.awaitKeyword),
_isEqualTokens(node.forKeyword, toNode.forKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.forLoopParts, toNode.forLoopParts),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualNodes(node.body, toNode.body));
}
@override
bool visitFormalParameterList(FormalParameterList node) {
FormalParameterList toNode = this._toNode as FormalParameterList;
return _and(
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodeLists(node.parameters, toNode.parameters),
_isEqualTokens(node.leftDelimiter, toNode.leftDelimiter),
_isEqualTokens(node.rightDelimiter, toNode.rightDelimiter),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis));
}
@override
bool visitForPartsWithDeclarations(ForPartsWithDeclarations node) {
ForPartsWithDeclarations toNode = this._toNode as ForPartsWithDeclarations;
return _and(
_isEqualNodes(node.variables, toNode.variables),
_isEqualTokens(node.leftSeparator, toNode.leftSeparator),
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.rightSeparator, toNode.rightSeparator),
_isEqualNodeLists(node.updaters, toNode.updaters));
}
@override
bool visitForPartsWithExpression(ForPartsWithExpression node) {
ForPartsWithExpression toNode = this._toNode as ForPartsWithExpression;
return _and(
_isEqualNodes(node.initialization, toNode.initialization),
_isEqualTokens(node.leftSeparator, toNode.leftSeparator),
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.rightSeparator, toNode.rightSeparator),
_isEqualNodeLists(node.updaters, toNode.updaters));
}
@override
bool visitForStatement(ForStatement node) {
ForStatement toNode = this._toNode as ForStatement;
return _and(
_isEqualTokens(node.awaitKeyword, toNode.awaitKeyword),
_isEqualTokens(node.forKeyword, toNode.forKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.forLoopParts, toNode.forLoopParts),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualNodes(node.body, toNode.body));
}
@override
bool visitFunctionDeclaration(FunctionDeclaration node) {
FunctionDeclaration toNode = this._toNode as FunctionDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.externalKeyword, toNode.externalKeyword),
_isEqualNodes(node.returnType, toNode.returnType),
_isEqualTokens(node.propertyKeyword, toNode.propertyKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.functionExpression, toNode.functionExpression));
}
@override
bool visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
FunctionDeclarationStatement toNode =
this._toNode as FunctionDeclarationStatement;
return _isEqualNodes(node.functionDeclaration, toNode.functionDeclaration);
}
@override
bool visitFunctionExpression(FunctionExpression node) {
FunctionExpressionImpl toNode = this._toNode as FunctionExpression;
if (_and(_isEqualNodes(node.parameters, toNode.parameters),
_isEqualNodes(node.body, toNode.body))) {
toNode.declaredElement = node.declaredElement;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
FunctionExpressionInvocation toNode =
this._toNode as FunctionExpressionInvocation;
if (_and(
_isEqualNodes(node.function, toNode.function),
_isEqualNodes(node.typeArguments, toNode.typeArguments),
_isEqualNodes(node.argumentList, toNode.argumentList))) {
toNode.staticInvokeType = node.staticInvokeType;
toNode.staticElement = node.staticElement;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitFunctionTypeAlias(FunctionTypeAlias node) {
FunctionTypeAlias toNode = this._toNode as FunctionTypeAlias;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.typedefKeyword, toNode.typedefKeyword),
_isEqualNodes(node.returnType, toNode.returnType),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.typeParameters, toNode.typeParameters),
_isEqualNodes(node.parameters, toNode.parameters),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
FunctionTypedFormalParameter toNode =
this._toNode as FunctionTypedFormalParameter;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualNodes(node.returnType, toNode.returnType),
_isEqualNodes(node.identifier, toNode.identifier),
_isEqualNodes(node.parameters, toNode.parameters));
}
@override
bool visitGenericFunctionType(GenericFunctionType node) {
GenericFunctionTypeImpl toNode = this._toNode as GenericFunctionTypeImpl;
if (_and(
_isEqualNodes(node.returnType, toNode.returnType),
_isEqualTokens(node.functionKeyword, toNode.functionKeyword),
_isEqualNodes(node.typeParameters, toNode.typeParameters),
_isEqualNodes(node.parameters, toNode.parameters),
_isEqualTokens(node.question, toNode.question))) {
toNode.type = node.type;
return true;
}
return false;
}
@override
bool visitGenericTypeAlias(GenericTypeAlias node) {
GenericTypeAliasImpl toNode = this._toNode as GenericTypeAliasImpl;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.typedefKeyword, toNode.typedefKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.typeParameters, toNode.typeParameters),
_isEqualTokens(node.equals, toNode.equals),
_isEqualNodes(node.functionType, toNode.functionType),
_isEqualTokens(node.semicolon, toNode.semicolon))) {
return true;
}
return false;
}
@override
bool visitHideCombinator(HideCombinator node) {
HideCombinator toNode = this._toNode as HideCombinator;
return _and(_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodeLists(node.hiddenNames, toNode.hiddenNames));
}
@override
bool visitIfElement(IfElement node) {
IfElement toNode = this._toNode as IfElement;
return _and(
_isEqualTokens(node.ifKeyword, toNode.ifKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualNodes(node.thenElement, toNode.thenElement),
_isEqualTokens(node.elseKeyword, toNode.elseKeyword),
_isEqualNodes(node.elseElement, toNode.elseElement));
}
@override
bool visitIfStatement(IfStatement node) {
IfStatement toNode = this._toNode as IfStatement;
return _and(
_isEqualTokens(node.ifKeyword, toNode.ifKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualNodes(node.thenStatement, toNode.thenStatement),
_isEqualTokens(node.elseKeyword, toNode.elseKeyword),
_isEqualNodes(node.elseStatement, toNode.elseStatement));
}
@override
bool visitImplementsClause(ImplementsClause node) {
ImplementsClause toNode = this._toNode as ImplementsClause;
return _and(
_isEqualTokens(node.implementsKeyword, toNode.implementsKeyword),
_isEqualNodeLists(node.interfaces, toNode.interfaces));
}
@override
bool visitImportDirective(ImportDirective node) {
ImportDirective toNode = this._toNode as ImportDirective;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodes(node.uri, toNode.uri),
_isEqualTokens(node.asKeyword, toNode.asKeyword),
_isEqualNodes(node.prefix, toNode.prefix),
_isEqualNodeLists(node.combinators, toNode.combinators),
_isEqualTokens(node.semicolon, toNode.semicolon))) {
toNode.element = node.element;
return true;
}
return false;
}
@override
bool visitIndexExpression(IndexExpression node) {
IndexExpression toNode = this._toNode as IndexExpression;
if (_and(
_isEqualNodes(node.target, toNode.target),
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodes(node.index, toNode.index),
_isEqualTokens(node.rightBracket, toNode.rightBracket))) {
toNode.auxiliaryElements = node.auxiliaryElements;
toNode.staticElement = node.staticElement;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitInstanceCreationExpression(InstanceCreationExpression node) {
InstanceCreationExpression toNode =
this._toNode as InstanceCreationExpression;
if (_and(
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodes(node.constructorName, toNode.constructorName),
_isEqualNodes(node.argumentList, toNode.argumentList))) {
toNode.staticElement = node.staticElement;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitIntegerLiteral(IntegerLiteral node) {
IntegerLiteral toNode = this._toNode as IntegerLiteral;
if (_and(_isEqualTokens(node.literal, toNode.literal),
node.value == toNode.value)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitInterpolationExpression(InterpolationExpression node) {
InterpolationExpression toNode = this._toNode as InterpolationExpression;
return _and(
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.rightBracket, toNode.rightBracket));
}
@override
bool visitInterpolationString(InterpolationString node) {
InterpolationString toNode = this._toNode as InterpolationString;
return _and(_isEqualTokens(node.contents, toNode.contents),
node.value == toNode.value);
}
@override
bool visitIsExpression(IsExpression node) {
IsExpression toNode = this._toNode as IsExpression;
if (_and(
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.isOperator, toNode.isOperator),
_isEqualTokens(node.notOperator, toNode.notOperator),
_isEqualNodes(node.type, toNode.type))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitLabel(Label node) {
Label toNode = this._toNode as Label;
return _and(_isEqualNodes(node.label, toNode.label),
_isEqualTokens(node.colon, toNode.colon));
}
@override
bool visitLabeledStatement(LabeledStatement node) {
LabeledStatement toNode = this._toNode as LabeledStatement;
return _and(_isEqualNodeLists(node.labels, toNode.labels),
_isEqualNodes(node.statement, toNode.statement));
}
@override
bool visitLibraryDirective(LibraryDirective node) {
LibraryDirective toNode = this._toNode as LibraryDirective;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.libraryKeyword, toNode.libraryKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualTokens(node.semicolon, toNode.semicolon))) {
toNode.element = node.element;
return true;
}
return false;
}
@override
bool visitLibraryIdentifier(LibraryIdentifier node) {
LibraryIdentifier toNode = this._toNode as LibraryIdentifier;
if (_isEqualNodeLists(node.components, toNode.components)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitListLiteral(ListLiteral node) {
ListLiteral toNode = this._toNode as ListLiteral;
if (_and(
_isEqualTokens(node.constKeyword, toNode.constKeyword),
_isEqualNodes(node.typeArguments, toNode.typeArguments),
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.elements, toNode.elements),
_isEqualTokens(node.rightBracket, toNode.rightBracket))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitMapLiteralEntry(MapLiteralEntry node) {
MapLiteralEntry toNode = this._toNode as MapLiteralEntry;
return _and(
_isEqualNodes(node.key, toNode.key),
_isEqualTokens(node.separator, toNode.separator),
_isEqualNodes(node.value, toNode.value));
}
@override
bool visitMethodDeclaration(MethodDeclaration node) {
MethodDeclaration toNode = this._toNode as MethodDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.externalKeyword, toNode.externalKeyword),
_isEqualTokens(node.modifierKeyword, toNode.modifierKeyword),
_isEqualNodes(node.returnType, toNode.returnType),
_isEqualTokens(node.propertyKeyword, toNode.propertyKeyword),
_isEqualTokens(node.propertyKeyword, toNode.propertyKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.parameters, toNode.parameters),
_isEqualNodes(node.body, toNode.body));
}
@override
bool visitMethodInvocation(MethodInvocation node) {
MethodInvocation toNode = this._toNode as MethodInvocation;
if (_and(
_isEqualNodes(node.target, toNode.target),
_isEqualTokens(node.operator, toNode.operator),
_isEqualNodes(node.typeArguments, toNode.typeArguments),
_isEqualNodes(node.methodName, toNode.methodName),
_isEqualNodes(node.argumentList, toNode.argumentList))) {
toNode.staticInvokeType = node.staticInvokeType;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitMixinDeclaration(MixinDeclaration node) {
MixinDeclaration toNode = this._toNode as MixinDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.mixinKeyword, toNode.mixinKeyword),
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.typeParameters, toNode.typeParameters),
_isEqualNodes(node.onClause, toNode.onClause),
_isEqualNodes(node.implementsClause, toNode.implementsClause),
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.members, toNode.members),
_isEqualTokens(node.rightBracket, toNode.rightBracket));
}
@override
bool visitNamedExpression(NamedExpression node) {
NamedExpression toNode = this._toNode as NamedExpression;
if (_and(_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.expression, toNode.expression))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitNativeClause(NativeClause node) {
NativeClause toNode = this._toNode as NativeClause;
return _and(_isEqualTokens(node.nativeKeyword, toNode.nativeKeyword),
_isEqualNodes(node.name, toNode.name));
}
@override
bool visitNativeFunctionBody(NativeFunctionBody node) {
NativeFunctionBody toNode = this._toNode as NativeFunctionBody;
return _and(
_isEqualTokens(node.nativeKeyword, toNode.nativeKeyword),
_isEqualNodes(node.stringLiteral, toNode.stringLiteral),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitNullLiteral(NullLiteral node) {
NullLiteral toNode = this._toNode as NullLiteral;
if (_isEqualTokens(node.literal, toNode.literal)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitOnClause(OnClause node) {
OnClause toNode = this._toNode as OnClause;
return _and(
_isEqualTokens(node.onKeyword, toNode.onKeyword),
_isEqualNodeLists(
node.superclassConstraints, toNode.superclassConstraints));
}
@override
bool visitParenthesizedExpression(ParenthesizedExpression node) {
ParenthesizedExpression toNode = this._toNode as ParenthesizedExpression;
if (_and(
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitPartDirective(PartDirective node) {
PartDirective toNode = this._toNode as PartDirective;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.partKeyword, toNode.partKeyword),
_isEqualNodes(node.uri, toNode.uri),
_isEqualTokens(node.semicolon, toNode.semicolon))) {
toNode.element = node.element;
return true;
}
return false;
}
@override
bool visitPartOfDirective(PartOfDirective node) {
PartOfDirective toNode = this._toNode as PartOfDirective;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.partKeyword, toNode.partKeyword),
_isEqualTokens(node.ofKeyword, toNode.ofKeyword),
_isEqualNodes(node.libraryName, toNode.libraryName),
_isEqualTokens(node.semicolon, toNode.semicolon))) {
toNode.element = node.element;
return true;
}
return false;
}
@override
bool visitPostfixExpression(PostfixExpression node) {
PostfixExpression toNode = this._toNode as PostfixExpression;
if (_and(_isEqualNodes(node.operand, toNode.operand),
_isEqualTokens(node.operator, toNode.operator))) {
toNode.staticElement = node.staticElement;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitPrefixedIdentifier(PrefixedIdentifier node) {
PrefixedIdentifier toNode = this._toNode as PrefixedIdentifier;
if (_and(
_isEqualNodes(node.prefix, toNode.prefix),
_isEqualTokens(node.period, toNode.period),
_isEqualNodes(node.identifier, toNode.identifier))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitPrefixExpression(PrefixExpression node) {
PrefixExpression toNode = this._toNode as PrefixExpression;
if (_and(_isEqualTokens(node.operator, toNode.operator),
_isEqualNodes(node.operand, toNode.operand))) {
toNode.staticElement = node.staticElement;
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitPropertyAccess(PropertyAccess node) {
PropertyAccess toNode = this._toNode as PropertyAccess;
if (_and(
_isEqualNodes(node.target, toNode.target),
_isEqualTokens(node.operator, toNode.operator),
_isEqualNodes(node.propertyName, toNode.propertyName))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
RedirectingConstructorInvocation toNode =
this._toNode as RedirectingConstructorInvocation;
if (_and(
_isEqualTokens(node.thisKeyword, toNode.thisKeyword),
_isEqualTokens(node.period, toNode.period),
_isEqualNodes(node.constructorName, toNode.constructorName),
_isEqualNodes(node.argumentList, toNode.argumentList))) {
toNode.staticElement = node.staticElement;
return true;
}
return false;
}
@override
bool visitRethrowExpression(RethrowExpression node) {
RethrowExpression toNode = this._toNode as RethrowExpression;
if (_isEqualTokens(node.rethrowKeyword, toNode.rethrowKeyword)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitReturnStatement(ReturnStatement node) {
ReturnStatement toNode = this._toNode as ReturnStatement;
return _and(
_isEqualTokens(node.returnKeyword, toNode.returnKeyword),
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitScriptTag(ScriptTag node) {
ScriptTag toNode = this._toNode as ScriptTag;
return _isEqualTokens(node.scriptTag, toNode.scriptTag);
}
@override
bool visitSetOrMapLiteral(SetOrMapLiteral node) {
SetOrMapLiteral toNode = this._toNode as SetOrMapLiteral;
if (_and(
_isEqualTokens(node.constKeyword, toNode.constKeyword),
_isEqualNodes(node.typeArguments, toNode.typeArguments),
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.elements, toNode.elements),
_isEqualTokens(node.rightBracket, toNode.rightBracket))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitShowCombinator(ShowCombinator node) {
ShowCombinator toNode = this._toNode as ShowCombinator;
return _and(_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodeLists(node.shownNames, toNode.shownNames));
}
@override
bool visitSimpleFormalParameter(SimpleFormalParameter node) {
SimpleFormalParameter toNode = this._toNode as SimpleFormalParameter;
if (_and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodes(node.type, toNode.type),
_isEqualNodes(node.identifier, toNode.identifier))) {
(toNode as SimpleFormalParameterImpl).declaredElement =
node.declaredElement;
return true;
}
return false;
}
@override
bool visitSimpleIdentifier(SimpleIdentifier node) {
SimpleIdentifier toNode = this._toNode as SimpleIdentifier;
if (_isEqualTokens(node.token, toNode.token)) {
toNode.staticElement = node.staticElement;
toNode.staticType = node.staticType;
toNode.auxiliaryElements = node.auxiliaryElements;
(toNode as SimpleIdentifierImpl).tearOffTypeArgumentTypes =
node.tearOffTypeArgumentTypes;
return true;
}
return false;
}
@override
bool visitSimpleStringLiteral(SimpleStringLiteral node) {
SimpleStringLiteral toNode = this._toNode as SimpleStringLiteral;
if (_and(_isEqualTokens(node.literal, toNode.literal),
node.value == toNode.value)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitSpreadElement(SpreadElement node) {
SpreadElement toNode = this._toNode as SpreadElement;
return _and(_isEqualTokens(node.spreadOperator, toNode.spreadOperator),
_isEqualNodes(node.expression, toNode.expression));
}
@override
bool visitStringInterpolation(StringInterpolation node) {
StringInterpolation toNode = this._toNode as StringInterpolation;
if (_isEqualNodeLists(node.elements, toNode.elements)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitSuperConstructorInvocation(SuperConstructorInvocation node) {
SuperConstructorInvocation toNode =
this._toNode as SuperConstructorInvocation;
if (_and(
_isEqualTokens(node.superKeyword, toNode.superKeyword),
_isEqualTokens(node.period, toNode.period),
_isEqualNodes(node.constructorName, toNode.constructorName),
_isEqualNodes(node.argumentList, toNode.argumentList))) {
toNode.staticElement = node.staticElement;
return true;
}
return false;
}
@override
bool visitSuperExpression(SuperExpression node) {
SuperExpression toNode = this._toNode as SuperExpression;
if (_isEqualTokens(node.superKeyword, toNode.superKeyword)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitSwitchCase(SwitchCase node) {
SwitchCase toNode = this._toNode as SwitchCase;
return _and(
_isEqualNodeLists(node.labels, toNode.labels),
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.colon, toNode.colon),
_isEqualNodeLists(node.statements, toNode.statements));
}
@override
bool visitSwitchDefault(SwitchDefault node) {
SwitchDefault toNode = this._toNode as SwitchDefault;
return _and(
_isEqualNodeLists(node.labels, toNode.labels),
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualTokens(node.colon, toNode.colon),
_isEqualNodeLists(node.statements, toNode.statements));
}
@override
bool visitSwitchStatement(SwitchStatement node) {
SwitchStatement toNode = this._toNode as SwitchStatement;
return _and(
_isEqualTokens(node.switchKeyword, toNode.switchKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.members, toNode.members),
_isEqualTokens(node.rightBracket, toNode.rightBracket));
}
@override
bool visitSymbolLiteral(SymbolLiteral node) {
SymbolLiteral toNode = this._toNode as SymbolLiteral;
if (_and(_isEqualTokens(node.poundSign, toNode.poundSign),
_isEqualTokenLists(node.components, toNode.components))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitThisExpression(ThisExpression node) {
ThisExpression toNode = this._toNode as ThisExpression;
if (_isEqualTokens(node.thisKeyword, toNode.thisKeyword)) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitThrowExpression(ThrowExpression node) {
ThrowExpression toNode = this._toNode as ThrowExpression;
if (_and(_isEqualTokens(node.throwKeyword, toNode.throwKeyword),
_isEqualNodes(node.expression, toNode.expression))) {
toNode.staticType = node.staticType;
return true;
}
return false;
}
@override
bool visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
TopLevelVariableDeclaration toNode =
this._toNode as TopLevelVariableDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualNodes(node.variables, toNode.variables),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitTryStatement(TryStatement node) {
TryStatement toNode = this._toNode as TryStatement;
return _and(
_isEqualTokens(node.tryKeyword, toNode.tryKeyword),
_isEqualNodes(node.body, toNode.body),
_isEqualNodeLists(node.catchClauses, toNode.catchClauses),
_isEqualTokens(node.finallyKeyword, toNode.finallyKeyword),
_isEqualNodes(node.finallyBlock, toNode.finallyBlock));
}
@override
bool visitTypeArgumentList(TypeArgumentList node) {
TypeArgumentList toNode = this._toNode as TypeArgumentList;
return _and(
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.arguments, toNode.arguments),
_isEqualTokens(node.rightBracket, toNode.rightBracket));
}
@override
bool visitTypeName(TypeName node) {
TypeName toNode = this._toNode as TypeName;
if (_and(
_isEqualNodes(node.name, toNode.name),
_isEqualNodes(node.typeArguments, toNode.typeArguments),
_isEqualTokens(node.question, toNode.question))) {
toNode.type = node.type;
return true;
}
return false;
}
@override
bool visitTypeParameter(TypeParameter node) {
TypeParameter toNode = this._toNode as TypeParameter;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualNodes(node.name, toNode.name),
_isEqualTokens(node.extendsKeyword, toNode.extendsKeyword),
_isEqualNodes(node.bound, toNode.bound));
}
@override
bool visitTypeParameterList(TypeParameterList node) {
TypeParameterList toNode = this._toNode as TypeParameterList;
return _and(
_isEqualTokens(node.leftBracket, toNode.leftBracket),
_isEqualNodeLists(node.typeParameters, toNode.typeParameters),
_isEqualTokens(node.rightBracket, toNode.rightBracket));
}
@override
bool visitVariableDeclaration(VariableDeclaration node) {
VariableDeclaration toNode = this._toNode as VariableDeclaration;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualNodes(node.name, toNode.name),
_isEqualTokens(node.equals, toNode.equals),
_isEqualNodes(node.initializer, toNode.initializer));
}
@override
bool visitVariableDeclarationList(VariableDeclarationList node) {
VariableDeclarationList toNode = this._toNode as VariableDeclarationList;
return _and(
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.keyword, toNode.keyword),
_isEqualNodes(node.type, toNode.type),
_isEqualNodeLists(node.variables, toNode.variables));
}
@override
bool visitVariableDeclarationStatement(VariableDeclarationStatement node) {
VariableDeclarationStatement toNode =
this._toNode as VariableDeclarationStatement;
return _and(_isEqualNodes(node.variables, toNode.variables),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
@override
bool visitWhileStatement(WhileStatement node) {
WhileStatement toNode = this._toNode as WhileStatement;
return _and(
_isEqualTokens(node.whileKeyword, toNode.whileKeyword),
_isEqualTokens(node.leftParenthesis, toNode.leftParenthesis),
_isEqualNodes(node.condition, toNode.condition),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
_isEqualNodes(node.body, toNode.body));
}
@override
bool visitWithClause(WithClause node) {
WithClause toNode = this._toNode as WithClause;
return _and(_isEqualTokens(node.withKeyword, toNode.withKeyword),
_isEqualNodeLists(node.mixinTypes, toNode.mixinTypes));
}
@override
bool visitYieldStatement(YieldStatement node) {
YieldStatement toNode = this._toNode as YieldStatement;
return _and(
_isEqualTokens(node.yieldKeyword, toNode.yieldKeyword),
_isEqualNodes(node.expression, toNode.expression),
_isEqualTokens(node.semicolon, toNode.semicolon));
}
/**
* Return `true` if all of the parameters are `true`.
*/
bool _and(bool b1, bool b2,
[bool b3 = true,
bool b4 = true,
bool b5 = true,
bool b6 = true,
bool b7 = true,
bool b8 = true,
bool b9 = true,
bool b10 = true,
bool b11 = true,
bool b12 = true,
bool b13 = true]) {
// TODO(brianwilkerson) Inline this method.
return b1 &&
b2 &&
b3 &&
b4 &&
b5 &&
b6 &&
b7 &&
b8 &&
b9 &&
b10 &&
b11 &&
b12 &&
b13;
}
/**
* Return `true` if the [first] and [second] lists of AST nodes have the same
* size and corresponding elements are equal.
*/
bool _isEqualNodeLists(NodeList first, NodeList second) {
if (first == null) {
return second == null;
} else if (second == null) {
return false;
}
int size = first.length;
if (second.length != size) {
return false;
}
bool equal = true;
for (int i = 0; i < size; i++) {
if (!_isEqualNodes(first[i], second[i])) {
equal = false;
}
}
return equal;
}
/**
* Return `true` if the [fromNode] and [toNode] have the same structure. As a
* side-effect, if the nodes do have the same structure, any resolution data
* from the first node will be copied to the second node.
*/
bool _isEqualNodes(AstNode fromNode, AstNode toNode) {
if (fromNode == null) {
return toNode == null;
} else if (toNode == null) {
return false;
} else if (fromNode.runtimeType == toNode.runtimeType) {
this._toNode = toNode;
return fromNode.accept(this);
}
//
// Check for a simple transformation caused by entering a period.
//
if (toNode is PrefixedIdentifier) {
SimpleIdentifier prefix = toNode.prefix;
if (fromNode.runtimeType == prefix.runtimeType) {
this._toNode = prefix;
return fromNode.accept(this);
}
} else if (toNode is PropertyAccess) {
Expression target = toNode.target;
if (fromNode.runtimeType == target.runtimeType) {
this._toNode = target;
return fromNode.accept(this);
}
}
return false;
}
/**
* Return `true` if the [first] and [second] arrays of tokens have the same
* length and corresponding elements are equal.
*/
bool _isEqualTokenLists(List<Token> first, List<Token> second) {
int length = first.length;
if (second.length != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (!_isEqualTokens(first[i], second[i])) {
return false;
}
}
return true;
}
/**
* Return `true` if the [first] and [second] tokens have the same structure.
*/
bool _isEqualTokens(Token first, Token second) {
if (first == null) {
return second == null;
} else if (second == null) {
return false;
}
return first.lexeme == second.lexeme;
}
/**
* Copy resolution data from the [fromNode] to the [toNode].
*/
static void copyResolutionData(AstNode fromNode, AstNode toNode) {
ResolutionCopier copier = new ResolutionCopier();
copier._isEqualNodes(fromNode, toNode);
}
}
/**
* Traverse the AST from initial child node to successive parents, building a
* collection of local variable and parameter names visible to the initial child
* node. In case of name shadowing, the first name seen is the most specific one
* so names are not redefined.
*
* Completion test code coverage is 95%. The two basic blocks that are not
* executed cannot be executed. They are included for future reference.
*/
class ScopedNameFinder extends GeneralizingAstVisitor<void> {
Declaration _declarationNode;
AstNode _immediateChild;
Map<String, SimpleIdentifier> _locals =
new HashMap<String, SimpleIdentifier>();
final int _position;
bool _referenceIsWithinLocalFunction = false;
ScopedNameFinder(this._position);
Declaration get declaration => _declarationNode;
Map<String, SimpleIdentifier> get locals => _locals;
@override
void visitBlock(Block node) {
_checkStatements(node.statements);
super.visitBlock(node);
}
@override
void visitCatchClause(CatchClause node) {
_addToScope(node.exceptionParameter);
_addToScope(node.stackTraceParameter);
super.visitCatchClause(node);
}
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
if (!identical(_immediateChild, node.parameters)) {
_addParameters(node.parameters.parameters);
}
_declarationNode = node;
}
@override
void visitFieldDeclaration(FieldDeclaration node) {
_declarationNode = node;
}
@override
void visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) {
_addToScope(node.loopVariable.identifier);
super.visitForEachPartsWithDeclaration(node);
}
@override
void visitForPartsWithDeclarations(ForPartsWithDeclarations node) {
_addVariables(node.variables.variables);
super.visitForPartsWithDeclarations(node);
}
@override
void visitFunctionDeclaration(FunctionDeclaration node) {
if (node.parent is! FunctionDeclarationStatement) {
_declarationNode = node;
} else {
super.visitFunctionDeclaration(node);
}
}
@override
void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
_referenceIsWithinLocalFunction = true;
super.visitFunctionDeclarationStatement(node);
}
@override
void visitFunctionExpression(FunctionExpression node) {
if (node.parameters != null &&
!identical(_immediateChild, node.parameters)) {
_addParameters(node.parameters.parameters);
}
super.visitFunctionExpression(node);
}
@override
void visitMethodDeclaration(MethodDeclaration node) {
_declarationNode = node;
if (node.parameters != null &&
!identical(_immediateChild, node.parameters)) {
_addParameters(node.parameters.parameters);
}
}
@override
void visitNode(AstNode node) {
_immediateChild = node;
AstNode parent = node.parent;
if (parent != null) {
parent.accept(this);
}
}
@override
void visitSwitchMember(SwitchMember node) {
_checkStatements(node.statements);
super.visitSwitchMember(node);
}
@override
void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
_declarationNode = node;
}
@override
void visitTypeAlias(TypeAlias node) {
_declarationNode = node;
}
void _addParameters(NodeList<FormalParameter> vars) {
for (FormalParameter var2 in vars) {
_addToScope(var2.identifier);
}
}
void _addToScope(SimpleIdentifier identifier) {
if (identifier != null && _isInRange(identifier)) {
String name = identifier.name;
if (!_locals.containsKey(name)) {
_locals[name] = identifier;
}
}
}
void _addVariables(NodeList<VariableDeclaration> variables) {
for (VariableDeclaration variable in variables) {
_addToScope(variable.name);
}
}
/**
* Check the given list of [statements] for any that come before the immediate
* child and that define a name that would be visible to the immediate child.
*/
void _checkStatements(List<Statement> statements) {
for (Statement statement in statements) {
if (identical(statement, _immediateChild)) {
return;
}
if (statement is VariableDeclarationStatement) {
_addVariables(statement.variables.variables);
} else if (statement is FunctionDeclarationStatement &&
!_referenceIsWithinLocalFunction) {
_addToScope(statement.functionDeclaration.name);
}
}
}
bool _isInRange(AstNode node) {
if (_position < 0) {
// if source position is not set then all nodes are in range
return true;
// not reached
}
return node.end < _position;
}
}
/**
* A visitor used to write a source representation of a visited AST node (and
* all of it's children) to a writer.
*
* This class has been deprecated. Use the class ToSourceVisitor2 instead.
*/
@deprecated
class ToSourceVisitor implements AstVisitor<void> {
/**
* The writer to which the source is to be written.
*/
final PrintWriter _writer;
/**
* Initialize a newly created visitor to write source code representing the
* visited nodes to the given [writer].
*/
ToSourceVisitor(this._writer);
@override
void visitAdjacentStrings(AdjacentStrings node) {
_visitNodeListWithSeparator(node.strings, " ");
}
@override
void visitAnnotation(Annotation node) {
_writer.print('@');
_visitNode(node.name);
_visitNodeWithPrefix(".", node.constructorName);
_visitNode(node.arguments);
}
@override
void visitArgumentList(ArgumentList node) {
_writer.print('(');
_visitNodeListWithSeparator(node.arguments, ", ");
_writer.print(')');
}
@override
void visitAsExpression(AsExpression node) {
_visitNode(node.expression);
_writer.print(" as ");
_visitNode(node.type);
}
@override
void visitAssertInitializer(AssertInitializer node) {
_writer.print("assert (");
_visitNode(node.condition);
if (node.message != null) {
_writer.print(', ');
_visitNode(node.message);
}
_writer.print(")");
}
@override
void visitAssertStatement(AssertStatement node) {
_writer.print("assert (");
_visitNode(node.condition);
if (node.message != null) {
_writer.print(', ');
_visitNode(node.message);
}
_writer.print(");");
}
@override
void visitAssignmentExpression(AssignmentExpression node) {
_visitNode(node.leftHandSide);
_writer.print(' ');
_writer.print(node.operator.lexeme);
_writer.print(' ');
_visitNode(node.rightHandSide);
}
@override
void visitAwaitExpression(AwaitExpression node) {
_writer.print("await ");
_visitNode(node.expression);
}
@override
void visitBinaryExpression(BinaryExpression node) {
_visitNode(node.leftOperand);
_writer.print(' ');
_writer.print(node.operator.lexeme);
_writer.print(' ');
_visitNode(node.rightOperand);
}
@override
void visitBlock(Block node) {
_writer.print('{');
_visitNodeListWithSeparator(node.statements, " ");
_writer.print('}');
}
@override
void visitBlockFunctionBody(BlockFunctionBody node) {
Token keyword = node.keyword;
if (keyword != null) {
_writer.print(keyword.lexeme);
if (node.star != null) {
_writer.print('*');
}
_writer.print(' ');
}
_visitNode(node.block);
}
@override
void visitBooleanLiteral(BooleanLiteral node) {
_writer.print(node.literal.lexeme);
}
@override
void visitBreakStatement(BreakStatement node) {
_writer.print("break");
_visitNodeWithPrefix(" ", node.label);
_writer.print(";");
}
@override
void visitCascadeExpression(CascadeExpression node) {
_visitNode(node.target);
_visitNodeList(node.cascadeSections);
}
@override
void visitCatchClause(CatchClause node) {
_visitNodeWithPrefix("on ", node.exceptionType);
if (node.catchKeyword != null) {
if (node.exceptionType != null) {
_writer.print(' ');
}
_writer.print("catch (");
_visitNode(node.exceptionParameter);
_visitNodeWithPrefix(", ", node.stackTraceParameter);
_writer.print(") ");
} else {
_writer.print(" ");
}
_visitNode(node.body);
}
@override
void visitClassDeclaration(ClassDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.abstractKeyword, " ");
_writer.print("class ");
_visitNode(node.name);
_visitNode(node.typeParameters);
_visitNodeWithPrefix(" ", node.extendsClause);
_visitNodeWithPrefix(" ", node.withClause);
_visitNodeWithPrefix(" ", node.implementsClause);
_writer.print(" {");
_visitNodeListWithSeparator(node.members, " ");
_writer.print("}");
}
@override
void visitClassTypeAlias(ClassTypeAlias node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
if (node.abstractKeyword != null) {
_writer.print("abstract ");
}
_writer.print("class ");
_visitNode(node.name);
_visitNode(node.typeParameters);
_writer.print(" = ");
_visitNode(node.superclass);
_visitNodeWithPrefix(" ", node.withClause);
_visitNodeWithPrefix(" ", node.implementsClause);
_writer.print(";");
}
@override
void visitComment(Comment node) {}
@override
void visitCommentReference(CommentReference node) {}
@override
void visitCompilationUnit(CompilationUnit node) {
ScriptTag scriptTag = node.scriptTag;
NodeList<Directive> directives = node.directives;
_visitNode(scriptTag);
String prefix = scriptTag == null ? "" : " ";
_visitNodeListWithSeparatorAndPrefix(prefix, directives, " ");
prefix = scriptTag == null && directives.isEmpty ? "" : " ";
_visitNodeListWithSeparatorAndPrefix(prefix, node.declarations, " ");
}
@override
void visitConditionalExpression(ConditionalExpression node) {
_visitNode(node.condition);
_writer.print(" ? ");
_visitNode(node.thenExpression);
_writer.print(" : ");
_visitNode(node.elseExpression);
}
@override
void visitConfiguration(Configuration node) {
_writer.print('if (');
_visitNode(node.name);
_visitNodeWithPrefix(" == ", node.value);
_writer.print(') ');
_visitNode(node.uri);
}
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.externalKeyword, " ");
_visitTokenWithSuffix(node.constKeyword, " ");
_visitTokenWithSuffix(node.factoryKeyword, " ");
_visitNode(node.returnType);
_visitNodeWithPrefix(".", node.name);
_visitNode(node.parameters);
_visitNodeListWithSeparatorAndPrefix(" : ", node.initializers, ", ");
_visitNodeWithPrefix(" = ", node.redirectedConstructor);
_visitFunctionWithPrefix(" ", node.body);
}
@override
void visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
_visitTokenWithSuffix(node.thisKeyword, ".");
_visitNode(node.fieldName);
_writer.print(" = ");
_visitNode(node.expression);
}
@override
void visitConstructorName(ConstructorName node) {
_visitNode(node.type);
_visitNodeWithPrefix(".", node.name);
}
@override
void visitContinueStatement(ContinueStatement node) {
_writer.print("continue");
_visitNodeWithPrefix(" ", node.label);
_writer.print(";");
}
@override
void visitDeclaredIdentifier(DeclaredIdentifier node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.keyword, " ");
_visitNodeWithSuffix(node.type, " ");
_visitNode(node.identifier);
}
@override
void visitDefaultFormalParameter(DefaultFormalParameter node) {
if (node.isRequiredNamed) {
_writer.print('required ');
}
_visitNode(node.parameter);
if (node.separator != null) {
if (node.separator.lexeme != ":") {
_writer.print(" ");
}
_writer.print(node.separator.lexeme);
_visitNodeWithPrefix(" ", node.defaultValue);
}
}
@override
void visitDoStatement(DoStatement node) {
_writer.print("do ");
_visitNode(node.body);
_writer.print(" while (");
_visitNode(node.condition);
_writer.print(");");
}
@override
void visitDottedName(DottedName node) {
_visitNodeListWithSeparator(node.components, ".");
}
@override
void visitDoubleLiteral(DoubleLiteral node) {
_writer.print(node.literal.lexeme);
}
@override
void visitEmptyFunctionBody(EmptyFunctionBody node) {
_writer.print(';');
}
@override
void visitEmptyStatement(EmptyStatement node) {
_writer.print(';');
}
@override
void visitEnumConstantDeclaration(EnumConstantDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitNode(node.name);
}
@override
void visitEnumDeclaration(EnumDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("enum ");
_visitNode(node.name);
_writer.print(" {");
_visitNodeListWithSeparator(node.constants, ", ");
_writer.print("}");
}
@override
void visitExportDirective(ExportDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("export ");
_visitNode(node.uri);
_visitNodeListWithSeparatorAndPrefix(" ", node.combinators, " ");
_writer.print(';');
}
@override
void visitExpressionFunctionBody(ExpressionFunctionBody node) {
Token keyword = node.keyword;
if (keyword != null) {
_writer.print(keyword.lexeme);
_writer.print(' ');
}
_writer.print('${node.functionDefinition?.lexeme} ');
_visitNode(node.expression);
if (node.semicolon != null) {
_writer.print(';');
}
}
@override
void visitExpressionStatement(ExpressionStatement node) {
_visitNode(node.expression);
_writer.print(';');
}
@override
void visitExtendsClause(ExtendsClause node) {
_writer.print("extends ");
_visitNode(node.superclass);
}
@override
void visitExtensionDeclaration(ExtensionDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
_visitTokenWithSuffix(node.extensionKeyword, ' ');
_visitNode(node.name);
_visitNode(node.typeParameters);
_writer.print(' ');
_visitToken(node.onKeyword);
_writer.print(' ');
_visitNodeWithSuffix(node.extendedType, ' ');
_visitToken(node.leftBracket);
_visitNodeListWithSeparator(node.members, ' ');
_visitToken(node.rightBracket);
}
@override
void visitExtensionOverride(ExtensionOverride node) {
_visitNode(node.extensionName);
_visitNode(node.typeArguments);
_visitNode(node.argumentList);
}
@override
void visitFieldDeclaration(FieldDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.staticKeyword, " ");
_visitNode(node.fields);
_writer.print(";");
}
@override
void visitFieldFormalParameter(FieldFormalParameter node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
_visitTokenWithSuffix(node.covariantKeyword, ' ');
_visitTokenWithSuffix(node.keyword, " ");
_visitNodeWithSuffix(node.type, " ");
_writer.print("this.");
_visitNode(node.identifier);
_visitNode(node.typeParameters);
_visitNode(node.parameters);
}
@override
void visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) {
_visitNode(node.loopVariable);
_writer.print(' in ');
_visitNode(node.iterable);
}
@override
void visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) {
_visitNode(node.identifier);
_writer.print(' in ');
_visitNode(node.iterable);
}
@override
void visitForElement(ForElement node) {
_visitTokenWithSuffix(node.awaitKeyword, ' ');
_writer.print('for (');
_visitNode(node.forLoopParts);
_writer.print(') ');
_visitNode(node.body);
}
@override
void visitFormalParameterList(FormalParameterList node) {
String groupEnd;
_writer.print('(');
NodeList<FormalParameter> parameters = node.parameters;
int size = parameters.length;
for (int i = 0; i < size; i++) {
FormalParameter parameter = parameters[i];
if (i > 0) {
_writer.print(", ");
}
if (groupEnd == null && parameter is DefaultFormalParameter) {
if (parameter.isNamed) {
groupEnd = "}";
_writer.print('{');
} else {
groupEnd = "]";
_writer.print('[');
}
}
parameter.accept(this);
}
if (groupEnd != null) {
_writer.print(groupEnd);
}
_writer.print(')');
}
@override
void visitForPartsWithDeclarations(ForPartsWithDeclarations node) {
_visitNode(node.variables);
_writer.print(';');
_visitNodeWithPrefix(' ', node.condition);
_writer.print(';');
_visitNodeListWithSeparatorAndPrefix(' ', node.updaters, ', ');
}
@override
void visitForPartsWithExpression(ForPartsWithExpression node) {
_visitNode(node.initialization);
_writer.print(';');
_visitNodeWithPrefix(' ', node.condition);
_writer.print(';');
_visitNodeListWithSeparatorAndPrefix(" ", node.updaters, ', ');
}
@override
void visitForStatement(ForStatement node) {
if (node.awaitKeyword != null) {
_writer.print('await ');
}
_writer.print('for (');
_visitNode(node.forLoopParts);
_writer.print(') ');
_visitNode(node.body);
}
@override
void visitFunctionDeclaration(FunctionDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.externalKeyword, " ");
_visitNodeWithSuffix(node.returnType, " ");
_visitTokenWithSuffix(node.propertyKeyword, " ");
_visitNode(node.name);
_visitNode(node.functionExpression);
}
@override
void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
_visitNode(node.functionDeclaration);
}
@override
void visitFunctionExpression(FunctionExpression node) {
_visitNode(node.typeParameters);
_visitNode(node.parameters);
if (node.body is! EmptyFunctionBody) {
_writer.print(' ');
}
_visitNode(node.body);
}
@override
void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
_visitNode(node.function);
_visitNode(node.typeArguments);
_visitNode(node.argumentList);
}
@override
void visitFunctionTypeAlias(FunctionTypeAlias node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("typedef ");
_visitNodeWithSuffix(node.returnType, " ");
_visitNode(node.name);
_visitNode(node.typeParameters);
_visitNode(node.parameters);
_writer.print(";");
}
@override
void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
_visitTokenWithSuffix(node.covariantKeyword, ' ');
_visitNodeWithSuffix(node.returnType, " ");
_visitNode(node.identifier);
_visitNode(node.typeParameters);
_visitNode(node.parameters);
if (node.question != null) {
_writer.print('?');
}
}
@override
void visitGenericFunctionType(GenericFunctionType node) {
_visitNode(node.returnType);
_writer.print(' Function');
_visitNode(node.typeParameters);
_visitNode(node.parameters);
if (node.question != null) {
_writer.print('?');
}
}
@override
void visitGenericTypeAlias(GenericTypeAlias node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("typedef ");
_visitNode(node.name);
_visitNode(node.typeParameters);
_writer.print(" = ");
_visitNode(node.functionType);
}
@override
void visitHideCombinator(HideCombinator node) {
_writer.print("hide ");
_visitNodeListWithSeparator(node.hiddenNames, ", ");
}
@override
void visitIfElement(IfElement node) {
_writer.print('if (');
_visitNode(node.condition);
_writer.print(') ');
_visitNode(node.thenElement);
_visitNodeWithPrefix(' else ', node.elseElement);
}
@override
void visitIfStatement(IfStatement node) {
_writer.print("if (");
_visitNode(node.condition);
_writer.print(") ");
_visitNode(node.thenStatement);
_visitNodeWithPrefix(" else ", node.elseStatement);
}
@override
void visitImplementsClause(ImplementsClause node) {
_writer.print("implements ");
_visitNodeListWithSeparator(node.interfaces, ", ");
}
@override
void visitImportDirective(ImportDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("import ");
_visitNode(node.uri);
if (node.deferredKeyword != null) {
_writer.print(" deferred");
}
_visitNodeWithPrefix(" as ", node.prefix);
_visitNodeListWithSeparatorAndPrefix(" ", node.combinators, " ");
_writer.print(';');
}
@override
void visitIndexExpression(IndexExpression node) {
if (node.isCascaded) {
_writer.print(node.period.lexeme);
} else {
_visitNode(node.target);
}
_writer.print('[');
_visitNode(node.index);
_writer.print(']');
}
@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
_visitTokenWithSuffix(node.keyword, " ");
_visitNode(node.constructorName);
_visitNode(node.argumentList);
}
@override
void visitIntegerLiteral(IntegerLiteral node) {
_writer.print(node.literal.lexeme);
}
@override
void visitInterpolationExpression(InterpolationExpression node) {
if (node.rightBracket != null) {
_writer.print("\${");
_visitNode(node.expression);
_writer.print("}");
} else {
_writer.print("\$");
_visitNode(node.expression);
}
}
@override
void visitInterpolationString(InterpolationString node) {
_writer.print(node.contents.lexeme);
}
@override
void visitIsExpression(IsExpression node) {
_visitNode(node.expression);
if (node.notOperator == null) {
_writer.print(" is ");
} else {
_writer.print(" is! ");
}
_visitNode(node.type);
}
@override
void visitLabel(Label node) {
_visitNode(node.label);
_writer.print(":");
}
@override
void visitLabeledStatement(LabeledStatement node) {
_visitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
_visitNode(node.statement);
}
@override
void visitLibraryDirective(LibraryDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("library ");
_visitNode(node.name);
_writer.print(';');
}
@override
void visitLibraryIdentifier(LibraryIdentifier node) {
_writer.print(node.name);
}
@override
void visitListLiteral(ListLiteral node) {
_visitTokenWithSuffix(node.constKeyword, ' ');
_visitNode(node.typeArguments);
_writer.print('[');
_visitNodeListWithSeparator(node.elements, ', ');
_writer.print(']');
}
@override
void visitMapLiteralEntry(MapLiteralEntry node) {
_visitNode(node.key);
_writer.print(" : ");
_visitNode(node.value);
}
@override
void visitMethodDeclaration(MethodDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.externalKeyword, " ");
_visitTokenWithSuffix(node.modifierKeyword, " ");
_visitNodeWithSuffix(node.returnType, " ");
_visitTokenWithSuffix(node.propertyKeyword, " ");
_visitTokenWithSuffix(node.operatorKeyword, " ");
_visitNode(node.name);
if (!node.isGetter) {
_visitNode(node.typeParameters);
_visitNode(node.parameters);
}
_visitFunctionWithPrefix(" ", node.body);
}
@override
void visitMethodInvocation(MethodInvocation node) {
if (node.isCascaded) {
_writer.print(node.operator.lexeme);
} else {
if (node.target != null) {
node.target.accept(this);
_writer.print(node.operator.lexeme);
}
}
_visitNode(node.methodName);
_visitNode(node.typeArguments);
_visitNode(node.argumentList);
}
@override
void visitMixinDeclaration(MixinDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("mixin ");
_visitNode(node.name);
_visitNode(node.typeParameters);
_visitNodeWithPrefix(" ", node.onClause);
_visitNodeWithPrefix(" ", node.implementsClause);
_writer.print(" {");
_visitNodeListWithSeparator(node.members, " ");
_writer.print("}");
}
@override
void visitNamedExpression(NamedExpression node) {
_visitNode(node.name);
_visitNodeWithPrefix(" ", node.expression);
}
@override
void visitNativeClause(NativeClause node) {
_writer.print("native ");
_visitNode(node.name);
}
@override
void visitNativeFunctionBody(NativeFunctionBody node) {
_writer.print("native ");
_visitNode(node.stringLiteral);
_writer.print(';');
}
@override
void visitNullLiteral(NullLiteral node) {
_writer.print("null");
}
@override
void visitOnClause(OnClause node) {
_writer.print('on ');
_visitNodeListWithSeparator(node.superclassConstraints, ", ");
}
@override
void visitParenthesizedExpression(ParenthesizedExpression node) {
_writer.print('(');
_visitNode(node.expression);
_writer.print(')');
}
@override
void visitPartDirective(PartDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("part ");
_visitNode(node.uri);
_writer.print(';');
}
@override
void visitPartOfDirective(PartOfDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_writer.print("part of ");
_visitNode(node.libraryName);
_writer.print(';');
}
@override
void visitPostfixExpression(PostfixExpression node) {
_visitNode(node.operand);
_writer.print(node.operator.lexeme);
}
@override
void visitPrefixedIdentifier(PrefixedIdentifier node) {
_visitNode(node.prefix);
_writer.print('.');
_visitNode(node.identifier);
}
@override
void visitPrefixExpression(PrefixExpression node) {
_writer.print(node.operator.lexeme);
_visitNode(node.operand);
}
@override
void visitPropertyAccess(PropertyAccess node) {
if (node.isCascaded) {
_writer.print(node.operator.lexeme);
} else {
_visitNode(node.target);
_writer.print(node.operator.lexeme);
}
_visitNode(node.propertyName);
}
@override
void visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
_writer.print("this");
_visitNodeWithPrefix(".", node.constructorName);
_visitNode(node.argumentList);
}
@override
void visitRethrowExpression(RethrowExpression node) {
_writer.print("rethrow");
}
@override
void visitReturnStatement(ReturnStatement node) {
Expression expression = node.expression;
if (expression == null) {
_writer.print("return;");
} else {
_writer.print("return ");
expression.accept(this);
_writer.print(";");
}
}
@override
void visitScriptTag(ScriptTag node) {
_writer.print(node.scriptTag.lexeme);
}
@override
void visitSetOrMapLiteral(SetOrMapLiteral node) {
if (node.constKeyword != null) {
_writer.print(node.constKeyword.lexeme);
_writer.print(' ');
}
_visitNode(node.typeArguments);
_writer.print('{');
_visitNodeListWithSeparator(node.elements, ', ');
_writer.print('}');
}
@override
void visitShowCombinator(ShowCombinator node) {
_writer.print("show ");
_visitNodeListWithSeparator(node.shownNames, ", ");
}
@override
void visitSimpleFormalParameter(SimpleFormalParameter node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
_visitTokenWithSuffix(node.covariantKeyword, ' ');
_visitTokenWithSuffix(node.keyword, " ");
_visitNode(node.type);
if (node.type != null && node.identifier != null) {
_writer.print(' ');
}
_visitNode(node.identifier);
}
@override
void visitSimpleIdentifier(SimpleIdentifier node) {
_writer.print(node.token.lexeme);
}
@override
void visitSimpleStringLiteral(SimpleStringLiteral node) {
_writer.print(node.literal.lexeme);
}
@override
void visitSpreadElement(SpreadElement node) {
_writer.print(node.spreadOperator.lexeme);
_visitNode(node.expression);
}
@override
void visitStringInterpolation(StringInterpolation node) {
_visitNodeList(node.elements);
}
@override
void visitSuperConstructorInvocation(SuperConstructorInvocation node) {
_writer.print("super");
_visitNodeWithPrefix(".", node.constructorName);
_visitNode(node.argumentList);
}
@override
void visitSuperExpression(SuperExpression node) {
_writer.print("super");
}
@override
void visitSwitchCase(SwitchCase node) {
_visitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
_writer.print("case ");
_visitNode(node.expression);
_writer.print(": ");
_visitNodeListWithSeparator(node.statements, " ");
}
@override
void visitSwitchDefault(SwitchDefault node) {
_visitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
_writer.print("default: ");
_visitNodeListWithSeparator(node.statements, " ");
}
@override
void visitSwitchStatement(SwitchStatement node) {
_writer.print("switch (");
_visitNode(node.expression);
_writer.print(") {");
_visitNodeListWithSeparator(node.members, " ");
_writer.print("}");
}
@override
void visitSymbolLiteral(SymbolLiteral node) {
_writer.print("#");
List<Token> components = node.components;
for (int i = 0; i < components.length; i++) {
if (i > 0) {
_writer.print(".");
}
_writer.print(components[i].lexeme);
}
}
@override
void visitThisExpression(ThisExpression node) {
_writer.print("this");
}
@override
void visitThrowExpression(ThrowExpression node) {
_writer.print("throw ");
_visitNode(node.expression);
}
@override
void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
_visitNodeWithSuffix(node.variables, ";");
}
@override
void visitTryStatement(TryStatement node) {
_writer.print("try ");
_visitNode(node.body);
_visitNodeListWithSeparatorAndPrefix(" ", node.catchClauses, " ");
_visitNodeWithPrefix(" finally ", node.finallyBlock);
}
@override
void visitTypeArgumentList(TypeArgumentList node) {
_writer.print('<');
_visitNodeListWithSeparator(node.arguments, ", ");
_writer.print('>');
}
@override
void visitTypeName(TypeName node) {
_visitNode(node.name);
_visitNode(node.typeArguments);
if (node.question != null) {
_writer.print('?');
}
}
@override
void visitTypeParameter(TypeParameter node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitNode(node.name);
_visitNodeWithPrefix(" extends ", node.bound);
}
@override
void visitTypeParameterList(TypeParameterList node) {
_writer.print('<');
_visitNodeListWithSeparator(node.typeParameters, ", ");
_writer.print('>');
}
@override
void visitVariableDeclaration(VariableDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitNode(node.name);
_visitNodeWithPrefix(" = ", node.initializer);
}
@override
void visitVariableDeclarationList(VariableDeclarationList node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.lateKeyword, " ");
_visitTokenWithSuffix(node.keyword, " ");
_visitNodeWithSuffix(node.type, " ");
_visitNodeListWithSeparator(node.variables, ", ");
}
@override
void visitVariableDeclarationStatement(VariableDeclarationStatement node) {
_visitNode(node.variables);
_writer.print(";");
}
@override
void visitWhileStatement(WhileStatement node) {
_writer.print("while (");
_visitNode(node.condition);
_writer.print(") ");
_visitNode(node.body);
}
@override
void visitWithClause(WithClause node) {
_writer.print("with ");
_visitNodeListWithSeparator(node.mixinTypes, ", ");
}
@override
void visitYieldStatement(YieldStatement node) {
if (node.star != null) {
_writer.print("yield* ");
} else {
_writer.print("yield ");
}
_visitNode(node.expression);
_writer.print(";");
}
/**
* Visit the given function [body], printing the [prefix] before if the body
* is not empty.
*/
void _visitFunctionWithPrefix(String prefix, FunctionBody body) {
if (body is! EmptyFunctionBody) {
_writer.print(prefix);
}
_visitNode(body);
}
/**
* Safely visit the given [node].
*/
void _visitNode(AstNode node) {
if (node != null) {
node.accept(this);
}
}
/**
* Print a list of [nodes] without any separation.
*/
void _visitNodeList(NodeList<AstNode> nodes) {
_visitNodeListWithSeparator(nodes, "");
}
/**
* Print a list of [nodes], separated by the given [separator].
*/
void _visitNodeListWithSeparator(NodeList<AstNode> nodes, String separator) {
if (nodes != null) {
int size = nodes.length;
for (int i = 0; i < size; i++) {
if (i > 0) {
_writer.print(separator);
}
nodes[i].accept(this);
}
}
}
/**
* Print a list of [nodes], prefixed by the given [prefix] if the list is not
* empty, and separated by the given [separator].
*/
void _visitNodeListWithSeparatorAndPrefix(
String prefix, NodeList<AstNode> nodes, String separator) {
if (nodes != null) {
int size = nodes.length;
if (size > 0) {
_writer.print(prefix);
for (int i = 0; i < size; i++) {
if (i > 0) {
_writer.print(separator);
}
nodes[i].accept(this);
}
}
}
}
/**
* Print a list of [nodes], separated by the given [separator], followed by
* the given [suffix] if the list is not empty.
*/
void _visitNodeListWithSeparatorAndSuffix(
NodeList<AstNode> nodes, String separator, String suffix) {
if (nodes != null) {
int size = nodes.length;
if (size > 0) {
for (int i = 0; i < size; i++) {
if (i > 0) {
_writer.print(separator);
}
nodes[i].accept(this);
}
_writer.print(suffix);
}
}
}
/**
* Safely visit the given [node], printing the [prefix] before the node if it
* is non-`null`.
*/
void _visitNodeWithPrefix(String prefix, AstNode node) {
if (node != null) {
_writer.print(prefix);
node.accept(this);
}
}
/**
* Safely visit the given [node], printing the [suffix] after the node if it
* is non-`null`.
*/
void _visitNodeWithSuffix(AstNode node, String suffix) {
if (node != null) {
node.accept(this);
_writer.print(suffix);
}
}
/**
* Safely visit the given [token].
*/
void _visitToken(Token token) {
if (token != null) {
_writer.print(token.lexeme);
}
}
/**
* Safely visit the given [token], printing the [suffix] after the token if it
* is non-`null`.
*/
void _visitTokenWithSuffix(Token token, String suffix) {
if (token != null) {
_writer.print(token.lexeme);
_writer.print(suffix);
}
}
}
/**
* A visitor used to write a source representation of a visited AST node (and
* all of it's children) to a sink.
*/
class ToSourceVisitor2 implements AstVisitor<void> {
/**
* The sink to which the source is to be written.
*/
@protected
final StringSink sink;
/**
* Initialize a newly created visitor to write source code representing the
* visited nodes to the given [sink].
*/
ToSourceVisitor2(this.sink);
/**
* Visit the given function [body], printing the [prefix] before if the body
* is not empty.
*/
@protected
void safelyVisitFunctionWithPrefix(String prefix, FunctionBody body) {
if (body is! EmptyFunctionBody) {
sink.write(prefix);
}
safelyVisitNode(body);
}
/**
* Safely visit the given [node].
*/
@protected
void safelyVisitNode(AstNode node) {
if (node != null) {
node.accept(this);
}
}
/**
* Print a list of [nodes] without any separation.
*/
@protected
void safelyVisitNodeList(NodeList<AstNode> nodes) {
safelyVisitNodeListWithSeparator(nodes, "");
}
/**
* Print a list of [nodes], separated by the given [separator].
*/
@protected
void safelyVisitNodeListWithSeparator(
NodeList<AstNode> nodes, String separator) {
if (nodes != null) {
int size = nodes.length;
for (int i = 0; i < size; i++) {
if (i > 0) {
sink.write(separator);
}
var node = nodes[i];
if (node != null) {
node.accept(this);
} else {
sink.write('<null>');
}
}
}
}
/**
* Print a list of [nodes], prefixed by the given [prefix] if the list is not
* empty, and separated by the given [separator].
*/
@protected
void safelyVisitNodeListWithSeparatorAndPrefix(
String prefix, NodeList<AstNode> nodes, String separator) {
if (nodes != null) {
int size = nodes.length;
if (size > 0) {
sink.write(prefix);
for (int i = 0; i < size; i++) {
if (i > 0) {
sink.write(separator);
}
nodes[i].accept(this);
}
}
}
}
/**
* Print a list of [nodes], separated by the given [separator], followed by
* the given [suffix] if the list is not empty.
*/
@protected
void safelyVisitNodeListWithSeparatorAndSuffix(
NodeList<AstNode> nodes, String separator, String suffix) {
if (nodes != null) {
int size = nodes.length;
if (size > 0) {
for (int i = 0; i < size; i++) {
if (i > 0) {
sink.write(separator);
}
nodes[i].accept(this);
}
sink.write(suffix);
}
}
}
/**
* Safely visit the given [node], printing the [prefix] before the node if it
* is non-`null`.
*/
@protected
void safelyVisitNodeWithPrefix(String prefix, AstNode node) {
if (node != null) {
sink.write(prefix);
node.accept(this);
}
}
/**
* Safely visit the given [node], printing the [suffix] after the node if it
* is non-`null`.
*/
@protected
void safelyVisitNodeWithSuffix(AstNode node, String suffix) {
if (node != null) {
node.accept(this);
sink.write(suffix);
}
}
/**
* Safely visit the given [token].
*/
@protected
void safelyVisitToken(Token token) {
if (token != null) {
sink.write(token.lexeme);
}
}
/**
* Safely visit the given [token], printing the [suffix] after the token if it
* is non-`null`.
*/
@protected
void safelyVisitTokenWithSuffix(Token token, String suffix) {
if (token != null) {
sink.write(token.lexeme);
sink.write(suffix);
}
}
@override
void visitAdjacentStrings(AdjacentStrings node) {
safelyVisitNodeListWithSeparator(node.strings, " ");
}
@override
void visitAnnotation(Annotation node) {
sink.write('@');
safelyVisitNode(node.name);
safelyVisitNodeWithPrefix(".", node.constructorName);
safelyVisitNode(node.arguments);
}
@override
void visitArgumentList(ArgumentList node) {
sink.write('(');
safelyVisitNodeListWithSeparator(node.arguments, ", ");
sink.write(')');
}
@override
void visitAsExpression(AsExpression node) {
safelyVisitNode(node.expression);
sink.write(" as ");
safelyVisitNode(node.type);
}
@override
void visitAssertInitializer(AssertInitializer node) {
sink.write("assert (");
safelyVisitNode(node.condition);
if (node.message != null) {
sink.write(', ');
safelyVisitNode(node.message);
}
sink.write(");");
}
@override
void visitAssertStatement(AssertStatement node) {
sink.write("assert (");
safelyVisitNode(node.condition);
if (node.message != null) {
sink.write(', ');
safelyVisitNode(node.message);
}
sink.write(");");
}
@override
void visitAssignmentExpression(AssignmentExpression node) {
safelyVisitNode(node.leftHandSide);
sink.write(' ');
sink.write(node.operator.lexeme);
sink.write(' ');
safelyVisitNode(node.rightHandSide);
}
@override
void visitAwaitExpression(AwaitExpression node) {
sink.write("await ");
safelyVisitNode(node.expression);
}
@override
void visitBinaryExpression(BinaryExpression node) {
_writeOperand(node, node.leftOperand);
sink.write(' ');
sink.write(node.operator.lexeme);
sink.write(' ');
_writeOperand(node, node.rightOperand);
}
@override
void visitBlock(Block node) {
sink.write('{');
safelyVisitNodeListWithSeparator(node.statements, " ");
sink.write('}');
}
@override
void visitBlockFunctionBody(BlockFunctionBody node) {
Token keyword = node.keyword;
if (keyword != null) {
sink.write(keyword.lexeme);
if (node.star != null) {
sink.write('*');
}
sink.write(' ');
}
safelyVisitNode(node.block);
}
@override
void visitBooleanLiteral(BooleanLiteral node) {
sink.write(node.literal.lexeme);
}
@override
void visitBreakStatement(BreakStatement node) {
sink.write("break");
safelyVisitNodeWithPrefix(" ", node.label);
sink.write(";");
}
@override
void visitCascadeExpression(CascadeExpression node) {
safelyVisitNode(node.target);
safelyVisitNodeList(node.cascadeSections);
}
@override
void visitCatchClause(CatchClause node) {
safelyVisitNodeWithPrefix("on ", node.exceptionType);
if (node.catchKeyword != null) {
if (node.exceptionType != null) {
sink.write(' ');
}
sink.write("catch (");
safelyVisitNode(node.exceptionParameter);
safelyVisitNodeWithPrefix(", ", node.stackTraceParameter);
sink.write(") ");
} else {
sink.write(" ");
}
safelyVisitNode(node.body);
}
@override
void visitClassDeclaration(ClassDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitTokenWithSuffix(node.abstractKeyword, " ");
sink.write("class ");
safelyVisitNode(node.name);
safelyVisitNode(node.typeParameters);
safelyVisitNodeWithPrefix(" ", node.extendsClause);
safelyVisitNodeWithPrefix(" ", node.withClause);
safelyVisitNodeWithPrefix(" ", node.implementsClause);
sink.write(" {");
safelyVisitNodeListWithSeparator(node.members, " ");
sink.write("}");
}
@override
void visitClassTypeAlias(ClassTypeAlias node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
if (node.abstractKeyword != null) {
sink.write("abstract ");
}
sink.write("class ");
safelyVisitNode(node.name);
safelyVisitNode(node.typeParameters);
sink.write(" = ");
safelyVisitNode(node.superclass);
safelyVisitNodeWithPrefix(" ", node.withClause);
safelyVisitNodeWithPrefix(" ", node.implementsClause);
sink.write(";");
}
@override
void visitComment(Comment node) {}
@override
void visitCommentReference(CommentReference node) {}
@override
void visitCompilationUnit(CompilationUnit node) {
ScriptTag scriptTag = node.scriptTag;
NodeList<Directive> directives = node.directives;
safelyVisitNode(scriptTag);
String prefix = scriptTag == null ? "" : " ";
safelyVisitNodeListWithSeparatorAndPrefix(prefix, directives, " ");
prefix = scriptTag == null && directives.isEmpty ? "" : " ";
safelyVisitNodeListWithSeparatorAndPrefix(prefix, node.declarations, " ");
}
@override
void visitConditionalExpression(ConditionalExpression node) {
safelyVisitNode(node.condition);
sink.write(" ? ");
safelyVisitNode(node.thenExpression);
sink.write(" : ");
safelyVisitNode(node.elseExpression);
}
@override
void visitConfiguration(Configuration node) {
sink.write('if (');
safelyVisitNode(node.name);
safelyVisitNodeWithPrefix(" == ", node.value);
sink.write(') ');
safelyVisitNode(node.uri);
}
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitTokenWithSuffix(node.externalKeyword, " ");
safelyVisitTokenWithSuffix(node.constKeyword, " ");
safelyVisitTokenWithSuffix(node.factoryKeyword, " ");
safelyVisitNode(node.returnType);
safelyVisitNodeWithPrefix(".", node.name);
safelyVisitNode(node.parameters);
safelyVisitNodeListWithSeparatorAndPrefix(" : ", node.initializers, ", ");
safelyVisitNodeWithPrefix(" = ", node.redirectedConstructor);
safelyVisitFunctionWithPrefix(" ", node.body);
}
@override
void visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
safelyVisitTokenWithSuffix(node.thisKeyword, ".");
safelyVisitNode(node.fieldName);
sink.write(" = ");
safelyVisitNode(node.expression);
}
@override
void visitConstructorName(ConstructorName node) {
safelyVisitNode(node.type);
safelyVisitNodeWithPrefix(".", node.name);
}
@override
void visitContinueStatement(ContinueStatement node) {
sink.write("continue");
safelyVisitNodeWithPrefix(" ", node.label);
sink.write(";");
}
@override
void visitDeclaredIdentifier(DeclaredIdentifier node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitTokenWithSuffix(node.keyword, " ");
safelyVisitNodeWithSuffix(node.type, " ");
safelyVisitNode(node.identifier);
}
@override
void visitDefaultFormalParameter(DefaultFormalParameter node) {
if (node.isRequiredNamed) {
sink.write('required ');
}
safelyVisitNode(node.parameter);
if (node.separator != null) {
if (node.separator.lexeme != ":") {
sink.write(" ");
}
sink.write(node.separator.lexeme);
safelyVisitNodeWithPrefix(" ", node.defaultValue);
}
}
@override
void visitDoStatement(DoStatement node) {
sink.write("do ");
safelyVisitNode(node.body);
sink.write(" while (");
safelyVisitNode(node.condition);
sink.write(");");
}
@override
void visitDottedName(DottedName node) {
safelyVisitNodeListWithSeparator(node.components, ".");
}
@override
void visitDoubleLiteral(DoubleLiteral node) {
sink.write(node.literal.lexeme);
}
@override
void visitEmptyFunctionBody(EmptyFunctionBody node) {
sink.write(';');
}
@override
void visitEmptyStatement(EmptyStatement node) {
sink.write(';');
}
@override
void visitEnumConstantDeclaration(EnumConstantDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitNode(node.name);
}
@override
void visitEnumDeclaration(EnumDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("enum ");
safelyVisitNode(node.name);
sink.write(" {");
safelyVisitNodeListWithSeparator(node.constants, ", ");
sink.write("}");
}
@override
void visitExportDirective(ExportDirective node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("export ");
safelyVisitNode(node.uri);
safelyVisitNodeListWithSeparatorAndPrefix(" ", node.combinators, " ");
sink.write(';');
}
@override
void visitExpressionFunctionBody(ExpressionFunctionBody node) {
Token keyword = node.keyword;
if (keyword != null) {
sink.write(keyword.lexeme);
sink.write(' ');
}
sink.write('${node.functionDefinition?.lexeme} ');
safelyVisitNode(node.expression);
if (node.semicolon != null) {
sink.write(';');
}
}
@override
void visitExpressionStatement(ExpressionStatement node) {
safelyVisitNode(node.expression);
sink.write(';');
}
@override
void visitExtendsClause(ExtendsClause node) {
sink.write("extends ");
safelyVisitNode(node.superclass);
}
@override
void visitExtensionDeclaration(ExtensionDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
safelyVisitTokenWithSuffix(node.extensionKeyword, ' ');
safelyVisitNode(node.name);
safelyVisitNode(node.typeParameters);
sink.write(' ');
safelyVisitToken(node.onKeyword);
sink.write(' ');
safelyVisitNodeWithSuffix(node.extendedType, ' ');
safelyVisitToken(node.leftBracket);
safelyVisitNodeListWithSeparator(node.members, ' ');
safelyVisitToken(node.rightBracket);
}
@override
void visitExtensionOverride(ExtensionOverride node) {
safelyVisitNode(node.extensionName);
safelyVisitNode(node.typeArguments);
safelyVisitNode(node.argumentList);
}
@override
void visitFieldDeclaration(FieldDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitTokenWithSuffix(node.staticKeyword, " ");
safelyVisitNode(node.fields);
sink.write(";");
}
@override
void visitFieldFormalParameter(FieldFormalParameter node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
safelyVisitTokenWithSuffix(node.covariantKeyword, ' ');
safelyVisitTokenWithSuffix(node.keyword, " ");
safelyVisitNodeWithSuffix(node.type, " ");
sink.write("this.");
safelyVisitNode(node.identifier);
safelyVisitNode(node.typeParameters);
safelyVisitNode(node.parameters);
}
@override
void visitForEachPartsWithDeclaration(ForEachPartsWithDeclaration node) {
safelyVisitNode(node.loopVariable);
sink.write(' in ');
safelyVisitNode(node.iterable);
}
@override
void visitForEachPartsWithIdentifier(ForEachPartsWithIdentifier node) {
safelyVisitNode(node.identifier);
sink.write(' in ');
safelyVisitNode(node.iterable);
}
@override
void visitForElement(ForElement node) {
safelyVisitTokenWithSuffix(node.awaitKeyword, ' ');
sink.write('for (');
safelyVisitNode(node.forLoopParts);
sink.write(') ');
safelyVisitNode(node.body);
}
@override
void visitFormalParameterList(FormalParameterList node) {
String groupEnd;
sink.write('(');
NodeList<FormalParameter> parameters = node.parameters;
int size = parameters.length;
for (int i = 0; i < size; i++) {
FormalParameter parameter = parameters[i];
if (i > 0) {
sink.write(", ");
}
if (groupEnd == null && parameter is DefaultFormalParameter) {
if (parameter.isNamed) {
groupEnd = "}";
sink.write('{');
} else {
groupEnd = "]";
sink.write('[');
}
}
parameter.accept(this);
}
if (groupEnd != null) {
sink.write(groupEnd);
}
sink.write(')');
}
@override
void visitForPartsWithDeclarations(ForPartsWithDeclarations node) {
safelyVisitNode(node.variables);
sink.write(';');
safelyVisitNodeWithPrefix(' ', node.condition);
sink.write(';');
safelyVisitNodeListWithSeparatorAndPrefix(' ', node.updaters, ', ');
}
@override
void visitForPartsWithExpression(ForPartsWithExpression node) {
safelyVisitNode(node.initialization);
sink.write(';');
safelyVisitNodeWithPrefix(' ', node.condition);
sink.write(';');
safelyVisitNodeListWithSeparatorAndPrefix(" ", node.updaters, ', ');
}
@override
void visitForStatement(ForStatement node) {
if (node.awaitKeyword != null) {
sink.write('await ');
}
sink.write('for (');
safelyVisitNode(node.forLoopParts);
sink.write(') ');
safelyVisitNode(node.body);
}
@override
void visitFunctionDeclaration(FunctionDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitTokenWithSuffix(node.externalKeyword, " ");
safelyVisitNodeWithSuffix(node.returnType, " ");
safelyVisitTokenWithSuffix(node.propertyKeyword, " ");
safelyVisitNode(node.name);
safelyVisitNode(node.functionExpression);
}
@override
void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
safelyVisitNode(node.functionDeclaration);
}
@override
void visitFunctionExpression(FunctionExpression node) {
safelyVisitNode(node.typeParameters);
safelyVisitNode(node.parameters);
if (node.body is! EmptyFunctionBody) {
sink.write(' ');
}
safelyVisitNode(node.body);
}
@override
void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
safelyVisitNode(node.function);
safelyVisitNode(node.typeArguments);
safelyVisitNode(node.argumentList);
}
@override
void visitFunctionTypeAlias(FunctionTypeAlias node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("typedef ");
safelyVisitNodeWithSuffix(node.returnType, " ");
safelyVisitNode(node.name);
safelyVisitNode(node.typeParameters);
safelyVisitNode(node.parameters);
sink.write(";");
}
@override
void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
safelyVisitTokenWithSuffix(node.covariantKeyword, ' ');
safelyVisitNodeWithSuffix(node.returnType, " ");
safelyVisitNode(node.identifier);
safelyVisitNode(node.typeParameters);
safelyVisitNode(node.parameters);
if (node.question != null) {
sink.write('?');
}
}
@override
void visitGenericFunctionType(GenericFunctionType node) {
safelyVisitNode(node.returnType);
sink.write(' Function');
safelyVisitNode(node.typeParameters);
safelyVisitNode(node.parameters);
if (node.question != null) {
sink.write('?');
}
}
@override
void visitGenericTypeAlias(GenericTypeAlias node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("typedef ");
safelyVisitNode(node.name);
safelyVisitNode(node.typeParameters);
sink.write(" = ");
safelyVisitNode(node.functionType);
}
@override
void visitHideCombinator(HideCombinator node) {
sink.write("hide ");
safelyVisitNodeListWithSeparator(node.hiddenNames, ", ");
}
@override
void visitIfElement(IfElement node) {
sink.write('if (');
safelyVisitNode(node.condition);
sink.write(') ');
safelyVisitNode(node.thenElement);
safelyVisitNodeWithPrefix(' else ', node.elseElement);
}
@override
void visitIfStatement(IfStatement node) {
sink.write("if (");
safelyVisitNode(node.condition);
sink.write(") ");
safelyVisitNode(node.thenStatement);
safelyVisitNodeWithPrefix(" else ", node.elseStatement);
}
@override
void visitImplementsClause(ImplementsClause node) {
sink.write("implements ");
safelyVisitNodeListWithSeparator(node.interfaces, ", ");
}
@override
void visitImportDirective(ImportDirective node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("import ");
safelyVisitNode(node.uri);
if (node.deferredKeyword != null) {
sink.write(" deferred");
}
safelyVisitNodeWithPrefix(" as ", node.prefix);
safelyVisitNodeListWithSeparatorAndPrefix(" ", node.combinators, " ");
sink.write(';');
}
@override
void visitIndexExpression(IndexExpression node) {
if (node.isCascaded) {
sink.write(node.period.lexeme);
} else {
safelyVisitNode(node.target);
}
sink.write('[');
safelyVisitNode(node.index);
sink.write(']');
}
@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
safelyVisitTokenWithSuffix(node.keyword, " ");
safelyVisitNode(node.constructorName);
safelyVisitNode(node.argumentList);
}
@override
void visitIntegerLiteral(IntegerLiteral node) {
sink.write(node.literal.lexeme);
}
@override
void visitInterpolationExpression(InterpolationExpression node) {
if (node.rightBracket != null) {
sink.write("\${");
safelyVisitNode(node.expression);
sink.write("}");
} else {
sink.write("\$");
safelyVisitNode(node.expression);
}
}
@override
void visitInterpolationString(InterpolationString node) {
sink.write(node.contents.lexeme);
}
@override
void visitIsExpression(IsExpression node) {
safelyVisitNode(node.expression);
if (node.notOperator == null) {
sink.write(" is ");
} else {
sink.write(" is! ");
}
safelyVisitNode(node.type);
}
@override
void visitLabel(Label node) {
safelyVisitNode(node.label);
sink.write(":");
}
@override
void visitLabeledStatement(LabeledStatement node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
safelyVisitNode(node.statement);
}
@override
void visitLibraryDirective(LibraryDirective node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("library ");
safelyVisitNode(node.name);
sink.write(';');
}
@override
void visitLibraryIdentifier(LibraryIdentifier node) {
sink.write(node.name);
}
@override
void visitListLiteral(ListLiteral node) {
safelyVisitTokenWithSuffix(node.constKeyword, ' ');
safelyVisitNode(node.typeArguments);
sink.write('[');
safelyVisitNodeListWithSeparator(node.elements, ', ');
sink.write(']');
}
@override
void visitMapLiteralEntry(MapLiteralEntry node) {
safelyVisitNode(node.key);
sink.write(" : ");
safelyVisitNode(node.value);
}
@override
void visitMethodDeclaration(MethodDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitTokenWithSuffix(node.externalKeyword, " ");
safelyVisitTokenWithSuffix(node.modifierKeyword, " ");
safelyVisitNodeWithSuffix(node.returnType, " ");
safelyVisitTokenWithSuffix(node.propertyKeyword, " ");
safelyVisitTokenWithSuffix(node.operatorKeyword, " ");
safelyVisitNode(node.name);
if (!node.isGetter) {
safelyVisitNode(node.typeParameters);
safelyVisitNode(node.parameters);
}
safelyVisitFunctionWithPrefix(" ", node.body);
}
@override
void visitMethodInvocation(MethodInvocation node) {
if (node.isCascaded) {
sink.write(node.operator.lexeme);
} else {
if (node.target != null) {
node.target.accept(this);
sink.write(node.operator.lexeme);
}
}
safelyVisitNode(node.methodName);
safelyVisitNode(node.typeArguments);
safelyVisitNode(node.argumentList);
}
@override
void visitMixinDeclaration(MixinDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("mixin ");
safelyVisitNode(node.name);
safelyVisitNode(node.typeParameters);
safelyVisitNodeWithPrefix(" ", node.onClause);
safelyVisitNodeWithPrefix(" ", node.implementsClause);
sink.write(" {");
safelyVisitNodeListWithSeparator(node.members, " ");
sink.write("}");
}
@override
void visitNamedExpression(NamedExpression node) {
safelyVisitNode(node.name);
safelyVisitNodeWithPrefix(" ", node.expression);
}
@override
void visitNativeClause(NativeClause node) {
sink.write("native ");
safelyVisitNode(node.name);
}
@override
void visitNativeFunctionBody(NativeFunctionBody node) {
sink.write("native ");
safelyVisitNode(node.stringLiteral);
sink.write(';');
}
@override
void visitNullLiteral(NullLiteral node) {
sink.write("null");
}
@override
void visitOnClause(OnClause node) {
sink.write('on ');
safelyVisitNodeListWithSeparator(node.superclassConstraints, ", ");
}
@override
void visitParenthesizedExpression(ParenthesizedExpression node) {
sink.write('(');
safelyVisitNode(node.expression);
sink.write(')');
}
@override
void visitPartDirective(PartDirective node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("part ");
safelyVisitNode(node.uri);
sink.write(';');
}
@override
void visitPartOfDirective(PartOfDirective node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
sink.write("part of ");
safelyVisitNode(node.libraryName);
sink.write(';');
}
@override
void visitPostfixExpression(PostfixExpression node) {
_writeOperand(node, node.operand);
sink.write(node.operator.lexeme);
}
@override
void visitPrefixedIdentifier(PrefixedIdentifier node) {
safelyVisitNode(node.prefix);
sink.write('.');
safelyVisitNode(node.identifier);
}
@override
void visitPrefixExpression(PrefixExpression node) {
sink.write(node.operator.lexeme);
_writeOperand(node, node.operand);
}
@override
void visitPropertyAccess(PropertyAccess node) {
if (node.isCascaded) {
sink.write(node.operator.lexeme);
} else {
safelyVisitNode(node.target);
sink.write(node.operator.lexeme);
}
safelyVisitNode(node.propertyName);
}
@override
void visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
sink.write("this");
safelyVisitNodeWithPrefix(".", node.constructorName);
safelyVisitNode(node.argumentList);
}
@override
void visitRethrowExpression(RethrowExpression node) {
sink.write("rethrow");
}
@override
void visitReturnStatement(ReturnStatement node) {
Expression expression = node.expression;
if (expression == null) {
sink.write("return;");
} else {
sink.write("return ");
expression.accept(this);
sink.write(";");
}
}
@override
void visitScriptTag(ScriptTag node) {
sink.write(node.scriptTag.lexeme);
}
@override
void visitSetOrMapLiteral(SetOrMapLiteral node) {
safelyVisitTokenWithSuffix(node.constKeyword, ' ');
safelyVisitNode(node.typeArguments);
sink.write('{');
safelyVisitNodeListWithSeparator(node.elements, ', ');
sink.write('}');
}
@override
void visitShowCombinator(ShowCombinator node) {
sink.write("show ");
safelyVisitNodeListWithSeparator(node.shownNames, ", ");
}
@override
void visitSimpleFormalParameter(SimpleFormalParameter node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
safelyVisitTokenWithSuffix(node.covariantKeyword, ' ');
safelyVisitTokenWithSuffix(node.keyword, " ");
safelyVisitNode(node.type);
if (node.type != null && node.identifier != null) {
sink.write(' ');
}
safelyVisitNode(node.identifier);
}
@override
void visitSimpleIdentifier(SimpleIdentifier node) {
sink.write(node.token.lexeme);
}
@override
void visitSimpleStringLiteral(SimpleStringLiteral node) {
sink.write(node.literal.lexeme);
}
@override
void visitSpreadElement(SpreadElement node) {
sink.write(node.spreadOperator.lexeme);
safelyVisitNode(node.expression);
}
@override
void visitStringInterpolation(StringInterpolation node) {
safelyVisitNodeList(node.elements);
}
@override
void visitSuperConstructorInvocation(SuperConstructorInvocation node) {
sink.write("super");
safelyVisitNodeWithPrefix(".", node.constructorName);
safelyVisitNode(node.argumentList);
}
@override
void visitSuperExpression(SuperExpression node) {
sink.write("super");
}
@override
void visitSwitchCase(SwitchCase node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
sink.write("case ");
safelyVisitNode(node.expression);
sink.write(": ");
safelyVisitNodeListWithSeparator(node.statements, " ");
}
@override
void visitSwitchDefault(SwitchDefault node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
sink.write("default: ");
safelyVisitNodeListWithSeparator(node.statements, " ");
}
@override
void visitSwitchStatement(SwitchStatement node) {
sink.write("switch (");
safelyVisitNode(node.expression);
sink.write(") {");
safelyVisitNodeListWithSeparator(node.members, " ");
sink.write("}");
}
@override
void visitSymbolLiteral(SymbolLiteral node) {
sink.write("#");
List<Token> components = node.components;
for (int i = 0; i < components.length; i++) {
if (i > 0) {
sink.write(".");
}
sink.write(components[i].lexeme);
}
}
@override
void visitThisExpression(ThisExpression node) {
sink.write("this");
}
@override
void visitThrowExpression(ThrowExpression node) {
sink.write("throw ");
safelyVisitNode(node.expression);
}
@override
void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
safelyVisitNodeWithSuffix(node.variables, ";");
}
@override
void visitTryStatement(TryStatement node) {
sink.write("try ");
safelyVisitNode(node.body);
safelyVisitNodeListWithSeparatorAndPrefix(" ", node.catchClauses, " ");
safelyVisitNodeWithPrefix(" finally ", node.finallyBlock);
}
@override
void visitTypeArgumentList(TypeArgumentList node) {
sink.write('<');
safelyVisitNodeListWithSeparator(node.arguments, ", ");
sink.write('>');
}
@override
void visitTypeName(TypeName node) {
safelyVisitNode(node.name);
safelyVisitNode(node.typeArguments);
if (node.question != null) {
sink.write('?');
}
}
@override
void visitTypeParameter(TypeParameter node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitNode(node.name);
safelyVisitNodeWithPrefix(" extends ", node.bound);
}
@override
void visitTypeParameterList(TypeParameterList node) {
sink.write('<');
safelyVisitNodeListWithSeparator(node.typeParameters, ", ");
sink.write('>');
}
@override
void visitVariableDeclaration(VariableDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitNode(node.name);
safelyVisitNodeWithPrefix(" = ", node.initializer);
}
@override
void visitVariableDeclarationList(VariableDeclarationList node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
safelyVisitTokenWithSuffix(node.lateKeyword, " ");
safelyVisitTokenWithSuffix(node.keyword, " ");
safelyVisitNodeWithSuffix(node.type, " ");
safelyVisitNodeListWithSeparator(node.variables, ", ");
}
@override
void visitVariableDeclarationStatement(VariableDeclarationStatement node) {
safelyVisitNode(node.variables);
sink.write(";");
}
@override
void visitWhileStatement(WhileStatement node) {
sink.write("while (");
safelyVisitNode(node.condition);
sink.write(") ");
safelyVisitNode(node.body);
}
@override
void visitWithClause(WithClause node) {
sink.write("with ");
safelyVisitNodeListWithSeparator(node.mixinTypes, ", ");
}
@override
void visitYieldStatement(YieldStatement node) {
if (node.star != null) {
sink.write("yield* ");
} else {
sink.write("yield ");
}
safelyVisitNode(node.expression);
sink.write(";");
}
void _writeOperand(Expression node, Expression operand) {
if (operand != null) {
bool needsParenthesis = operand.precedence < node.precedence;
if (needsParenthesis) {
sink.write('(');
}
operand.accept(this);
if (needsParenthesis) {
sink.write(')');
}
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/ast/ast_factory.dart | // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/ast_factory.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
import 'package:front_end/src/scanner/token.dart';
import 'package:meta/meta.dart';
/**
* Concrete implementation of [AstFactory] based on the standard AST
* implementation.
*/
class AstFactoryImpl extends AstFactory {
@override
AdjacentStrings adjacentStrings(List<StringLiteral> strings) =>
new AdjacentStringsImpl(strings);
@override
Annotation annotation(Token atSign, Identifier name, Token period,
SimpleIdentifier constructorName, ArgumentList arguments) =>
new AnnotationImpl(atSign, name, period, constructorName, arguments);
@override
ArgumentList argumentList(Token leftParenthesis, List<Expression> arguments,
Token rightParenthesis) =>
new ArgumentListImpl(leftParenthesis, arguments, rightParenthesis);
@override
AsExpression asExpression(
Expression expression, Token asOperator, TypeAnnotation type) =>
new AsExpressionImpl(expression, asOperator, type);
@override
AssertInitializer assertInitializer(
Token assertKeyword,
Token leftParenthesis,
Expression condition,
Token comma,
Expression message,
Token rightParenthesis) =>
new AssertInitializerImpl(assertKeyword, leftParenthesis, condition,
comma, message, rightParenthesis);
@override
AssertStatement assertStatement(
Token assertKeyword,
Token leftParenthesis,
Expression condition,
Token comma,
Expression message,
Token rightParenthesis,
Token semicolon) =>
new AssertStatementImpl(assertKeyword, leftParenthesis, condition, comma,
message, rightParenthesis, semicolon);
@override
AssignmentExpression assignmentExpression(
Expression leftHandSide, Token operator, Expression rightHandSide) =>
new AssignmentExpressionImpl(leftHandSide, operator, rightHandSide);
@override
AwaitExpression awaitExpression(Token awaitKeyword, Expression expression) =>
new AwaitExpressionImpl(awaitKeyword, expression);
@override
BinaryExpression binaryExpression(
Expression leftOperand, Token operator, Expression rightOperand) =>
new BinaryExpressionImpl(leftOperand, operator, rightOperand);
@override
Block block(
Token leftBracket, List<Statement> statements, Token rightBracket) =>
new BlockImpl(leftBracket, statements, rightBracket);
@override
Comment blockComment(List<Token> tokens) =>
CommentImpl.createBlockComment(tokens);
@override
BlockFunctionBody blockFunctionBody(Token keyword, Token star, Block block) =>
new BlockFunctionBodyImpl(keyword, star, block);
@override
BooleanLiteral booleanLiteral(Token literal, bool value) =>
new BooleanLiteralImpl(literal, value);
@override
BreakStatement breakStatement(
Token breakKeyword, SimpleIdentifier label, Token semicolon) =>
new BreakStatementImpl(breakKeyword, label, semicolon);
@override
CascadeExpression cascadeExpression(
Expression target, List<Expression> cascadeSections) =>
new CascadeExpressionImpl(target, cascadeSections);
@override
CatchClause catchClause(
Token onKeyword,
TypeAnnotation exceptionType,
Token catchKeyword,
Token leftParenthesis,
SimpleIdentifier exceptionParameter,
Token comma,
SimpleIdentifier stackTraceParameter,
Token rightParenthesis,
Block body) =>
new CatchClauseImpl(
onKeyword,
exceptionType,
catchKeyword,
leftParenthesis,
exceptionParameter,
comma,
stackTraceParameter,
rightParenthesis,
body);
@override
ClassDeclaration classDeclaration(
Comment comment,
List<Annotation> metadata,
Token abstractKeyword,
Token classKeyword,
SimpleIdentifier name,
TypeParameterList typeParameters,
ExtendsClause extendsClause,
WithClause withClause,
ImplementsClause implementsClause,
Token leftBracket,
List<ClassMember> members,
Token rightBracket) =>
new ClassDeclarationImpl(
comment,
metadata,
abstractKeyword,
classKeyword,
name,
typeParameters,
extendsClause,
withClause,
implementsClause,
leftBracket,
members,
rightBracket);
@override
ClassTypeAlias classTypeAlias(
Comment comment,
List<Annotation> metadata,
Token keyword,
SimpleIdentifier name,
TypeParameterList typeParameters,
Token equals,
Token abstractKeyword,
TypeName superclass,
WithClause withClause,
ImplementsClause implementsClause,
Token semicolon) =>
new ClassTypeAliasImpl(
comment,
metadata,
keyword,
name,
typeParameters,
equals,
abstractKeyword,
superclass,
withClause,
implementsClause,
semicolon);
@override
CommentReference commentReference(Token newKeyword, Identifier identifier) =>
new CommentReferenceImpl(newKeyword, identifier);
@override
CompilationUnit compilationUnit(
{Token beginToken,
ScriptTag scriptTag,
List<Directive> directives,
List<CompilationUnitMember> declarations,
Token endToken,
FeatureSet featureSet}) =>
new CompilationUnitImpl(beginToken, scriptTag, directives, declarations,
endToken, featureSet);
@override
ConditionalExpression conditionalExpression(
Expression condition,
Token question,
Expression thenExpression,
Token colon,
Expression elseExpression) =>
new ConditionalExpressionImpl(
condition, question, thenExpression, colon, elseExpression);
@override
Configuration configuration(
Token ifKeyword,
Token leftParenthesis,
DottedName name,
Token equalToken,
StringLiteral value,
Token rightParenthesis,
StringLiteral libraryUri) =>
new ConfigurationImpl(ifKeyword, leftParenthesis, name, equalToken, value,
rightParenthesis, libraryUri);
@override
ConstructorDeclaration constructorDeclaration(
Comment comment,
List<Annotation> metadata,
Token externalKeyword,
Token constKeyword,
Token factoryKeyword,
Identifier returnType,
Token period,
SimpleIdentifier name,
FormalParameterList parameters,
Token separator,
List<ConstructorInitializer> initializers,
ConstructorName redirectedConstructor,
FunctionBody body) =>
new ConstructorDeclarationImpl(
comment,
metadata,
externalKeyword,
constKeyword,
factoryKeyword,
returnType,
period,
name,
parameters,
separator,
initializers,
redirectedConstructor,
body);
@override
ConstructorFieldInitializer constructorFieldInitializer(
Token thisKeyword,
Token period,
SimpleIdentifier fieldName,
Token equals,
Expression expression) =>
new ConstructorFieldInitializerImpl(
thisKeyword, period, fieldName, equals, expression);
@override
ConstructorName constructorName(
TypeName type, Token period, SimpleIdentifier name) =>
new ConstructorNameImpl(type, period, name);
@override
ContinueStatement continueStatement(
Token continueKeyword, SimpleIdentifier label, Token semicolon) =>
new ContinueStatementImpl(continueKeyword, label, semicolon);
@override
DeclaredIdentifier declaredIdentifier(
Comment comment,
List<Annotation> metadata,
Token keyword,
TypeAnnotation type,
SimpleIdentifier identifier) =>
new DeclaredIdentifierImpl(comment, metadata, keyword, type, identifier);
@override
DefaultFormalParameter defaultFormalParameter(NormalFormalParameter parameter,
ParameterKind kind, Token separator, Expression defaultValue) =>
new DefaultFormalParameterImpl(parameter, kind, separator, defaultValue);
@override
Comment documentationComment(List<Token> tokens,
[List<CommentReference> references]) =>
CommentImpl.createDocumentationCommentWithReferences(
tokens, references ?? <CommentReference>[]);
@override
DoStatement doStatement(
Token doKeyword,
Statement body,
Token whileKeyword,
Token leftParenthesis,
Expression condition,
Token rightParenthesis,
Token semicolon) =>
new DoStatementImpl(doKeyword, body, whileKeyword, leftParenthesis,
condition, rightParenthesis, semicolon);
@override
DottedName dottedName(List<SimpleIdentifier> components) =>
new DottedNameImpl(components);
@override
DoubleLiteral doubleLiteral(Token literal, double value) =>
new DoubleLiteralImpl(literal, value);
@override
EmptyFunctionBody emptyFunctionBody(Token semicolon) =>
new EmptyFunctionBodyImpl(semicolon);
@override
EmptyStatement emptyStatement(Token semicolon) =>
new EmptyStatementImpl(semicolon);
@override
Comment endOfLineComment(List<Token> tokens) =>
CommentImpl.createEndOfLineComment(tokens);
@override
EnumConstantDeclaration enumConstantDeclaration(
Comment comment, List<Annotation> metadata, SimpleIdentifier name) =>
new EnumConstantDeclarationImpl(comment, metadata, name);
@override
EnumDeclaration enumDeclaration(
Comment comment,
List<Annotation> metadata,
Token enumKeyword,
SimpleIdentifier name,
Token leftBracket,
List<EnumConstantDeclaration> constants,
Token rightBracket) =>
new EnumDeclarationImpl(comment, metadata, enumKeyword, name, leftBracket,
constants, rightBracket);
@override
ExportDirective exportDirective(
Comment comment,
List<Annotation> metadata,
Token keyword,
StringLiteral libraryUri,
List<Configuration> configurations,
List<Combinator> combinators,
Token semicolon) =>
new ExportDirectiveImpl(comment, metadata, keyword, libraryUri,
configurations, combinators, semicolon);
@override
ExpressionFunctionBody expressionFunctionBody(Token keyword,
Token functionDefinition, Expression expression, Token semicolon) =>
new ExpressionFunctionBodyImpl(
keyword, functionDefinition, expression, semicolon);
@override
ExpressionStatement expressionStatement(
Expression expression, Token semicolon) =>
new ExpressionStatementImpl(expression, semicolon);
@override
ExtendsClause extendsClause(Token extendsKeyword, TypeName superclass) =>
new ExtendsClauseImpl(extendsKeyword, superclass);
@override
ExtensionDeclaration extensionDeclaration(
{Comment comment,
List<Annotation> metadata,
Token extensionKeyword,
@required SimpleIdentifier name,
TypeParameterList typeParameters,
Token onKeyword,
@required TypeAnnotation extendedType,
Token leftBracket,
List<ClassMember> members,
Token rightBracket}) =>
new ExtensionDeclarationImpl(
comment,
metadata,
extensionKeyword,
name,
typeParameters,
onKeyword,
extendedType,
leftBracket,
members,
rightBracket);
@override
ExtensionOverride extensionOverride(
{@required Identifier extensionName,
TypeArgumentList typeArguments,
@required ArgumentList argumentList}) =>
ExtensionOverrideImpl(extensionName, typeArguments, argumentList);
@override
FieldDeclaration fieldDeclaration(
Comment comment,
List<Annotation> metadata,
Token staticKeyword,
VariableDeclarationList fieldList,
Token semicolon) =>
new FieldDeclarationImpl(
comment, metadata, null, staticKeyword, fieldList, semicolon);
@override
FieldDeclaration fieldDeclaration2(
{Comment comment,
List<Annotation> metadata,
Token covariantKeyword,
Token staticKeyword,
@required VariableDeclarationList fieldList,
@required Token semicolon}) =>
new FieldDeclarationImpl(comment, metadata, covariantKeyword,
staticKeyword, fieldList, semicolon);
@override
FieldFormalParameter fieldFormalParameter(
Comment comment,
List<Annotation> metadata,
Token keyword,
TypeAnnotation type,
Token thisKeyword,
Token period,
SimpleIdentifier identifier,
TypeParameterList typeParameters,
FormalParameterList parameters) =>
new FieldFormalParameterImpl(comment, metadata, null, null, keyword, type,
thisKeyword, period, identifier, typeParameters, parameters);
@override
FieldFormalParameter fieldFormalParameter2(
{Comment comment,
List<Annotation> metadata,
Token covariantKeyword,
Token requiredKeyword,
Token keyword,
TypeAnnotation type,
@required Token thisKeyword,
@required Token period,
@required SimpleIdentifier identifier,
TypeParameterList typeParameters,
FormalParameterList parameters}) =>
new FieldFormalParameterImpl(
comment,
metadata,
covariantKeyword,
requiredKeyword,
keyword,
type,
thisKeyword,
period,
identifier,
typeParameters,
parameters);
@override
ForEachPartsWithDeclaration forEachPartsWithDeclaration(
{DeclaredIdentifier loopVariable,
Token inKeyword,
Expression iterable}) =>
new ForEachPartsWithDeclarationImpl(loopVariable, inKeyword, iterable);
@override
ForEachPartsWithIdentifier forEachPartsWithIdentifier(
{SimpleIdentifier identifier,
Token inKeyword,
Expression iterable}) =>
new ForEachPartsWithIdentifierImpl(identifier, inKeyword, iterable);
@override
ForElement forElement(
{Token awaitKeyword,
Token forKeyword,
Token leftParenthesis,
ForLoopParts forLoopParts,
Token rightParenthesis,
CollectionElement body}) =>
new ForElementImpl(awaitKeyword, forKeyword, leftParenthesis,
forLoopParts, rightParenthesis, body);
@override
FormalParameterList formalParameterList(
Token leftParenthesis,
List<FormalParameter> parameters,
Token leftDelimiter,
Token rightDelimiter,
Token rightParenthesis) =>
new FormalParameterListImpl(leftParenthesis, parameters, leftDelimiter,
rightDelimiter, rightParenthesis);
@override
ForPartsWithDeclarations forPartsWithDeclarations(
{VariableDeclarationList variables,
Token leftSeparator,
Expression condition,
Token rightSeparator,
List<Expression> updaters}) =>
new ForPartsWithDeclarationsImpl(
variables, leftSeparator, condition, rightSeparator, updaters);
@override
ForPartsWithExpression forPartsWithExpression(
{Expression initialization,
Token leftSeparator,
Expression condition,
Token rightSeparator,
List<Expression> updaters}) =>
new ForPartsWithExpressionImpl(
initialization, leftSeparator, condition, rightSeparator, updaters);
@override
ForStatement forStatement(
{Token awaitKeyword,
Token forKeyword,
Token leftParenthesis,
ForLoopParts forLoopParts,
Token rightParenthesis,
Statement body}) {
return ForStatementImpl(awaitKeyword, forKeyword, leftParenthesis,
forLoopParts, rightParenthesis, body);
}
@override
FunctionDeclaration functionDeclaration(
Comment comment,
List<Annotation> metadata,
Token externalKeyword,
TypeAnnotation returnType,
Token propertyKeyword,
SimpleIdentifier name,
FunctionExpression functionExpression) =>
new FunctionDeclarationImpl(comment, metadata, externalKeyword,
returnType, propertyKeyword, name, functionExpression);
@override
FunctionDeclarationStatement functionDeclarationStatement(
FunctionDeclaration functionDeclaration) =>
new FunctionDeclarationStatementImpl(functionDeclaration);
@override
FunctionExpression functionExpression(TypeParameterList typeParameters,
FormalParameterList parameters, FunctionBody body) =>
new FunctionExpressionImpl(typeParameters, parameters, body);
@override
FunctionExpressionInvocation functionExpressionInvocation(Expression function,
TypeArgumentList typeArguments, ArgumentList argumentList) =>
new FunctionExpressionInvocationImpl(
function, typeArguments, argumentList);
@override
FunctionTypeAlias functionTypeAlias(
Comment comment,
List<Annotation> metadata,
Token keyword,
TypeAnnotation returnType,
SimpleIdentifier name,
TypeParameterList typeParameters,
FormalParameterList parameters,
Token semicolon) =>
new FunctionTypeAliasImpl(comment, metadata, keyword, returnType, name,
typeParameters, parameters, semicolon);
@override
FunctionTypedFormalParameter functionTypedFormalParameter(
Comment comment,
List<Annotation> metadata,
TypeAnnotation returnType,
SimpleIdentifier identifier,
TypeParameterList typeParameters,
FormalParameterList parameters) =>
new FunctionTypedFormalParameterImpl(comment, metadata, null, null,
returnType, identifier, typeParameters, parameters, null);
@override
FunctionTypedFormalParameter functionTypedFormalParameter2(
{Comment comment,
List<Annotation> metadata,
Token covariantKeyword,
Token requiredKeyword,
TypeAnnotation returnType,
@required SimpleIdentifier identifier,
TypeParameterList typeParameters,
@required FormalParameterList parameters,
Token question}) =>
new FunctionTypedFormalParameterImpl(
comment,
metadata,
covariantKeyword,
requiredKeyword,
returnType,
identifier,
typeParameters,
parameters,
question);
@override
GenericFunctionType genericFunctionType(
TypeAnnotation returnType,
Token functionKeyword,
TypeParameterList typeParameters,
FormalParameterList parameters,
{Token question}) =>
new GenericFunctionTypeImpl(
returnType, functionKeyword, typeParameters, parameters,
question: question);
@override
GenericTypeAlias genericTypeAlias(
Comment comment,
List<Annotation> metadata,
Token typedefKeyword,
SimpleIdentifier name,
TypeParameterList typeParameters,
Token equals,
GenericFunctionType functionType,
Token semicolon) =>
new GenericTypeAliasImpl(comment, metadata, typedefKeyword, name,
typeParameters, equals, functionType, semicolon);
@override
HideCombinator hideCombinator(
Token keyword, List<SimpleIdentifier> hiddenNames) =>
new HideCombinatorImpl(keyword, hiddenNames);
@override
IfElement ifElement(
{Token ifKeyword,
Token leftParenthesis,
Expression condition,
Token rightParenthesis,
CollectionElement thenElement,
Token elseKeyword,
CollectionElement elseElement}) =>
new IfElementImpl(ifKeyword, leftParenthesis, condition, rightParenthesis,
thenElement, elseKeyword, elseElement);
@override
IfStatement ifStatement(
Token ifKeyword,
Token leftParenthesis,
Expression condition,
Token rightParenthesis,
Statement thenStatement,
Token elseKeyword,
Statement elseStatement) =>
new IfStatementImpl(ifKeyword, leftParenthesis, condition,
rightParenthesis, thenStatement, elseKeyword, elseStatement);
@override
ImplementsClause implementsClause(
Token implementsKeyword, List<TypeName> interfaces) =>
new ImplementsClauseImpl(implementsKeyword, interfaces);
@override
ImportDirective importDirective(
Comment comment,
List<Annotation> metadata,
Token keyword,
StringLiteral libraryUri,
List<Configuration> configurations,
Token deferredKeyword,
Token asKeyword,
SimpleIdentifier prefix,
List<Combinator> combinators,
Token semicolon) =>
new ImportDirectiveImpl(
comment,
metadata,
keyword,
libraryUri,
configurations,
deferredKeyword,
asKeyword,
prefix,
combinators,
semicolon);
@override
IndexExpression indexExpressionForCascade(Token period, Token leftBracket,
Expression index, Token rightBracket) =>
new IndexExpressionImpl.forCascade(
period, leftBracket, index, rightBracket);
@override
IndexExpression indexExpressionForTarget(Expression target, Token leftBracket,
Expression index, Token rightBracket) =>
new IndexExpressionImpl.forTarget(
target, leftBracket, index, rightBracket);
@override
InstanceCreationExpression instanceCreationExpression(Token keyword,
ConstructorName constructorName, ArgumentList argumentList,
{TypeArgumentList typeArguments}) =>
new InstanceCreationExpressionImpl(keyword, constructorName, argumentList,
typeArguments: typeArguments);
@override
IntegerLiteral integerLiteral(Token literal, int value) =>
new IntegerLiteralImpl(literal, value);
@override
InterpolationExpression interpolationExpression(
Token leftBracket, Expression expression, Token rightBracket) =>
new InterpolationExpressionImpl(leftBracket, expression, rightBracket);
@override
InterpolationString interpolationString(Token contents, String value) =>
new InterpolationStringImpl(contents, value);
@override
IsExpression isExpression(Expression expression, Token isOperator,
Token notOperator, TypeAnnotation type) =>
new IsExpressionImpl(expression, isOperator, notOperator, type);
@override
Label label(SimpleIdentifier label, Token colon) =>
new LabelImpl(label, colon);
@override
LabeledStatement labeledStatement(List<Label> labels, Statement statement) =>
new LabeledStatementImpl(labels, statement);
@override
LibraryDirective libraryDirective(Comment comment, List<Annotation> metadata,
Token libraryKeyword, LibraryIdentifier name, Token semicolon) =>
new LibraryDirectiveImpl(
comment, metadata, libraryKeyword, name, semicolon);
@override
LibraryIdentifier libraryIdentifier(List<SimpleIdentifier> components) =>
new LibraryIdentifierImpl(components);
@override
ListLiteral listLiteral(Token constKeyword, TypeArgumentList typeArguments,
Token leftBracket, List<CollectionElement> elements, Token rightBracket) {
if (elements == null || elements is List<Expression>) {
return new ListLiteralImpl(
constKeyword, typeArguments, leftBracket, elements, rightBracket);
}
return new ListLiteralImpl.experimental(
constKeyword, typeArguments, leftBracket, elements, rightBracket);
}
@override
MapLiteralEntry mapLiteralEntry(
Expression key, Token separator, Expression value) =>
new MapLiteralEntryImpl(key, separator, value);
@override
MethodDeclaration methodDeclaration(
Comment comment,
List<Annotation> metadata,
Token externalKeyword,
Token modifierKeyword,
TypeAnnotation returnType,
Token propertyKeyword,
Token operatorKeyword,
SimpleIdentifier name,
TypeParameterList typeParameters,
FormalParameterList parameters,
FunctionBody body) =>
new MethodDeclarationImpl(
comment,
metadata,
externalKeyword,
modifierKeyword,
returnType,
propertyKeyword,
operatorKeyword,
name,
typeParameters,
parameters,
body);
@override
MethodInvocation methodInvocation(
Expression target,
Token operator,
SimpleIdentifier methodName,
TypeArgumentList typeArguments,
ArgumentList argumentList) =>
new MethodInvocationImpl(
target, operator, methodName, typeArguments, argumentList);
@override
MixinDeclaration mixinDeclaration(
Comment comment,
List<Annotation> metadata,
Token mixinKeyword,
SimpleIdentifier name,
TypeParameterList typeParameters,
OnClause onClause,
ImplementsClause implementsClause,
Token leftBracket,
List<ClassMember> members,
Token rightBracket) =>
new MixinDeclarationImpl(
comment,
metadata,
mixinKeyword,
name,
typeParameters,
onClause,
implementsClause,
leftBracket,
members,
rightBracket);
@override
NamedExpression namedExpression(Label name, Expression expression) =>
new NamedExpressionImpl(name, expression);
@override
NativeClause nativeClause(Token nativeKeyword, StringLiteral name) =>
new NativeClauseImpl(nativeKeyword, name);
@override
NativeFunctionBody nativeFunctionBody(
Token nativeKeyword, StringLiteral stringLiteral, Token semicolon) =>
new NativeFunctionBodyImpl(nativeKeyword, stringLiteral, semicolon);
@override
NodeList<E> nodeList<E extends AstNode>(AstNode owner, [List<E> elements]) =>
new NodeListImpl<E>(owner as AstNodeImpl, elements);
@override
NullLiteral nullLiteral(Token literal) => new NullLiteralImpl(literal);
@override
OnClause onClause(Token onKeyword, List<TypeName> superclassConstraints) =>
new OnClauseImpl(onKeyword, superclassConstraints);
@override
ParenthesizedExpression parenthesizedExpression(Token leftParenthesis,
Expression expression, Token rightParenthesis) =>
new ParenthesizedExpressionImpl(
leftParenthesis, expression, rightParenthesis);
@override
PartDirective partDirective(Comment comment, List<Annotation> metadata,
Token partKeyword, StringLiteral partUri, Token semicolon) =>
new PartDirectiveImpl(comment, metadata, partKeyword, partUri, semicolon);
@override
PartOfDirective partOfDirective(
Comment comment,
List<Annotation> metadata,
Token partKeyword,
Token ofKeyword,
StringLiteral uri,
LibraryIdentifier libraryName,
Token semicolon) =>
new PartOfDirectiveImpl(comment, metadata, partKeyword, ofKeyword, uri,
libraryName, semicolon);
@override
PostfixExpression postfixExpression(Expression operand, Token operator) =>
new PostfixExpressionImpl(operand, operator);
@override
PrefixedIdentifier prefixedIdentifier(
SimpleIdentifier prefix, Token period, SimpleIdentifier identifier) =>
new PrefixedIdentifierImpl(prefix, period, identifier);
@override
PrefixExpression prefixExpression(Token operator, Expression operand) =>
new PrefixExpressionImpl(operator, operand);
@override
PropertyAccess propertyAccess(
Expression target, Token operator, SimpleIdentifier propertyName) =>
new PropertyAccessImpl(target, operator, propertyName);
@override
RedirectingConstructorInvocation redirectingConstructorInvocation(
Token thisKeyword,
Token period,
SimpleIdentifier constructorName,
ArgumentList argumentList) =>
new RedirectingConstructorInvocationImpl(
thisKeyword, period, constructorName, argumentList);
@override
RethrowExpression rethrowExpression(Token rethrowKeyword) =>
new RethrowExpressionImpl(rethrowKeyword);
@override
ReturnStatement returnStatement(
Token returnKeyword, Expression expression, Token semicolon) =>
new ReturnStatementImpl(returnKeyword, expression, semicolon);
@override
ScriptTag scriptTag(Token scriptTag) => new ScriptTagImpl(scriptTag);
@override
SetOrMapLiteral setOrMapLiteral(
{Token constKeyword,
TypeArgumentList typeArguments,
Token leftBracket,
List<CollectionElement> elements,
Token rightBracket}) =>
new SetOrMapLiteralImpl(
constKeyword, typeArguments, leftBracket, elements, rightBracket);
@override
ShowCombinator showCombinator(
Token keyword, List<SimpleIdentifier> shownNames) =>
new ShowCombinatorImpl(keyword, shownNames);
@override
SimpleFormalParameter simpleFormalParameter(
Comment comment,
List<Annotation> metadata,
Token keyword,
TypeAnnotation type,
SimpleIdentifier identifier) =>
new SimpleFormalParameterImpl(
comment, metadata, null, null, keyword, type, identifier);
@override
SimpleFormalParameter simpleFormalParameter2(
{Comment comment,
List<Annotation> metadata,
Token covariantKeyword,
Token requiredKeyword,
Token keyword,
TypeAnnotation type,
@required SimpleIdentifier identifier}) =>
new SimpleFormalParameterImpl(comment, metadata, covariantKeyword,
requiredKeyword, keyword, type, identifier);
@override
SimpleIdentifier simpleIdentifier(Token token, {bool isDeclaration: false}) {
if (isDeclaration) {
return new DeclaredSimpleIdentifier(token);
}
return new SimpleIdentifierImpl(token);
}
@override
SimpleStringLiteral simpleStringLiteral(Token literal, String value) =>
new SimpleStringLiteralImpl(literal, value);
@override
SpreadElement spreadElement({Token spreadOperator, Expression expression}) =>
new SpreadElementImpl(spreadOperator, expression);
@override
StringInterpolation stringInterpolation(
List<InterpolationElement> elements) =>
new StringInterpolationImpl(elements);
@override
SuperConstructorInvocation superConstructorInvocation(
Token superKeyword,
Token period,
SimpleIdentifier constructorName,
ArgumentList argumentList) =>
new SuperConstructorInvocationImpl(
superKeyword, period, constructorName, argumentList);
@override
SuperExpression superExpression(Token superKeyword) =>
new SuperExpressionImpl(superKeyword);
@override
SwitchCase switchCase(List<Label> labels, Token keyword,
Expression expression, Token colon, List<Statement> statements) =>
new SwitchCaseImpl(labels, keyword, expression, colon, statements);
@override
SwitchDefault switchDefault(List<Label> labels, Token keyword, Token colon,
List<Statement> statements) =>
new SwitchDefaultImpl(labels, keyword, colon, statements);
@override
SwitchStatement switchStatement(
Token switchKeyword,
Token leftParenthesis,
Expression expression,
Token rightParenthesis,
Token leftBracket,
List<SwitchMember> members,
Token rightBracket) =>
new SwitchStatementImpl(switchKeyword, leftParenthesis, expression,
rightParenthesis, leftBracket, members, rightBracket);
@override
SymbolLiteral symbolLiteral(Token poundSign, List<Token> components) =>
new SymbolLiteralImpl(poundSign, components);
@override
ThisExpression thisExpression(Token thisKeyword) =>
new ThisExpressionImpl(thisKeyword);
@override
ThrowExpression throwExpression(Token throwKeyword, Expression expression) =>
new ThrowExpressionImpl(throwKeyword, expression);
@override
TopLevelVariableDeclaration topLevelVariableDeclaration(
Comment comment,
List<Annotation> metadata,
VariableDeclarationList variableList,
Token semicolon) =>
new TopLevelVariableDeclarationImpl(
comment, metadata, variableList, semicolon);
@override
TryStatement tryStatement(
Token tryKeyword,
Block body,
List<CatchClause> catchClauses,
Token finallyKeyword,
Block finallyBlock) =>
new TryStatementImpl(
tryKeyword, body, catchClauses, finallyKeyword, finallyBlock);
@override
TypeArgumentList typeArgumentList(Token leftBracket,
List<TypeAnnotation> arguments, Token rightBracket) =>
new TypeArgumentListImpl(leftBracket, arguments, rightBracket);
@override
TypeName typeName(Identifier name, TypeArgumentList typeArguments,
{Token question}) =>
new TypeNameImpl(name, typeArguments, question: question);
@override
TypeParameter typeParameter(Comment comment, List<Annotation> metadata,
SimpleIdentifier name, Token extendsKeyword, TypeAnnotation bound) =>
new TypeParameterImpl(comment, metadata, name, extendsKeyword, bound);
@override
TypeParameterList typeParameterList(Token leftBracket,
List<TypeParameter> typeParameters, Token rightBracket) =>
new TypeParameterListImpl(leftBracket, typeParameters, rightBracket);
@override
VariableDeclaration variableDeclaration(
SimpleIdentifier name, Token equals, Expression initializer) =>
new VariableDeclarationImpl(name, equals, initializer);
@override
VariableDeclarationList variableDeclarationList(
Comment comment,
List<Annotation> metadata,
Token keyword,
TypeAnnotation type,
List<VariableDeclaration> variables) =>
new VariableDeclarationListImpl(
comment, metadata, null, keyword, type, variables);
@override
VariableDeclarationList variableDeclarationList2(
{Comment comment,
List<Annotation> metadata,
Token lateKeyword,
Token keyword,
TypeAnnotation type,
List<VariableDeclaration> variables}) {
return new VariableDeclarationListImpl(
comment, metadata, lateKeyword, keyword, type, variables);
}
@override
VariableDeclarationStatement variableDeclarationStatement(
VariableDeclarationList variableList, Token semicolon) =>
new VariableDeclarationStatementImpl(variableList, semicolon);
@override
WhileStatement whileStatement(Token whileKeyword, Token leftParenthesis,
Expression condition, Token rightParenthesis, Statement body) =>
new WhileStatementImpl(
whileKeyword, leftParenthesis, condition, rightParenthesis, body);
@override
WithClause withClause(Token withKeyword, List<TypeName> mixinTypes) =>
new WithClauseImpl(withKeyword, mixinTypes);
@override
YieldStatement yieldStatement(Token yieldKeyword, Token star,
Expression expression, Token semicolon) =>
new YieldStatementImpl(yieldKeyword, star, expression, semicolon);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/ast/constant_evaluator.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:collection';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
/**
* Instances of the class [ConstantEvaluator] evaluate constant expressions to
* produce their compile-time value.
*
* According to the Dart Language Specification:
*
* > A constant expression is one of the following:
* >
* > * A literal number.
* > * A literal boolean.
* > * A literal string where any interpolated expression is a compile-time
* > constant that evaluates to a numeric, string or boolean value or to
* > **null**.
* > * A literal symbol.
* > * **null**.
* > * A qualified reference to a static constant variable.
* > * An identifier expression that denotes a constant variable, class or type
* > alias.
* > * A constant constructor invocation.
* > * A constant list literal.
* > * A constant map literal.
* > * A simple or qualified identifier denoting a top-level function or a
* > static method.
* > * A parenthesized expression _(e)_ where _e_ is a constant expression.
* > * <span>
* > An expression of the form <i>identical(e<sub>1</sub>, e<sub>2</sub>)</i>
* > where <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> are constant
* > expressions and <i>identical()</i> is statically bound to the predefined
* > dart function <i>identical()</i> discussed above.
* > </span>
* > * <span>
* > An expression of one of the forms <i>e<sub>1</sub> == e<sub>2</sub></i>
* > or <i>e<sub>1</sub> != e<sub>2</sub></i> where <i>e<sub>1</sub></i> and
* > <i>e<sub>2</sub></i> are constant expressions that evaluate to a
* > numeric, string or boolean value.
* > </span>
* > * <span>
* > An expression of one of the forms <i>!e</i>, <i>e<sub>1</sub> &&
* > e<sub>2</sub></i> or <i>e<sub>1</sub> || e<sub>2</sub></i>, where
* > <i>e</i>, <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> are constant
* > expressions that evaluate to a boolean value.
* > </span>
* > * <span>
* > An expression of one of the forms <i>~e</i>, <i>e<sub>1</sub> ^
* > e<sub>2</sub></i>, <i>e<sub>1</sub> & e<sub>2</sub></i>,
* > <i>e<sub>1</sub> | e<sub>2</sub></i>, <i>e<sub>1</sub> >>
* > e<sub>2</sub></i> or <i>e<sub>1</sub> << e<sub>2</sub></i>, where
* > <i>e</i>, <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> are constant
* > expressions that evaluate to an integer value or to <b>null</b>.
* > </span>
* > * <span>
* > An expression of one of the forms <i>-e</i>, <i>e<sub>1</sub>
* > -e<sub>2</sub></i>, <i>e<sub>1</sub> * e<sub>2</sub></i>,
* > <i>e<sub>1</sub> / e<sub>2</sub></i>, <i>e<sub>1</sub> ~/
* > e<sub>2</sub></i>, <i>e<sub>1</sub> > e<sub>2</sub></i>,
* > <i>e<sub>1</sub> < e<sub>2</sub></i>, <i>e<sub>1</sub> >=
* > e<sub>2</sub></i>, <i>e<sub>1</sub> <= e<sub>2</sub></i> or
* > <i>e<sub>1</sub> % e<sub>2</sub></i>, where <i>e</i>,
* > <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> are constant expressions
* > that evaluate to a numeric value or to <b>null</b>.
* > </span>
* > * <span>
* > An expression of one the form <i>e<sub>1</sub> + e<sub>2</sub></i>,
* > <i>e<sub>1</sub> -e<sub>2</sub></i> where <i>e<sub>1</sub> and
* > e<sub>2</sub></i> are constant expressions that evaluate to a numeric or
* > string value or to <b>null</b>.
* > </span>
* > * <span>
* > An expression of the form <i>e<sub>1</sub> ? e<sub>2</sub> :
* > e<sub>3</sub></i> where <i>e<sub>1</sub></i>, <i>e<sub>2</sub></i> and
* > <i>e<sub>3</sub></i> are constant expressions, and <i>e<sub>1</sub></i>
* > evaluates to a boolean value.
* > </span>
*
* However, this comment is now at least a little bit out of sync with the spec.
*
* The values returned by instances of this class are therefore `null` and
* instances of the classes `Boolean`, `BigInteger`, `Double`, `String`, and
* `DartObject`.
*
* In addition, this class defines several values that can be returned to
* indicate various conditions encountered during evaluation. These are
* documented with the static fields that define those values.
*/
class ConstantEvaluator extends GeneralizingAstVisitor<Object> {
/**
* The value returned for expressions (or non-expression nodes) that are not
* compile-time constant expressions.
*/
static Object NOT_A_CONSTANT = new Object();
@override
Object visitAdjacentStrings(AdjacentStrings node) {
StringBuffer buffer = new StringBuffer();
for (StringLiteral string in node.strings) {
Object value = string.accept(this);
if (identical(value, NOT_A_CONSTANT)) {
return value;
}
buffer.write(value);
}
return buffer.toString();
}
@override
Object visitBinaryExpression(BinaryExpression node) {
Object leftOperand = node.leftOperand.accept(this);
if (identical(leftOperand, NOT_A_CONSTANT)) {
return leftOperand;
}
Object rightOperand = node.rightOperand.accept(this);
if (identical(rightOperand, NOT_A_CONSTANT)) {
return rightOperand;
}
while (true) {
if (node.operator.type == TokenType.AMPERSAND) {
// integer or {@code null}
if (leftOperand is int && rightOperand is int) {
return leftOperand & rightOperand;
}
} else if (node.operator.type == TokenType.AMPERSAND_AMPERSAND) {
// boolean or {@code null}
if (leftOperand is bool && rightOperand is bool) {
return leftOperand && rightOperand;
}
} else if (node.operator.type == TokenType.BANG_EQ) {
// numeric, string, boolean, or {@code null}
if (leftOperand is bool && rightOperand is bool) {
return leftOperand != rightOperand;
} else if (leftOperand is num && rightOperand is num) {
return leftOperand != rightOperand;
} else if (leftOperand is String && rightOperand is String) {
return leftOperand != rightOperand;
}
} else if (node.operator.type == TokenType.BAR) {
// integer or {@code null}
if (leftOperand is int && rightOperand is int) {
return leftOperand | rightOperand;
}
} else if (node.operator.type == TokenType.BAR_BAR) {
// boolean or {@code null}
if (leftOperand is bool && rightOperand is bool) {
return leftOperand || rightOperand;
}
} else if (node.operator.type == TokenType.CARET) {
// integer or {@code null}
if (leftOperand is int && rightOperand is int) {
return leftOperand ^ rightOperand;
}
} else if (node.operator.type == TokenType.EQ_EQ) {
// numeric, string, boolean, or {@code null}
if (leftOperand is bool && rightOperand is bool) {
return leftOperand == rightOperand;
} else if (leftOperand is num && rightOperand is num) {
return leftOperand == rightOperand;
} else if (leftOperand is String && rightOperand is String) {
return leftOperand == rightOperand;
}
} else if (node.operator.type == TokenType.GT) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand.compareTo(rightOperand) > 0;
}
} else if (node.operator.type == TokenType.GT_EQ) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand.compareTo(rightOperand) >= 0;
}
} else if (node.operator.type == TokenType.GT_GT) {
// integer or {@code null}
if (leftOperand is int && rightOperand is int) {
return leftOperand >> rightOperand;
}
} else if (node.operator.type == TokenType.LT) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand.compareTo(rightOperand) < 0;
}
} else if (node.operator.type == TokenType.LT_EQ) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand.compareTo(rightOperand) <= 0;
}
} else if (node.operator.type == TokenType.LT_LT) {
// integer or {@code null}
if (leftOperand is int && rightOperand is int) {
return leftOperand << rightOperand;
}
} else if (node.operator.type == TokenType.MINUS) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand - rightOperand;
}
} else if (node.operator.type == TokenType.PERCENT) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand.remainder(rightOperand);
}
} else if (node.operator.type == TokenType.PLUS) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand + rightOperand;
}
if (leftOperand is String && rightOperand is String) {
return leftOperand + rightOperand;
}
} else if (node.operator.type == TokenType.STAR) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand * rightOperand;
}
} else if (node.operator.type == TokenType.SLASH) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand / rightOperand;
}
} else if (node.operator.type == TokenType.TILDE_SLASH) {
// numeric or {@code null}
if (leftOperand is num && rightOperand is num) {
return leftOperand ~/ rightOperand;
}
}
break;
}
// TODO(brianwilkerson) This doesn't handle numeric conversions.
return visitExpression(node);
}
@override
Object visitBooleanLiteral(BooleanLiteral node) => node.value ? true : false;
@override
Object visitDoubleLiteral(DoubleLiteral node) => node.value;
@override
Object visitIntegerLiteral(IntegerLiteral node) => node.value;
@override
Object visitInterpolationExpression(InterpolationExpression node) {
Object value = node.expression.accept(this);
if (value == null || value is bool || value is String || value is num) {
return value;
}
return NOT_A_CONSTANT;
}
@override
Object visitInterpolationString(InterpolationString node) => node.value;
@override
Object visitListLiteral(ListLiteral node) {
List<Object> list = new List<Object>();
for (CollectionElement element in node.elements) {
if (element is Expression) {
Object value = element.accept(this);
if (identical(value, NOT_A_CONSTANT)) {
return value;
}
list.add(value);
} else {
// There are a lot of constants that this class does not support, so we
// didn't add support for the extended collection support.
return NOT_A_CONSTANT;
}
}
return list;
}
@override
Object visitMethodInvocation(MethodInvocation node) => visitNode(node);
@override
Object visitNode(AstNode node) => NOT_A_CONSTANT;
@override
Object visitNullLiteral(NullLiteral node) => null;
@override
Object visitParenthesizedExpression(ParenthesizedExpression node) =>
node.expression.accept(this);
@override
Object visitPrefixedIdentifier(PrefixedIdentifier node) =>
_getConstantValue(null);
@override
Object visitPrefixExpression(PrefixExpression node) {
Object operand = node.operand.accept(this);
if (identical(operand, NOT_A_CONSTANT)) {
return operand;
}
while (true) {
if (node.operator.type == TokenType.BANG) {
if (identical(operand, true)) {
return false;
} else if (identical(operand, false)) {
return true;
}
} else if (node.operator.type == TokenType.TILDE) {
if (operand is int) {
return ~operand;
}
} else if (node.operator.type == TokenType.MINUS) {
if (operand == null) {
return null;
} else if (operand is num) {
return -operand;
}
} else {}
break;
}
return NOT_A_CONSTANT;
}
@override
Object visitPropertyAccess(PropertyAccess node) => _getConstantValue(null);
@override
Object visitSetOrMapLiteral(SetOrMapLiteral node) {
// There are a lot of constants that this class does not support, so we
// didn't add support for set literals. As a result, this assumes that we're
// looking at a map literal until we prove otherwise.
Map<String, Object> map = new HashMap<String, Object>();
for (CollectionElement element in node.elements) {
if (element is MapLiteralEntry) {
Object key = element.key.accept(this);
Object value = element.value.accept(this);
if (key is String && !identical(value, NOT_A_CONSTANT)) {
map[key] = value;
} else {
return NOT_A_CONSTANT;
}
} else {
// There are a lot of constants that this class does not support, so
// we didn't add support for the extended collection support.
return NOT_A_CONSTANT;
}
}
return map;
}
@override
Object visitSimpleIdentifier(SimpleIdentifier node) =>
_getConstantValue(null);
@override
Object visitSimpleStringLiteral(SimpleStringLiteral node) => node.value;
@override
Object visitStringInterpolation(StringInterpolation node) {
StringBuffer buffer = new StringBuffer();
for (InterpolationElement element in node.elements) {
Object value = element.accept(this);
if (identical(value, NOT_A_CONSTANT)) {
return value;
}
buffer.write(value);
}
return buffer.toString();
}
@override
Object visitSymbolLiteral(SymbolLiteral node) {
// TODO(brianwilkerson) This isn't optimal because a Symbol is not a String.
StringBuffer buffer = new StringBuffer();
for (Token component in node.components) {
if (buffer.length > 0) {
buffer.writeCharCode(0x2E);
}
buffer.write(component.lexeme);
}
return buffer.toString();
}
/**
* Return the constant value of the static constant represented by the given
* [element].
*/
Object _getConstantValue(Element element) {
// TODO(brianwilkerson) Implement this
// if (element is FieldElement) {
// FieldElement field = element;
// if (field.isStatic && field.isConst) {
// //field.getConstantValue();
// }
// // } else if (element instanceof VariableElement) {
// // VariableElement variable = (VariableElement) element;
// // if (variable.isStatic() && variable.isConst()) {
// // //variable.getConstantValue();
// // }
// }
return NOT_A_CONSTANT;
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/ast/token.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:analyzer/dart/ast/token.dart';
export 'package:front_end/src/scanner/token.dart'
show
BeginToken,
CommentToken,
DocumentationCommentToken,
KeywordToken,
SimpleToken,
StringToken,
SyntheticBeginToken,
SyntheticKeywordToken,
SyntheticStringToken,
SyntheticToken,
TokenClass;
/**
* Return the binary operator that is invoked by the given compound assignment
* [operator]. Throw [StateError] if the assignment [operator] does not
* correspond to a binary operator.
*/
TokenType operatorFromCompoundAssignment(TokenType operator) {
if (operator == TokenType.AMPERSAND_EQ) {
return TokenType.AMPERSAND;
} else if (operator == TokenType.BAR_EQ) {
return TokenType.BAR;
} else if (operator == TokenType.CARET_EQ) {
return TokenType.CARET;
} else if (operator == TokenType.GT_GT_EQ) {
return TokenType.GT_GT;
} else if (operator == TokenType.GT_GT_GT_EQ) {
return TokenType.GT_GT_GT;
} else if (operator == TokenType.LT_LT_EQ) {
return TokenType.LT_LT;
} else if (operator == TokenType.MINUS_EQ) {
return TokenType.MINUS;
} else if (operator == TokenType.PERCENT_EQ) {
return TokenType.PERCENT;
} else if (operator == TokenType.PLUS_EQ) {
return TokenType.PLUS;
} else if (operator == TokenType.SLASH_EQ) {
return TokenType.SLASH;
} else if (operator == TokenType.STAR_EQ) {
return TokenType.STAR;
} else if (operator == TokenType.TILDE_SLASH_EQ) {
return TokenType.TILDE_SLASH;
} else {
throw StateError('Unknown assignment operator: $operator');
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/ast/mixin_super_invoked_names.dart | import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
/// Visitor that collects super-invoked names in a mixin declaration.
class MixinSuperInvokedNamesCollector extends RecursiveAstVisitor<void> {
final Set<String> _names;
MixinSuperInvokedNamesCollector(this._names);
@override
void visitBinaryExpression(BinaryExpression node) {
if (node.leftOperand is SuperExpression) {
_names.add(node.operator.lexeme);
}
super.visitBinaryExpression(node);
}
@override
void visitIndexExpression(IndexExpression node) {
if (node.target is SuperExpression) {
if (node.inGetterContext()) {
_names.add('[]');
}
if (node.inSetterContext()) {
_names.add('[]=');
}
}
super.visitIndexExpression(node);
}
@override
void visitMethodInvocation(MethodInvocation node) {
if (node.target is SuperExpression) {
_names.add(node.methodName.name);
}
super.visitMethodInvocation(node);
}
@override
void visitPrefixExpression(PrefixExpression node) {
if (node.operand is SuperExpression) {
TokenType operatorType = node.operator.type;
if (operatorType == TokenType.MINUS) {
_names.add('unary-');
} else if (operatorType == TokenType.TILDE) {
_names.add('~');
}
}
super.visitPrefixExpression(node);
}
@override
void visitPropertyAccess(PropertyAccess node) {
if (node.target is SuperExpression) {
var name = node.propertyName.name;
if (node.propertyName.inGetterContext()) {
_names.add(name);
}
if (node.propertyName.inSetterContext()) {
_names.add('$name=');
}
}
super.visitPropertyAccess(node);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/type_algebra.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:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/dart/element/type_visitor.dart';
import 'package:analyzer/src/generated/type_system.dart';
import 'package:analyzer/src/summary2/function_type_builder.dart';
import 'package:analyzer/src/summary2/named_type_builder.dart';
/// Generates a fresh copy of the given type parameters, with their bounds
/// substituted to reference the new parameters.
///
/// The returned object contains the fresh type parameter list as well as a
/// mapping to be used for replacing other types to use the new type parameters.
FreshTypeParameters getFreshTypeParameters(
List<TypeParameterElement> typeParameters) {
var freshParameters = new List<TypeParameterElementImpl>.generate(
typeParameters.length,
(i) => new TypeParameterElementImpl(typeParameters[i].name, -1),
growable: true,
);
var map = <TypeParameterElement, DartType>{};
for (int i = 0; i < typeParameters.length; ++i) {
map[typeParameters[i]] = new TypeParameterTypeImpl(freshParameters[i]);
}
var substitution = Substitution.fromMap(map);
for (int i = 0; i < typeParameters.length; ++i) {
var bound = typeParameters[i].bound;
if (bound != null) {
var newBound = substitution.substituteType(bound);
freshParameters[i].bound = newBound;
}
}
return new FreshTypeParameters(freshParameters, substitution);
}
/// Returns a type where all occurrences of the given type parameters have been
/// replaced with the corresponding types.
///
/// This will copy only the sub-terms of [type] that contain substituted
/// variables; all other [DartType] objects will be reused.
///
/// In particular, if no type parameters were substituted, this is guaranteed
/// to return the [type] instance (not a copy), so the caller may use
/// [identical] to efficiently check if a distinct type was created.
DartType substitute(
DartType type,
Map<TypeParameterElement, DartType> substitution,
) {
if (substitution.isEmpty) {
return type;
}
return Substitution.fromMap(substitution).substituteType(type);
}
class FreshTypeParameters {
final List<TypeParameterElement> freshTypeParameters;
final Substitution substitution;
FreshTypeParameters(this.freshTypeParameters, this.substitution);
FunctionType applyToFunctionType(FunctionType type) {
return new FunctionTypeImpl.synthetic(
substitute(type.returnType),
freshTypeParameters,
type.parameters.map((parameter) {
return ParameterElementImpl.synthetic(
parameter.name,
substitute(parameter.type),
// ignore: deprecated_member_use_from_same_package
parameter.parameterKind,
);
}).toList(),
);
}
DartType substitute(DartType type) => substitution.substituteType(type);
}
/// Substitution that is based on the [map].
abstract class MapSubstitution extends Substitution {
const MapSubstitution();
Map<TypeParameterElement, DartType> get map;
}
abstract class Substitution {
static const Substitution empty = _NullSubstitution.instance;
const Substitution();
DartType getSubstitute(TypeParameterElement parameter, bool upperBound);
DartType substituteType(DartType type, {bool contravariant: false}) {
return new _TopSubstitutor(this, contravariant).visit(type);
}
/// Substitutes both variables from [first] and [second], favoring those from
/// [first] if they overlap.
///
/// Neither substitution is applied to the results of the other, so this does
/// *not* correspond to a sequence of two substitutions. For example,
/// combining `{T -> List<G>}` with `{G -> String}` does not correspond to
/// `{T -> List<String>}` because the result from substituting `T` is not
/// searched for occurrences of `G`.
static Substitution combine(Substitution first, Substitution second) {
if (first == _NullSubstitution.instance) return second;
if (second == _NullSubstitution.instance) return first;
return new _CombinedSubstitution(first, second);
}
/// Substitutes the type parameters on the class of [type] with the
/// type arguments provided in [type].
static Substitution fromInterfaceType(InterfaceType type) {
if (type.typeArguments.isEmpty) {
return _NullSubstitution.instance;
}
return fromPairs(type.element.typeParameters, type.typeArguments);
}
/// Substitutes each parameter to the type it maps to in [map].
static MapSubstitution fromMap(Map<TypeParameterElement, DartType> map) {
if (map.isEmpty) {
return _NullSubstitution.instance;
}
return new _MapSubstitution(map);
}
/// Substitutes the Nth parameter in [parameters] with the Nth type in
/// [types].
static Substitution fromPairs(
List<TypeParameterElement> parameters,
List<DartType> types,
) {
assert(parameters.length == types.length);
if (parameters.isEmpty) {
return _NullSubstitution.instance;
}
return fromMap(
new Map<TypeParameterElement, DartType>.fromIterables(
parameters,
types,
),
);
}
/// Substitutes all occurrences of the given type parameters with the
/// corresponding upper or lower bound, depending on the variance of the
/// context where it occurs.
///
/// For example the type `(T) => T` with the bounds `bottom <: T <: num`
/// becomes `(bottom) => num` (in this example, `num` is the upper bound,
/// and `bottom` is the lower bound).
///
/// This is a way to obtain an upper bound for a type while eliminating all
/// references to certain type variables.
static Substitution fromUpperAndLowerBounds(
Map<TypeParameterElement, DartType> upper,
Map<TypeParameterElement, DartType> lower,
) {
if (upper.isEmpty && lower.isEmpty) {
return _NullSubstitution.instance;
}
return new _UpperLowerBoundsSubstitution(upper, lower);
}
}
class _CombinedSubstitution extends Substitution {
final Substitution first;
final Substitution second;
_CombinedSubstitution(this.first, this.second);
@override
DartType getSubstitute(TypeParameterElement parameter, bool upperBound) {
return first.getSubstitute(parameter, upperBound) ??
second.getSubstitute(parameter, upperBound);
}
}
class _FreshTypeParametersSubstitutor extends _TypeSubstitutor {
final Map<TypeParameterElement, DartType> substitution = {};
_FreshTypeParametersSubstitutor(_TypeSubstitutor outer) : super(outer);
@override
List<TypeParameterElement> freshTypeParameters(
List<TypeParameterElement> elements) {
if (elements.isEmpty) {
return const <TypeParameterElement>[];
}
var freshElements = List<TypeParameterElement>(elements.length);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var freshElement = TypeParameterElementImpl(element.name, -1);
freshElements[i] = freshElement;
var freshType = TypeParameterTypeImpl(freshElement);
freshElement.type = freshType;
substitution[element] = freshType;
}
for (var i = 0; i < freshElements.length; i++) {
var element = elements[i];
if (element.bound != null) {
TypeParameterElementImpl freshElement = freshElements[i];
freshElement.bound = visit(element.bound);
}
}
return freshElements;
}
DartType lookup(TypeParameterElement parameter, bool upperBound) {
return substitution[parameter];
}
}
class _MapSubstitution extends MapSubstitution {
final Map<TypeParameterElement, DartType> map;
_MapSubstitution(this.map);
DartType getSubstitute(TypeParameterElement parameter, bool upperBound) {
return map[parameter];
}
@override
String toString() => '_MapSubstitution($map)';
}
class _NullSubstitution extends MapSubstitution {
static const _NullSubstitution instance = const _NullSubstitution();
const _NullSubstitution();
@override
Map<TypeParameterElement, DartType> get map => const {};
DartType getSubstitute(TypeParameterElement parameter, bool upperBound) {
return new TypeParameterTypeImpl(parameter);
}
@override
DartType substituteType(DartType type, {bool contravariant: false}) => type;
@override
String toString() => "Substitution.empty";
}
class _TopSubstitutor extends _TypeSubstitutor {
final Substitution substitution;
_TopSubstitutor(this.substitution, bool contravariant) : super(null) {
if (contravariant) {
invertVariance();
}
}
List<TypeParameterElement> freshTypeParameters(
List<TypeParameterElement> parameters) {
throw 'Create a fresh environment first';
}
@override
DartType lookup(TypeParameterElement parameter, bool upperBound) {
return substitution.getSubstitute(parameter, upperBound);
}
}
abstract class _TypeSubstitutor extends DartTypeVisitor<DartType> {
final _TypeSubstitutor outer;
bool covariantContext = true;
/// The number of times a variable from this environment has been used in
/// a substitution.
///
/// There is a strict requirement that we must return the same instance for
/// types that were not altered by the substitution. This counter lets us
/// check quickly if anything happened in a substitution.
int useCounter = 0;
_TypeSubstitutor(this.outer) {
covariantContext = outer == null ? true : outer.covariantContext;
}
void bumpCountersUntil(_TypeSubstitutor target) {
var substitutor = this;
while (substitutor != target) {
substitutor.useCounter++;
substitutor = substitutor.outer;
}
target.useCounter++;
}
List<TypeParameterElement> freshTypeParameters(
List<TypeParameterElement> elements);
DartType getSubstitute(TypeParameterElement parameter) {
var environment = this;
while (environment != null) {
var replacement = environment.lookup(parameter, covariantContext);
if (replacement != null) {
bumpCountersUntil(environment);
return replacement;
}
environment = environment.outer;
}
return null;
}
void invertVariance() {
covariantContext = !covariantContext;
}
DartType lookup(TypeParameterElement parameter, bool upperBound);
_FreshTypeParametersSubstitutor newInnerEnvironment() {
return new _FreshTypeParametersSubstitutor(this);
}
DartType visit(DartType type) {
return DartTypeVisitor.visit(type, this);
}
@override
DartType visitBottomType(BottomTypeImpl type) => type;
@override
DartType visitDynamicType(DynamicTypeImpl type) => type;
@override
DartType visitFunctionType(FunctionType type) {
// This is a bit tricky because we have to generate fresh type parameters
// in order to change the bounds. At the same time, if the function type
// was unaltered, we have to return the [type] object (not a copy!).
// Substituting a type for a fresh type variable should not be confused
// with a "real" substitution.
//
// Create an inner environment to generate fresh type parameters. The use
// counter on the inner environment tells if the fresh type parameters have
// any uses, but does not tell if the resulting function type is distinct.
// Our own use counter will get incremented if something from our
// environment has been used inside the function.
int before = this.useCounter;
var inner = this;
var typeFormals = type.typeFormals;
if (typeFormals.isNotEmpty) {
inner = newInnerEnvironment();
typeFormals = inner.freshTypeParameters(typeFormals);
}
// Invert the variance when translating parameters.
inner.invertVariance();
var parameters = type.parameters.map((parameter) {
var type = inner.visit(parameter.type);
return _parameterElement(parameter, type);
}).toList();
inner.invertVariance();
var returnType = inner.visit(type.returnType);
var typeArguments = type.typeArguments.map(visit).toList();
if (this.useCounter == before) return type;
return FunctionTypeImpl.synthetic(returnType, typeFormals, parameters,
element: type.element, typeArguments: typeArguments);
}
@override
DartType visitFunctionTypeBuilder(FunctionTypeBuilder type) {
// This is a bit tricky because we have to generate fresh type parameters
// in order to change the bounds. At the same time, if the function type
// was unaltered, we have to return the [type] object (not a copy!).
// Substituting a type for a fresh type variable should not be confused
// with a "real" substitution.
//
// Create an inner environment to generate fresh type parameters. The use
// counter on the inner environment tells if the fresh type parameters have
// any uses, but does not tell if the resulting function type is distinct.
// Our own use counter will get incremented if something from our
// environment has been used inside the function.
int before = this.useCounter;
var inner = this;
var typeFormals = type.typeFormals;
if (typeFormals.isNotEmpty) {
inner = newInnerEnvironment();
typeFormals = inner.freshTypeParameters(typeFormals);
}
// Invert the variance when translating parameters.
inner.invertVariance();
var parameters = type.parameters.map((parameter) {
var type = inner.visit(parameter.type);
return _parameterElement(parameter, type);
}).toList();
inner.invertVariance();
var returnType = inner.visit(type.returnType);
if (this.useCounter == before) return type;
return FunctionTypeBuilder(
typeFormals,
parameters,
returnType,
type.nullabilitySuffix,
);
}
@override
DartType visitInterfaceType(InterfaceType type) {
if (type.typeArguments.isEmpty) {
return type;
}
int before = useCounter;
var typeArguments = type.typeArguments.map(visit).toList();
if (useCounter == before) {
return type;
}
return new InterfaceTypeImpl.explicit(type.element, typeArguments,
nullabilitySuffix: (type as TypeImpl).nullabilitySuffix);
}
@override
DartType visitNamedTypeBuilder(NamedTypeBuilder type) {
if (type.arguments.isEmpty) {
return type;
}
int before = useCounter;
var arguments = type.arguments.map(visit).toList();
if (useCounter == before) {
return type;
}
return new NamedTypeBuilder(
type.element,
arguments,
type.nullabilitySuffix,
);
}
@override
DartType visitTypeParameterType(TypeParameterType type) {
return getSubstitute(type.element) ?? type;
}
@override
DartType visitUnknownInferredType(UnknownInferredType type) => type;
@override
DartType visitVoidType(VoidType type) => type;
static ParameterElementImpl _parameterElement(
ParameterElement parameter,
DartType type,
) {
var result = ParameterElementImpl.synthetic(
parameter.name,
type,
// ignore: deprecated_member_use_from_same_package
parameter.parameterKind,
);
result.isExplicitlyCovariant = parameter.isCovariant;
return result;
}
}
class _UpperLowerBoundsSubstitution extends Substitution {
final Map<TypeParameterElement, DartType> upper;
final Map<TypeParameterElement, DartType> lower;
_UpperLowerBoundsSubstitution(this.upper, this.lower);
DartType getSubstitute(TypeParameterElement parameter, bool upperBound) {
return upperBound ? upper[parameter] : lower[parameter];
}
@override
String toString() => '_UpperLowerBoundsSubstitution($upper, $lower)';
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/element.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'dart:math' show min;
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/constant/compute.dart';
import 'package:analyzer/src/dart/constant/evaluation.dart';
import 'package:analyzer/src/dart/constant/value.dart';
import 'package:analyzer/src/dart/element/handle.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/dart/element/type_algebra.dart';
import 'package:analyzer/src/generated/constant.dart' show EvaluationResultImpl;
import 'package:analyzer/src/generated/engine.dart'
show AnalysisContext, AnalysisEngine, AnalysisOptionsImpl;
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/sdk.dart' show DartSdk;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/testing/ast_test_factory.dart';
import 'package:analyzer/src/generated/utilities_collection.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary2/linked_unit_context.dart';
import 'package:analyzer/src/summary2/reference.dart';
import 'package:analyzer/src/util/comment.dart';
import 'package:meta/meta.dart';
/// Assert that the given [object] is null, which in the places where this
/// function is called means that the element is not resynthesized.
void _assertNotResynthesized(Object object) {
// TODO(scheglov) I comment this check for now.
// When we make a decision about switch to the new analysis driver,
// we will need to rework the analysis code to don't call the setters
// or restore / inline it.
// assert(object == null);
}
/// A concrete implementation of a [ClassElement].
abstract class AbstractClassElementImpl extends ElementImpl
implements ClassElement {
/// The type defined by the class.
InterfaceType _thisType;
/// A list containing all of the accessors (getters and setters) contained in
/// this class.
List<PropertyAccessorElement> _accessors;
/// A list containing all of the fields contained in this class.
List<FieldElement> _fields;
/// A list containing all of the methods contained in this class.
List<MethodElement> _methods;
/// Initialize a newly created class element to have the given [name] at the
/// given [offset] in the file that contains the declaration of this element.
AbstractClassElementImpl(String name, int offset) : super(name, offset);
AbstractClassElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created class element to have the given [name].
AbstractClassElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
AbstractClassElementImpl.forSerialized(
CompilationUnitElementImpl enclosingUnit)
: super.forSerialized(enclosingUnit);
@override
List<PropertyAccessorElement> get accessors {
return _accessors ?? const <PropertyAccessorElement>[];
}
/// Set the accessors contained in this class to the given [accessors].
void set accessors(List<PropertyAccessorElement> accessors) {
for (PropertyAccessorElement accessor in accessors) {
(accessor as PropertyAccessorElementImpl).enclosingElement = this;
}
this._accessors = accessors;
}
@override
String get displayName => name;
@override
List<FieldElement> get fields => _fields ?? const <FieldElement>[];
/// Set the fields contained in this class to the given [fields].
void set fields(List<FieldElement> fields) {
for (FieldElement field in fields) {
(field as FieldElementImpl).enclosingElement = this;
}
this._fields = fields;
}
@override
bool get isDartCoreObject => false;
@override
bool get isEnum => false;
@override
bool get isMixin => false;
@override
ElementKind get kind => ElementKind.CLASS;
@override
List<InterfaceType> get superclassConstraints => const <InterfaceType>[];
@override
InterfaceType get thisType {
if (_thisType == null) {
// TODO(scheglov) `library` is null in low-level unit tests
var nullabilitySuffix = library?.isNonNullableByDefault == true
? NullabilitySuffix.none
: NullabilitySuffix.star;
List<DartType> typeArguments;
if (typeParameters.isNotEmpty) {
typeArguments = typeParameters.map<DartType>((t) {
return t.instantiate(nullabilitySuffix: nullabilitySuffix);
}).toList();
} else {
typeArguments = const <DartType>[];
}
return _thisType = instantiate(
typeArguments: typeArguments,
nullabilitySuffix: nullabilitySuffix,
);
}
return _thisType;
}
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitClassElement(this);
@deprecated
@override
NamedCompilationUnitMember computeNode() {
if (isEnum) {
return getNodeMatching((node) => node is EnumDeclaration);
} else {
return getNodeMatching(
(node) => node is ClassDeclaration || node is ClassTypeAlias);
}
}
@override
ElementImpl getChild(String identifier) {
//
// The casts in this method are safe because the set methods would have
// thrown a CCE if any of the elements in the arrays were not of the
// expected types.
//
for (PropertyAccessorElement accessor in accessors) {
PropertyAccessorElementImpl accessorImpl = accessor;
if (accessorImpl.identifier == identifier) {
return accessorImpl;
}
}
for (FieldElement field in fields) {
FieldElementImpl fieldImpl = field;
if (fieldImpl.identifier == identifier) {
return fieldImpl;
}
}
return null;
}
@override
FieldElement getField(String name) {
for (FieldElement fieldElement in fields) {
if (name == fieldElement.name) {
return fieldElement;
}
}
return null;
}
@override
PropertyAccessorElement getGetter(String getterName) {
int length = accessors.length;
for (int i = 0; i < length; i++) {
PropertyAccessorElement accessor = accessors[i];
if (accessor.isGetter && accessor.name == getterName) {
return accessor;
}
}
return null;
}
@override
MethodElement getMethod(String methodName) {
int length = methods.length;
for (int i = 0; i < length; i++) {
MethodElement method = methods[i];
if (method.name == methodName) {
return method;
}
}
return null;
}
@override
PropertyAccessorElement getSetter(String setterName) {
return getSetterFromAccessors(setterName, accessors);
}
@override
InterfaceType instantiate({
@required List<DartType> typeArguments,
@required NullabilitySuffix nullabilitySuffix,
}) {
if (typeArguments.length != typeParameters.length) {
var ta = 'typeArguments.length (${typeArguments.length})';
var tp = 'typeParameters.length (${typeParameters.length})';
throw ArgumentError('$ta != $tp');
}
return InterfaceTypeImpl.explicit(
this,
typeArguments,
nullabilitySuffix: nullabilitySuffix,
);
}
@override
MethodElement lookUpConcreteMethod(
String methodName, LibraryElement library) =>
_first(getImplementationsOfMethod(this, methodName).where(
(MethodElement method) =>
!method.isAbstract && method.isAccessibleIn(library)));
@override
PropertyAccessorElement lookUpGetter(
String getterName, LibraryElement library) =>
_first(_implementationsOfGetter(getterName).where(
(PropertyAccessorElement getter) => getter.isAccessibleIn(library)));
@override
PropertyAccessorElement lookUpInheritedConcreteGetter(
String getterName, LibraryElement library) =>
_first(_implementationsOfGetter(getterName).where(
(PropertyAccessorElement getter) =>
!getter.isAbstract &&
getter.isAccessibleIn(library) &&
getter.enclosingElement != this));
ExecutableElement lookUpInheritedConcreteMember(
String name, LibraryElement library) {
if (name.endsWith('=')) {
return lookUpInheritedConcreteSetter(name, library);
} else {
return lookUpInheritedConcreteMethod(name, library) ??
lookUpInheritedConcreteGetter(name, library);
}
}
@override
MethodElement lookUpInheritedConcreteMethod(
String methodName, LibraryElement library) =>
_first(getImplementationsOfMethod(this, methodName).where(
(MethodElement method) =>
!method.isAbstract &&
method.isAccessibleIn(library) &&
method.enclosingElement != this));
@override
PropertyAccessorElement lookUpInheritedConcreteSetter(
String setterName, LibraryElement library) =>
_first(_implementationsOfSetter(setterName).where(
(PropertyAccessorElement setter) =>
!setter.isAbstract &&
setter.isAccessibleIn(library) &&
setter.enclosingElement != this));
@override
MethodElement lookUpInheritedMethod(
String methodName, LibraryElement library) =>
_first(getImplementationsOfMethod(this, methodName).where(
(MethodElement method) =>
method.isAccessibleIn(library) &&
method.enclosingElement != this));
@override
MethodElement lookUpMethod(String methodName, LibraryElement library) =>
lookUpMethodInClass(this, methodName, library);
@override
PropertyAccessorElement lookUpSetter(
String setterName, LibraryElement library) =>
_first(_implementationsOfSetter(setterName).where(
(PropertyAccessorElement setter) => setter.isAccessibleIn(library)));
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
safelyVisitChildren(accessors, visitor);
safelyVisitChildren(fields, visitor);
}
/// Return an iterable containing all of the implementations of a getter with
/// the given [getterName] that are defined in this class any any superclass
/// of this class (but not in interfaces).
///
/// The getters that are returned are not filtered in any way. In particular,
/// they can include getters that are not visible in some context. Clients
/// must perform any necessary filtering.
///
/// The getters are returned based on the depth of their defining class; if
/// this class contains a definition of the getter it will occur first, if
/// Object contains a definition of the getter it will occur last.
Iterable<PropertyAccessorElement> _implementationsOfGetter(
String getterName) sync* {
ClassElement classElement = this;
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
while (classElement != null && visitedClasses.add(classElement)) {
PropertyAccessorElement getter = classElement.getGetter(getterName);
if (getter != null) {
yield getter;
}
for (InterfaceType mixin in classElement.mixins.reversed) {
getter = mixin.element?.getGetter(getterName);
if (getter != null) {
yield getter;
}
}
classElement = classElement.supertype?.element;
}
}
/// Return an iterable containing all of the implementations of a setter with
/// the given [setterName] that are defined in this class any any superclass
/// of this class (but not in interfaces).
///
/// The setters that are returned are not filtered in any way. In particular,
/// they can include setters that are not visible in some context. Clients
/// must perform any necessary filtering.
///
/// The setters are returned based on the depth of their defining class; if
/// this class contains a definition of the setter it will occur first, if
/// Object contains a definition of the setter it will occur last.
Iterable<PropertyAccessorElement> _implementationsOfSetter(
String setterName) sync* {
ClassElement classElement = this;
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
while (classElement != null && visitedClasses.add(classElement)) {
PropertyAccessorElement setter = classElement.getSetter(setterName);
if (setter != null) {
yield setter;
}
for (InterfaceType mixin in classElement.mixins.reversed) {
setter = mixin.element?.getSetter(setterName);
if (setter != null) {
yield setter;
}
}
classElement = classElement.supertype?.element;
}
}
/// Return the [AbstractClassElementImpl] of the given [classElement]. May
/// throw an exception if the [AbstractClassElementImpl] cannot be provided
/// (should not happen though).
static AbstractClassElementImpl getImpl(ClassElement classElement) {
if (classElement is ClassElementHandle) {
return getImpl(classElement.actualElement);
}
return classElement as AbstractClassElementImpl;
}
/// Return an iterable containing all of the implementations of a method with
/// the given [methodName] that are defined in this class any any superclass
/// of this class (but not in interfaces).
///
/// The methods that are returned are not filtered in any way. In particular,
/// they can include methods that are not visible in some context. Clients
/// must perform any necessary filtering.
///
/// The methods are returned based on the depth of their defining class; if
/// this class contains a definition of the method it will occur first, if
/// Object contains a definition of the method it will occur last.
static Iterable<MethodElement> getImplementationsOfMethod(
ClassElement classElement, String methodName) sync* {
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
while (classElement != null && visitedClasses.add(classElement)) {
MethodElement method = classElement.getMethod(methodName);
if (method != null) {
yield method;
}
for (InterfaceType mixin in classElement.mixins.reversed) {
method = mixin.element?.getMethod(methodName);
if (method != null) {
yield method;
}
}
classElement = classElement.supertype?.element;
}
}
static PropertyAccessorElement getSetterFromAccessors(
String setterName, List<PropertyAccessorElement> accessors) {
// TODO (jwren) revisit- should we append '=' here or require clients to
// include it?
// Do we need the check for isSetter below?
if (!StringUtilities.endsWithChar(setterName, 0x3D)) {
setterName += '=';
}
for (PropertyAccessorElement accessor in accessors) {
if (accessor.isSetter && accessor.name == setterName) {
return accessor;
}
}
return null;
}
static MethodElement lookUpMethodInClass(
ClassElement classElement, String methodName, LibraryElement library) {
return _first(getImplementationsOfMethod(classElement, methodName)
.where((MethodElement method) => method.isAccessibleIn(library)));
}
/// Return the first element from the given [iterable], or `null` if the
/// iterable is empty.
static E _first<E>(Iterable<E> iterable) {
if (iterable.isEmpty) {
return null;
}
return iterable.first;
}
}
/// For AST nodes that could be in both the getter and setter contexts
/// ([IndexExpression]s and [SimpleIdentifier]s), the additional resolved
/// elements are stored in the AST node, in an [AuxiliaryElements]. Because
/// resolved elements are either statically resolved or resolved using
/// propagated type information, this class is a wrapper for a pair of
/// [ExecutableElement]s, not just a single [ExecutableElement].
class AuxiliaryElements {
/// The element based on static type information, or `null` if the AST
/// structure has not been resolved or if the node could not be resolved.
final ExecutableElement staticElement;
/// Initialize a newly created pair to have both the [staticElement] and
/// `null`.
AuxiliaryElements(this.staticElement, ExecutableElement propagatedElement);
/// The element based on propagated type information, or `null` if the AST
/// structure has not been resolved or if the node could not be resolved.
ExecutableElement get propagatedElement => null;
}
/// An [AbstractClassElementImpl] which is a class.
class ClassElementImpl extends AbstractClassElementImpl
with TypeParameterizedElementMixin, SimplyBoundableMixin {
/// The unlinked representation of the class in the summary.
final UnlinkedClass _unlinkedClass;
/// If this class is resynthesized, whether it has a constant constructor.
bool _hasConstConstructorCached;
/// The superclass of the class, or `null` for [Object].
InterfaceType _supertype;
/// The type defined by the class.
InterfaceType _type;
/// A list containing all of the mixins that are applied to the class being
/// extended in order to derive the superclass of this class.
List<InterfaceType> _mixins;
/// A list containing all of the interfaces that are implemented by this
/// class.
List<InterfaceType> _interfaces;
/// For classes which are not mixin applications, a list containing all of the
/// constructors contained in this class, or `null` if the list of
/// constructors has not yet been built.
///
/// For classes which are mixin applications, the list of constructors is
/// computed on the fly by the [constructors] getter, and this field is
/// `null`.
List<ConstructorElement> _constructors;
/// A flag indicating whether the types associated with the instance members
/// of this class have been inferred.
bool _hasBeenInferred = false;
/// The version of this element. The version is changed when the element is
/// incrementally updated, so that its lists of constructors, accessors and
/// methods might be different.
int version = 0;
/// This callback is set during mixins inference to handle reentrant calls.
List<InterfaceType> Function(ClassElementImpl) linkedMixinInferenceCallback;
/// Initialize a newly created class element to have the given [name] at the
/// given [offset] in the file that contains the declaration of this element.
ClassElementImpl(String name, int offset)
: _unlinkedClass = null,
super(name, offset);
ClassElementImpl.forLinkedNode(CompilationUnitElementImpl enclosing,
Reference reference, AstNode linkedNode)
: _unlinkedClass = null,
super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created class element to have the given [name].
ClassElementImpl.forNode(Identifier name)
: _unlinkedClass = null,
super.forNode(name);
/// Initialize using the given serialized information.
ClassElementImpl.forSerialized(
this._unlinkedClass, CompilationUnitElementImpl enclosingUnit)
: super.forSerialized(enclosingUnit);
@override
List<PropertyAccessorElement> get accessors {
if (_accessors != null) return _accessors;
if (linkedNode != null) {
if (linkedNode is ClassOrMixinDeclaration) {
_createPropertiesAndAccessors();
assert(_accessors != null);
return _accessors;
} else {
return _accessors = const [];
}
}
if (_accessors == null) {
if (_unlinkedClass != null) {
_resynthesizeFieldsAndPropertyAccessors();
}
}
return _accessors ??= const <PropertyAccessorElement>[];
}
@override
void set accessors(List<PropertyAccessorElement> accessors) {
_assertNotResynthesized(_unlinkedClass);
super.accessors = accessors;
}
@override
List<InterfaceType> get allSupertypes {
List<InterfaceType> list = new List<InterfaceType>();
collectAllSupertypes(list, thisType, thisType);
return list;
}
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (_unlinkedClass != null) {
return _unlinkedClass.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (_unlinkedClass != null) {
return _unlinkedClass.codeRange?.offset;
}
return super.codeOffset;
}
@override
List<ConstructorElement> get constructors {
if (_constructors != null) {
return _constructors;
}
if (isMixinApplication) {
return _constructors = _computeMixinAppConstructors();
}
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var containerRef = reference.getChild('@constructor');
_constructors = context.getConstructors(linkedNode).map((node) {
var name = node.name?.name ?? '';
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
return reference.element as ConstructorElement;
}
return ConstructorElementImpl.forLinkedNode(this, reference, node);
}).toList();
if (_constructors.isEmpty) {
return _constructors = [
ConstructorElementImpl.forLinkedNode(
this,
containerRef.getChild(''),
null,
)
..isSynthetic = true
..name = ''
..nameOffset = -1,
];
}
}
if (_unlinkedClass != null) {
var unlinkedExecutables = _unlinkedClass.executables;
var length = unlinkedExecutables.length;
if (length != 0) {
var count = 0;
for (var i = 0; i < length; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.constructor) {
count++;
}
}
if (count != 0) {
var constructors = new List<ConstructorElement>(count);
var index = 0;
for (var i = 0; i < length; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.constructor) {
constructors[index++] =
new ConstructorElementImpl.forSerialized(e, this);
}
}
return _constructors = constructors;
}
}
_constructors = const <ConstructorElement>[];
}
if (_constructors.isEmpty) {
var constructor = new ConstructorElementImpl('', -1);
constructor.isSynthetic = true;
constructor.enclosingElement = this;
_constructors = <ConstructorElement>[constructor];
}
return _constructors;
}
/// Set the constructors contained in this class to the given [constructors].
///
/// Should only be used for class elements that are not mixin applications.
void set constructors(List<ConstructorElement> constructors) {
_assertNotResynthesized(_unlinkedClass);
assert(!isMixinApplication);
for (ConstructorElement constructor in constructors) {
(constructor as ConstructorElementImpl).enclosingElement = this;
}
this._constructors = constructors;
}
@override
String get documentationComment {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var comment = context.getDocumentationComment(linkedNode);
return getCommentNodeRawText(comment);
}
if (_unlinkedClass != null) {
return _unlinkedClass.documentationComment?.text;
}
return super.documentationComment;
}
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext => null;
@override
List<FieldElement> get fields {
if (_fields != null) return _fields;
if (linkedNode != null) {
if (linkedNode is ClassOrMixinDeclaration) {
_createPropertiesAndAccessors();
assert(_fields != null);
return _fields;
} else {
_fields = const [];
}
}
if (_fields == null) {
if (_unlinkedClass != null) {
_resynthesizeFieldsAndPropertyAccessors();
}
}
return _fields ?? const <FieldElement>[];
}
@override
void set fields(List<FieldElement> fields) {
_assertNotResynthesized(_unlinkedClass);
super.fields = fields;
}
bool get hasBeenInferred {
if (linkedNode != null) {
return linkedContext.hasOverrideInferenceDone(linkedNode);
}
return _unlinkedClass != null || _hasBeenInferred;
}
void set hasBeenInferred(bool hasBeenInferred) {
if (linkedNode != null) {
return linkedContext.setOverrideInferenceDone(linkedNode);
}
_assertNotResynthesized(_unlinkedClass);
_hasBeenInferred = hasBeenInferred;
}
@override
bool get hasNonFinalField {
List<ClassElement> classesToVisit = new List<ClassElement>();
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
classesToVisit.add(this);
while (classesToVisit.isNotEmpty) {
ClassElement currentElement = classesToVisit.removeAt(0);
if (visitedClasses.add(currentElement)) {
// check fields
for (FieldElement field in currentElement.fields) {
if (!field.isFinal &&
!field.isConst &&
!field.isStatic &&
!field.isSynthetic) {
return true;
}
}
// check mixins
for (InterfaceType mixinType in currentElement.mixins) {
ClassElement mixinElement = mixinType.element;
classesToVisit.add(mixinElement);
}
// check super
InterfaceType supertype = currentElement.supertype;
if (supertype != null) {
ClassElement superElement = supertype.element;
if (superElement != null) {
classesToVisit.add(superElement);
}
}
}
}
// not found
return false;
}
/// Return `true` if the class has a concrete `noSuchMethod()` method distinct
/// from the one declared in class `Object`, as per the Dart Language
/// Specification (section 10.4).
bool get hasNoSuchMethod {
MethodElement method = lookUpConcreteMethod(
FunctionElement.NO_SUCH_METHOD_METHOD_NAME, library);
ClassElement definingClass = method?.enclosingElement;
return definingClass != null && !definingClass.isDartCoreObject;
}
@override
bool get hasReferenceToSuper => hasModifier(Modifier.REFERENCES_SUPER);
/// Set whether this class references 'super'.
void set hasReferenceToSuper(bool isReferencedSuper) {
setModifier(Modifier.REFERENCES_SUPER, isReferencedSuper);
}
@override
bool get hasStaticMember {
for (MethodElement method in methods) {
if (method.isStatic) {
return true;
}
}
for (PropertyAccessorElement accessor in accessors) {
if (accessor.isStatic) {
return true;
}
}
return false;
}
@override
List<InterfaceType> get interfaces {
if (_interfaces != null) {
return _interfaces;
}
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var implementsClause = context.getImplementsClause(linkedNode);
if (implementsClause != null) {
return _interfaces = implementsClause.interfaces
.map((node) => node.type)
.whereType<InterfaceType>()
.where(_isInterfaceTypeInterface)
.toList();
} else {
return _interfaces = const [];
}
} else if (_unlinkedClass != null) {
var unlinkedInterfaces = _unlinkedClass.interfaces;
var length = unlinkedInterfaces.length;
if (length == 0) {
return _interfaces = const <InterfaceType>[];
}
ResynthesizerContext context = enclosingUnit.resynthesizerContext;
var interfaces = new List<InterfaceType>(length);
var index = 0;
var hasNonInterfaceType = false;
for (var i = 0; i < length; i++) {
var t = unlinkedInterfaces[i];
var type = context.resolveTypeRef(this, t);
if (_isInterfaceTypeInterface(type)) {
interfaces[index++] = type;
} else {
hasNonInterfaceType = true;
}
}
if (hasNonInterfaceType) {
interfaces = interfaces.sublist(0, index);
}
return _interfaces = interfaces;
}
return _interfaces = const <InterfaceType>[];
}
void set interfaces(List<InterfaceType> interfaces) {
_assertNotResynthesized(_unlinkedClass);
_interfaces = interfaces;
}
@override
bool get isAbstract {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isAbstract(linkedNode);
}
if (_unlinkedClass != null) {
return _unlinkedClass.isAbstract;
}
return hasModifier(Modifier.ABSTRACT);
}
/// Set whether this class is abstract.
void set isAbstract(bool isAbstract) {
_assertNotResynthesized(_unlinkedClass);
setModifier(Modifier.ABSTRACT, isAbstract);
}
@override
bool get isDartCoreObject => !isMixin && supertype == null;
@override
bool get isMixinApplication {
if (linkedNode != null) {
return linkedNode is ClassTypeAlias;
}
if (_unlinkedClass != null) {
return _unlinkedClass.isMixinApplication;
}
return hasModifier(Modifier.MIXIN_APPLICATION);
}
@override
bool get isOrInheritsProxy =>
_safeIsOrInheritsProxy(this, new HashSet<ClassElement>());
@override
bool get isProxy {
for (ElementAnnotation annotation in metadata) {
if (annotation.isProxy) {
return true;
}
}
return false;
}
@override
bool get isSimplyBounded {
if (linkedNode != null) {
return linkedContext.isSimplyBounded(linkedNode);
}
return super.isSimplyBounded;
}
@override
bool get isValidMixin {
if (hasReferenceToSuper) {
return false;
}
if (!supertype.isObject) {
return false;
}
for (ConstructorElement constructor in constructors) {
if (!constructor.isSynthetic && !constructor.isFactory) {
return false;
}
}
return true;
}
@override
List<ElementAnnotation> get metadata {
if (_unlinkedClass != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, _unlinkedClass.annotations);
}
return super.metadata;
}
@override
List<MethodElement> get methods {
if (_methods != null) {
return _methods;
}
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var containerRef = reference.getChild('@method');
return _methods = context
.getMethods(linkedNode)
.where((node) => node.propertyKeyword == null)
.map((node) {
var name = node.name.name;
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
return reference.element as MethodElement;
}
return MethodElementImpl.forLinkedNode(this, reference, node);
}).toList();
}
if (_unlinkedClass != null) {
var unlinkedExecutables = _unlinkedClass.executables;
var length = unlinkedExecutables.length;
if (length == 0) {
return _methods = const <MethodElement>[];
}
var count = 0;
for (var i = 0; i < length; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.functionOrMethod) {
count++;
}
}
if (count == 0) {
return _methods = const <MethodElement>[];
}
var methods = new List<MethodElement>(count);
var index = 0;
for (var i = 0; i < length; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.functionOrMethod) {
methods[index++] = new MethodElementImpl.forSerialized(e, this);
}
}
return _methods = methods;
}
return _methods = const <MethodElement>[];
}
/// Set the methods contained in this class to the given [methods].
void set methods(List<MethodElement> methods) {
_assertNotResynthesized(_unlinkedClass);
for (MethodElement method in methods) {
(method as MethodElementImpl).enclosingElement = this;
}
_methods = methods;
}
/// Set whether this class is a mixin application.
void set mixinApplication(bool isMixinApplication) {
_assertNotResynthesized(_unlinkedClass);
setModifier(Modifier.MIXIN_APPLICATION, isMixinApplication);
}
@override
List<InterfaceType> get mixins {
if (linkedMixinInferenceCallback != null) {
_mixins = linkedMixinInferenceCallback(this);
}
if (_mixins != null) {
return _mixins;
}
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var withClause = context.getWithClause(linkedNode);
if (withClause != null) {
return _mixins = withClause.mixinTypes
.map((node) => node.type)
.whereType<InterfaceType>()
.where(_isInterfaceTypeInterface)
.toList();
} else {
return _mixins = const [];
}
} else if (_unlinkedClass != null) {
var unlinkedMixins = _unlinkedClass.mixins;
var length = unlinkedMixins.length;
if (length == 0) {
return _mixins = const <InterfaceType>[];
}
ResynthesizerContext context = enclosingUnit.resynthesizerContext;
var mixins = new List<InterfaceType>(length);
var index = 0;
var hasNonInterfaceType = false;
for (var i = 0; i < length; i++) {
var t = unlinkedMixins[i];
var type = context.resolveTypeRef(this, t);
if (_isInterfaceTypeInterface(type)) {
mixins[index++] = type;
} else {
hasNonInterfaceType = true;
}
}
if (hasNonInterfaceType) {
mixins = mixins.sublist(0, index);
}
return _mixins = mixins;
}
return _mixins = const <InterfaceType>[];
}
void set mixins(List<InterfaceType> mixins) {
_assertNotResynthesized(_unlinkedClass);
// Note: if we are using the analysis driver, the set of mixins has already
// been computed, and it's more accurate (since mixin arguments have been
// inferred). So we only store mixins if we are using the old task model.
if (_unlinkedClass == null) {
_mixins = mixins;
}
}
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
if (_unlinkedClass != null) {
return _unlinkedClass.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0 && _unlinkedClass != null) {
return _unlinkedClass.nameOffset;
}
return offset;
}
/// Names of methods, getters, setters, and operators that this mixin
/// declaration super-invokes. For setters this includes the trailing "=".
/// The list will be empty if this class is not a mixin declaration.
List<String> get superInvokedNames => const <String>[];
@override
InterfaceType get supertype {
if (_supertype != null) return _supertype;
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var coreTypes = context.bundleContext.elementFactory.coreTypes;
if (identical(this, coreTypes.objectClass)) {
return null;
}
var type = context.getSuperclass(linkedNode)?.type;
if (_isInterfaceTypeClass(type)) {
return _supertype = type;
}
return _supertype = this.context.typeProvider.objectType;
} else if (_unlinkedClass != null) {
if (_unlinkedClass.supertype != null) {
DartType type = enclosingUnit.resynthesizerContext
.resolveTypeRef(this, _unlinkedClass.supertype);
if (_isInterfaceTypeClass(type)) {
_supertype = type;
} else {
_supertype = context.typeProvider.objectType;
}
} else if (_unlinkedClass.hasNoSupertype) {
return null;
} else {
_supertype = context.typeProvider.objectType;
}
}
return _supertype;
}
void set supertype(InterfaceType supertype) {
_assertNotResynthesized(_unlinkedClass);
_supertype = supertype;
}
@override
InterfaceType get type {
if (_type == null) {
InterfaceTypeImpl type = new InterfaceTypeImpl(this);
type.typeArguments = typeParameterTypes;
_type = type;
}
return _type;
}
/// Set the type parameters defined for this class to the given
/// [typeParameters].
void set typeParameters(List<TypeParameterElement> typeParameters) {
_assertNotResynthesized(_unlinkedClass);
for (TypeParameterElement typeParameter in typeParameters) {
(typeParameter as TypeParameterElementImpl).enclosingElement = this;
}
this._typeParameterElements = typeParameters;
}
@override
List<UnlinkedTypeParam> get unlinkedTypeParams =>
_unlinkedClass?.typeParameters;
@override
ConstructorElement get unnamedConstructor {
for (ConstructorElement element in constructors) {
String name = element.displayName;
if (name == null || name.isEmpty) {
return element;
}
}
return null;
}
/// Return whether the class is resynthesized and has a constant constructor.
bool get _hasConstConstructor {
if (_hasConstConstructorCached == null) {
_hasConstConstructorCached = false;
if (_unlinkedClass != null) {
_hasConstConstructorCached = _unlinkedClass.executables.any(
(c) => c.kind == UnlinkedExecutableKind.constructor && c.isConst);
}
}
return _hasConstConstructorCached;
}
@override
int get _notSimplyBoundedSlot => _unlinkedClass?.notSimplyBoundedSlot;
@override
void appendTo(StringBuffer buffer) {
if (isAbstract) {
buffer.write('abstract ');
}
buffer.write('class ');
String name = displayName;
if (name == null) {
buffer.write("{unnamed class}");
} else {
buffer.write(name);
}
int variableCount = typeParameters.length;
if (variableCount > 0) {
buffer.write("<");
for (int i = 0; i < variableCount; i++) {
if (i > 0) {
buffer.write(", ");
}
(typeParameters[i] as TypeParameterElementImpl).appendTo(buffer);
}
buffer.write(">");
}
if (supertype != null && !supertype.isObject) {
buffer.write(' extends ');
buffer.write(supertype.displayName);
}
if (mixins.isNotEmpty) {
buffer.write(' with ');
buffer.write(mixins.map((t) => t.displayName).join(', '));
}
if (interfaces.isNotEmpty) {
buffer.write(' implements ');
buffer.write(interfaces.map((t) => t.displayName).join(', '));
}
}
@override
ElementImpl getChild(String identifier) {
ElementImpl child = super.getChild(identifier);
if (child != null) {
return child;
}
//
// The casts in this method are safe because the set methods would have
// thrown a CCE if any of the elements in the arrays were not of the
// expected types.
//
for (ConstructorElement constructor in constructors) {
ConstructorElementImpl constructorImpl = constructor;
if (constructorImpl.identifier == identifier) {
return constructorImpl;
}
}
for (MethodElement method in methods) {
MethodElementImpl methodImpl = method;
if (methodImpl.identifier == identifier) {
return methodImpl;
}
}
for (TypeParameterElement typeParameter in typeParameters) {
TypeParameterElementImpl typeParameterImpl = typeParameter;
if (typeParameterImpl.identifier == identifier) {
return typeParameterImpl;
}
}
return null;
}
@override
ConstructorElement getNamedConstructor(String name) =>
getNamedConstructorFromList(name, constructors);
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
safelyVisitChildren(constructors, visitor);
safelyVisitChildren(methods, visitor);
safelyVisitChildren(typeParameters, visitor);
}
/// Compute a list of constructors for this class, which is a mixin
/// application. If specified, [visitedClasses] is a list of the other mixin
/// application classes which have been visited on the way to reaching this
/// one (this is used to detect circularities).
List<ConstructorElement> _computeMixinAppConstructors(
[List<ClassElementImpl> visitedClasses]) {
// First get the list of constructors of the superclass which need to be
// forwarded to this class.
Iterable<ConstructorElement> constructorsToForward;
if (supertype == null) {
// Shouldn't ever happen, since the only classes with no supertype are
// Object and mixins, and they aren't a mixin application. But for
// safety's sake just assume an empty list.
assert(false);
constructorsToForward = <ConstructorElement>[];
} else if (!supertype.element.isMixinApplication) {
var library = this.library;
constructorsToForward = supertype.element.constructors
.where((constructor) => constructor.isAccessibleIn(library));
} else {
if (visitedClasses == null) {
visitedClasses = <ClassElementImpl>[this];
} else {
if (visitedClasses.contains(this)) {
// Loop in the class hierarchy. Don't try to forward any
// constructors.
return <ConstructorElement>[];
}
visitedClasses.add(this);
}
try {
ClassElementImpl superElement =
AbstractClassElementImpl.getImpl(supertype.element)
as ClassElementImpl;
constructorsToForward =
superElement._computeMixinAppConstructors(visitedClasses);
} finally {
visitedClasses.removeLast();
}
}
// Figure out the type parameter substitution we need to perform in order
// to produce constructors for this class. We want to be robust in the
// face of errors, so drop any extra type arguments and fill in any missing
// ones with `dynamic`.
List<DartType> parameterTypes =
TypeParameterTypeImpl.getTypes(supertype.typeParameters);
List<DartType> argumentTypes = new List<DartType>.filled(
parameterTypes.length, DynamicTypeImpl.instance);
for (int i = 0; i < supertype.typeArguments.length; i++) {
if (i >= argumentTypes.length) {
break;
}
argumentTypes[i] = supertype.typeArguments[i];
}
// Now create an implicit constructor for every constructor found above,
// substituting type parameters as appropriate.
return constructorsToForward
.map((ConstructorElement superclassConstructor) {
ConstructorElementImpl implicitConstructor =
new ConstructorElementImpl(superclassConstructor.name, -1);
implicitConstructor.isSynthetic = true;
implicitConstructor.redirectedConstructor = superclassConstructor;
List<ParameterElement> superParameters = superclassConstructor.parameters;
int count = superParameters.length;
if (count > 0) {
List<ParameterElement> implicitParameters =
new List<ParameterElement>(count);
for (int i = 0; i < count; i++) {
ParameterElement superParameter = superParameters[i];
ParameterElementImpl implicitParameter;
if (superParameter is DefaultParameterElementImpl) {
implicitParameter =
new DefaultParameterElementImpl(superParameter.name, -1)
..constantInitializer = superParameter.constantInitializer;
} else {
implicitParameter =
new ParameterElementImpl(superParameter.name, -1);
}
implicitParameter.isConst = superParameter.isConst;
implicitParameter.isFinal = superParameter.isFinal;
// ignore: deprecated_member_use_from_same_package
implicitParameter.parameterKind = superParameter.parameterKind;
implicitParameter.isSynthetic = true;
implicitParameter.type =
superParameter.type.substitute2(argumentTypes, parameterTypes);
implicitParameters[i] = implicitParameter;
}
implicitConstructor.parameters = implicitParameters;
}
implicitConstructor.enclosingElement = this;
return implicitConstructor;
}).toList(growable: false);
}
void _createPropertiesAndAccessors() {
assert(_accessors == null);
assert(_fields == null);
var context = enclosingUnit.linkedContext;
var accessorList = <PropertyAccessorElement>[];
var fieldList = <FieldElement>[];
var fields = context.getFields(linkedNode);
for (var field in fields) {
var name = field.name.name;
var fieldElement = FieldElementImpl.forLinkedNodeFactory(
this,
reference.getChild('@field').getChild(name),
field,
);
fieldList.add(fieldElement);
accessorList.add(fieldElement.getter);
if (fieldElement.setter != null) {
accessorList.add(fieldElement.setter);
}
}
var methods = context.getMethods(linkedNode);
for (var method in methods) {
var isGetter = method.isGetter;
var isSetter = method.isSetter;
if (!isGetter && !isSetter) continue;
var name = method.name.name;
var containerRef = isGetter
? reference.getChild('@getter')
: reference.getChild('@setter');
var accessorElement = PropertyAccessorElementImpl.forLinkedNode(
this,
containerRef.getChild(name),
method,
);
accessorList.add(accessorElement);
var fieldRef = reference.getChild('@field').getChild(name);
FieldElementImpl field = fieldRef.element;
if (field == null) {
field = new FieldElementImpl(name, -1);
fieldRef.element = field;
field.enclosingElement = this;
field.isSynthetic = true;
field.isFinal = isGetter;
field.isStatic = accessorElement.isStatic;
fieldList.add(field);
} else {
field.isFinal = false;
}
accessorElement.variable = field;
if (isGetter) {
field.getter ??= accessorElement;
} else {
field.setter ??= accessorElement;
}
}
_accessors = accessorList;
_fields = fieldList;
}
/// Return `true` if the given [type] is an [InterfaceType] that can be used
/// as a class.
bool _isInterfaceTypeClass(DartType type) {
if (type is InterfaceType) {
var element = type.element;
return !element.isEnum && !element.isMixin;
}
return false;
}
/// Return `true` if the given [type] is an [InterfaceType] that can be used
/// as an interface or a mixin.
bool _isInterfaceTypeInterface(DartType type) {
return type is InterfaceType && !type.element.isEnum;
}
/// Resynthesize explicit fields and property accessors and fill [_fields] and
/// [_accessors] with explicit and implicit elements.
void _resynthesizeFieldsAndPropertyAccessors() {
assert(_fields == null);
assert(_accessors == null);
var unlinkedFields = _unlinkedClass.fields;
var unlinkedExecutables = _unlinkedClass.executables;
// Build explicit fields and implicit property accessors.
List<FieldElement> explicitFields;
List<PropertyAccessorElement> implicitAccessors;
var unlinkedFieldsLength = unlinkedFields.length;
if (unlinkedFieldsLength != 0) {
explicitFields = new List<FieldElement>(unlinkedFieldsLength);
implicitAccessors = <PropertyAccessorElement>[];
for (var i = 0; i < unlinkedFieldsLength; i++) {
var v = unlinkedFields[i];
FieldElementImpl field =
new FieldElementImpl.forSerializedFactory(v, this);
explicitFields[i] = field;
implicitAccessors.add(
new PropertyAccessorElementImpl_ImplicitGetter(field)
..enclosingElement = this);
if (!field.isConst && !field.isFinal) {
implicitAccessors.add(
new PropertyAccessorElementImpl_ImplicitSetter(field)
..enclosingElement = this);
}
}
} else {
explicitFields = const <FieldElement>[];
implicitAccessors = const <PropertyAccessorElement>[];
}
var unlinkedExecutablesLength = unlinkedExecutables.length;
var getterSetterCount = 0;
for (var i = 0; i < unlinkedExecutablesLength; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.getter ||
e.kind == UnlinkedExecutableKind.setter) {
getterSetterCount++;
}
}
// Build explicit property accessors and implicit fields.
List<PropertyAccessorElement> explicitAccessors;
Map<String, FieldElementImpl> implicitFields;
if (getterSetterCount != 0) {
explicitAccessors = new List<PropertyAccessorElement>(getterSetterCount);
implicitFields = <String, FieldElementImpl>{};
var index = 0;
for (var i = 0; i < unlinkedExecutablesLength; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.getter ||
e.kind == UnlinkedExecutableKind.setter) {
PropertyAccessorElementImpl accessor =
new PropertyAccessorElementImpl.forSerialized(e, this);
explicitAccessors[index++] = accessor;
// Create or update the implicit field.
String fieldName = accessor.displayName;
FieldElementImpl field = implicitFields[fieldName];
if (field == null) {
field = new FieldElementImpl(fieldName, -1);
implicitFields[fieldName] = field;
field.enclosingElement = this;
field.isSynthetic = true;
field.isFinal = e.kind == UnlinkedExecutableKind.getter;
field.isStatic = e.isStatic;
} else {
field.isFinal = false;
}
accessor.variable = field;
if (e.kind == UnlinkedExecutableKind.getter) {
field.getter = accessor;
} else {
field.setter = accessor;
}
}
}
} else {
explicitAccessors = const <PropertyAccessorElement>[];
implicitFields = const <String, FieldElementImpl>{};
}
// Combine explicit and implicit fields and property accessors.
if (implicitFields.isEmpty) {
_fields = explicitFields;
} else if (explicitFields.isEmpty) {
_fields = implicitFields.values.toList(growable: false);
} else {
_fields = <FieldElement>[]
..addAll(explicitFields)
..addAll(implicitFields.values);
}
if (explicitAccessors.isEmpty) {
_accessors = implicitAccessors;
} else if (implicitAccessors.isEmpty) {
_accessors = explicitAccessors;
} else {
_accessors = <PropertyAccessorElement>[]
..addAll(explicitAccessors)
..addAll(implicitAccessors);
}
}
bool _safeIsOrInheritsProxy(
ClassElement element, HashSet<ClassElement> visited) {
if (visited.contains(element)) {
return false;
}
visited.add(element);
if (element.isProxy) {
return true;
} else if (element.supertype != null &&
_safeIsOrInheritsProxy(element.supertype.element, visited)) {
return true;
}
List<InterfaceType> supertypes = element.interfaces;
for (int i = 0; i < supertypes.length; i++) {
if (_safeIsOrInheritsProxy(supertypes[i].element, visited)) {
return true;
}
}
supertypes = element.mixins;
for (int i = 0; i < supertypes.length; i++) {
if (_safeIsOrInheritsProxy(supertypes[i].element, visited)) {
return true;
}
}
return false;
}
static void collectAllSupertypes(List<InterfaceType> supertypes,
InterfaceType startingType, InterfaceType excludeType) {
List<InterfaceType> typesToVisit = new List<InterfaceType>();
List<ClassElement> visitedClasses = new List<ClassElement>();
typesToVisit.add(startingType);
while (typesToVisit.isNotEmpty) {
InterfaceType currentType = typesToVisit.removeAt(0);
ClassElement currentElement = currentType.element;
if (!visitedClasses.contains(currentElement)) {
visitedClasses.add(currentElement);
if (!identical(currentType, excludeType)) {
supertypes.add(currentType);
}
InterfaceType supertype = currentType.superclass;
if (supertype != null) {
typesToVisit.add(supertype);
}
for (InterfaceType type in currentType.superclassConstraints) {
typesToVisit.add(type);
}
for (InterfaceType type in currentType.interfaces) {
typesToVisit.add(type);
}
for (InterfaceType type in currentType.mixins) {
typesToVisit.add(type);
}
}
}
}
static ConstructorElement getNamedConstructorFromList(
String name, List<ConstructorElement> constructors) {
for (ConstructorElement element in constructors) {
String elementName = element.name;
if (elementName != null && elementName == name) {
return element;
}
}
return null;
}
}
/// A concrete implementation of a [CompilationUnitElement].
class CompilationUnitElementImpl extends UriReferencedElementImpl
implements CompilationUnitElement {
/// The context in which this unit is resynthesized, or `null` if the
/// element is not resynthesized a summary.
final ResynthesizerContext resynthesizerContext;
/// The unlinked representation of the unit in the summary.
final UnlinkedUnit _unlinkedUnit;
/// The unlinked representation of the part in the summary.
final UnlinkedPart _unlinkedPart;
final LinkedUnitContext linkedContext;
/// The source that corresponds to this compilation unit.
@override
Source source;
@override
LineInfo lineInfo;
/// The source of the library containing this compilation unit.
///
/// This is the same as the source of the containing [LibraryElement],
/// except that it does not require the containing [LibraryElement] to be
/// computed.
Source librarySource;
/// A table mapping the offset of a directive to the annotations associated
/// with that directive, or `null` if none of the annotations in the
/// compilation unit have annotations.
Map<int, List<ElementAnnotation>> annotationMap;
/// A list containing all of the top-level accessors (getters and setters)
/// contained in this compilation unit.
List<PropertyAccessorElement> _accessors;
/// A list containing all of the enums contained in this compilation unit.
List<ClassElement> _enums;
/// A list containing all of the extensions contained in this compilation
/// unit.
List<ExtensionElement> _extensions;
/// A list containing all of the top-level functions contained in this
/// compilation unit.
List<FunctionElement> _functions;
/// A list containing all of the mixins contained in this compilation unit.
List<ClassElement> _mixins;
/// A list containing all of the function type aliases contained in this
/// compilation unit.
List<FunctionTypeAliasElement> _typeAliases;
/// A list containing all of the classes contained in this compilation unit.
List<ClassElement> _types;
/// A list containing all of the variables contained in this compilation unit.
List<TopLevelVariableElement> _variables;
/// Resynthesized explicit top-level property accessors.
UnitExplicitTopLevelAccessors _explicitTopLevelAccessors;
/// Resynthesized explicit top-level variables.
UnitExplicitTopLevelVariables _explicitTopLevelVariables;
/// Description of top-level variable replacements that should be applied
/// to implicit top-level variables because of re-linking top-level property
/// accessors between different unit of the same library.
Map<TopLevelVariableElement, TopLevelVariableElement>
_topLevelVariableReplaceMap;
/// Initialize a newly created compilation unit element to have the given
/// [name].
CompilationUnitElementImpl()
: resynthesizerContext = null,
_unlinkedUnit = null,
_unlinkedPart = null,
linkedContext = null,
super(null, -1);
CompilationUnitElementImpl.forLinkedNode(LibraryElementImpl enclosingLibrary,
this.linkedContext, Reference reference, CompilationUnit linkedNode)
: resynthesizerContext = null,
_unlinkedUnit = null,
_unlinkedPart = null,
super.forLinkedNode(enclosingLibrary, reference, linkedNode) {
_nameOffset = -1;
}
/// Initialize using the given serialized information.
CompilationUnitElementImpl.forSerialized(LibraryElementImpl enclosingLibrary,
this.resynthesizerContext, this._unlinkedUnit, this._unlinkedPart)
: linkedContext = null,
super.forSerialized(null) {
_enclosingElement = enclosingLibrary;
_nameOffset = -1;
}
@override
List<PropertyAccessorElement> get accessors {
if (_accessors != null) return _accessors;
if (linkedNode != null) {
_createPropertiesAndAccessors(this);
assert(_accessors != null);
return _accessors;
}
if (_unlinkedUnit != null) {
_explicitTopLevelAccessors ??=
resynthesizerContext.buildTopLevelAccessors();
_explicitTopLevelVariables ??=
resynthesizerContext.buildTopLevelVariables();
}
if (_explicitTopLevelAccessors != null) {
_accessors = <PropertyAccessorElementImpl>[]
..addAll(_explicitTopLevelAccessors.accessors)
..addAll(_explicitTopLevelVariables.implicitAccessors);
}
return _accessors ?? const <PropertyAccessorElement>[];
}
/// Set the top-level accessors (getters and setters) contained in this
/// compilation unit to the given [accessors].
void set accessors(List<PropertyAccessorElement> accessors) {
for (PropertyAccessorElement accessor in accessors) {
(accessor as PropertyAccessorElementImpl).enclosingElement = this;
}
this._accessors = accessors;
}
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (_unlinkedUnit != null) {
return _unlinkedUnit.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (_unlinkedUnit != null) {
return _unlinkedUnit.codeRange?.offset;
}
return super.codeOffset;
}
@override
LibraryElement get enclosingElement =>
super.enclosingElement as LibraryElement;
@override
CompilationUnitElementImpl get enclosingUnit {
return this;
}
@override
List<ClassElement> get enums {
if (_enums != null) return _enums;
if (linkedNode != null) {
var containerRef = reference.getChild('@enum');
CompilationUnit linkedNode = this.linkedNode;
_enums = linkedNode.declarations.whereType<EnumDeclaration>().map((node) {
var name = node.name.name;
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
return reference.element as EnumElementImpl;
}
return EnumElementImpl.forLinkedNode(this, reference, node);
}).toList();
}
if (_unlinkedUnit != null) {
return _enums = _unlinkedUnit.enums
.map((e) => new EnumElementImpl.forSerialized(e, this))
.toList(growable: false);
}
return _enums ??= const <ClassElement>[];
}
/// Set the enums contained in this compilation unit to the given [enums].
void set enums(List<ClassElement> enums) {
_assertNotResynthesized(_unlinkedUnit);
for (ClassElement enumDeclaration in enums) {
(enumDeclaration as EnumElementImpl).enclosingElement = this;
}
this._enums = enums;
}
@override
List<ExtensionElement> get extensions {
if (_extensions != null) {
return _extensions;
}
if (linkedNode != null) {
CompilationUnit linkedNode = this.linkedNode;
var containerRef = reference.getChild('@extension');
_extensions = <ExtensionElement>[];
for (var node in linkedNode.declarations) {
if (node is ExtensionDeclaration) {
var refName = linkedContext.getExtensionRefName(node);
var reference = containerRef.getChild(refName);
if (reference.hasElementFor(node)) {
_extensions.add(reference.element);
} else {
_extensions.add(
ExtensionElementImpl.forLinkedNode(this, reference, node),
);
}
}
}
return _extensions;
} else if (_unlinkedUnit != null) {
return _extensions = _unlinkedUnit.extensions
.map((e) => ExtensionElementImpl.forSerialized(e, this))
.toList(growable: false);
}
return _extensions ?? const <ExtensionElement>[];
}
/// Set the extensions contained in this compilation unit to the given
/// [extensions].
void set extensions(List<ExtensionElement> extensions) {
for (ExtensionElement extension in extensions) {
(extension as ExtensionElementImpl).enclosingElement = this;
}
this._extensions = extensions;
}
@override
List<FunctionElement> get functions {
if (_functions != null) return _functions;
if (linkedNode != null) {
CompilationUnit linkedNode = this.linkedNode;
var containerRef = reference.getChild('@function');
return _functions = linkedNode.declarations
.whereType<FunctionDeclaration>()
.where((node) => !node.isGetter && !node.isSetter)
.map((node) {
var name = node.name.name;
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
return reference.element as FunctionElementImpl;
}
return FunctionElementImpl.forLinkedNode(this, reference, node);
}).toList();
} else if (_unlinkedUnit != null) {
_functions = _unlinkedUnit.executables
.where((e) => e.kind == UnlinkedExecutableKind.functionOrMethod)
.map((e) => new FunctionElementImpl.forSerialized(e, this))
.toList(growable: false);
}
return _functions ?? const <FunctionElement>[];
}
/// Set the top-level functions contained in this compilation unit to the
/// given[functions].
void set functions(List<FunctionElement> functions) {
for (FunctionElement function in functions) {
(function as FunctionElementImpl).enclosingElement = this;
}
this._functions = functions;
}
@override
List<FunctionTypeAliasElement> get functionTypeAliases {
if (_typeAliases != null) return _typeAliases;
if (linkedNode != null) {
CompilationUnit linkedNode = this.linkedNode;
var containerRef = reference.getChild('@typeAlias');
return _typeAliases = linkedNode.declarations.where((node) {
return node is FunctionTypeAlias || node is GenericTypeAlias;
}).map((node) {
String name;
if (node is FunctionTypeAlias) {
name = node.name.name;
} else {
name = (node as GenericTypeAlias).name.name;
}
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
return reference.element as GenericTypeAliasElementImpl;
}
return GenericTypeAliasElementImpl.forLinkedNode(this, reference, node);
}).toList();
}
if (_unlinkedUnit != null) {
_typeAliases = _unlinkedUnit.typedefs.map((t) {
return new GenericTypeAliasElementImpl.forSerialized(t, this);
}).toList(growable: false);
}
return _typeAliases ?? const <FunctionTypeAliasElement>[];
}
@override
int get hashCode => source.hashCode;
@override
bool get hasLoadLibraryFunction {
List<FunctionElement> functions = this.functions;
for (int i = 0; i < functions.length; i++) {
if (functions[i].name == FunctionElement.LOAD_LIBRARY_NAME) {
return true;
}
}
return false;
}
@override
String get identifier => '${source.uri}';
@override
ElementKind get kind => ElementKind.COMPILATION_UNIT;
@override
List<ElementAnnotation> get metadata {
if (_metadata == null) {
if (_unlinkedPart != null) {
return _metadata = _buildAnnotations(
library.definingCompilationUnit as CompilationUnitElementImpl,
_unlinkedPart.annotations);
}
}
return super.metadata;
}
@override
List<ClassElement> get mixins {
if (_mixins != null) return _mixins;
if (linkedNode != null) {
CompilationUnit linkedNode = this.linkedNode;
var containerRef = reference.getChild('@mixin');
var declarations = linkedNode.declarations;
return _mixins = declarations.whereType<MixinDeclaration>().map((node) {
var name = node.name.name;
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
return reference.element as MixinElementImpl;
}
return MixinElementImpl.forLinkedNode(this, reference, node);
}).toList();
}
if (_unlinkedUnit != null) {
return _mixins = _unlinkedUnit.mixins
.map((c) => new MixinElementImpl.forSerialized(c, this))
.toList(growable: false);
}
return _mixins ?? const <ClassElement>[];
}
/// Set the mixins contained in this compilation unit to the given [mixins].
void set mixins(List<ClassElement> mixins) {
_assertNotResynthesized(_unlinkedUnit);
for (MixinElementImpl type in mixins) {
type.enclosingElement = this;
}
this._mixins = mixins;
}
@override
List<TopLevelVariableElement> get topLevelVariables {
if (linkedNode != null) {
if (_variables != null) return _variables;
_createPropertiesAndAccessors(this);
assert(_variables != null);
return _variables;
}
if (_variables == null) {
if (_unlinkedUnit != null) {
_explicitTopLevelAccessors ??=
resynthesizerContext.buildTopLevelAccessors();
_explicitTopLevelVariables ??=
resynthesizerContext.buildTopLevelVariables();
}
if (_explicitTopLevelVariables != null) {
var variables = <TopLevelVariableElement>[]
..addAll(_explicitTopLevelVariables.variables)
..addAll(_explicitTopLevelAccessors.implicitVariables);
// Ensure that getters and setters in different units use
// the same top-level variables.
BuildLibraryElementUtils.patchTopLevelAccessors(library);
// Apply recorded patches to variables.
_topLevelVariableReplaceMap?.forEach((from, to) {
int index = variables.indexOf(from);
variables[index] = to;
});
_topLevelVariableReplaceMap = null;
_variables = variables;
}
}
return _variables ?? const <TopLevelVariableElement>[];
}
/// Set the top-level variables contained in this compilation unit to the
/// given[variables].
void set topLevelVariables(List<TopLevelVariableElement> variables) {
assert(!isResynthesized);
for (TopLevelVariableElement field in variables) {
(field as TopLevelVariableElementImpl).enclosingElement = this;
}
this._variables = variables;
}
/// Set the function type aliases contained in this compilation unit to the
/// given [typeAliases].
void set typeAliases(List<FunctionTypeAliasElement> typeAliases) {
_assertNotResynthesized(_unlinkedUnit);
for (FunctionTypeAliasElement typeAlias in typeAliases) {
(typeAlias as ElementImpl).enclosingElement = this;
}
this._typeAliases = typeAliases;
}
@override
TypeParameterizedElementMixin get typeParameterContext => null;
@override
List<ClassElement> get types {
if (_types != null) return _types;
if (linkedNode != null) {
CompilationUnit linkedNode = this.linkedNode;
var containerRef = reference.getChild('@class');
_types = <ClassElement>[];
for (var node in linkedNode.declarations) {
String name;
if (node is ClassDeclaration) {
name = node.name.name;
} else if (node is ClassTypeAlias) {
name = node.name.name;
} else {
continue;
}
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
_types.add(reference.element);
} else {
_types.add(
ClassElementImpl.forLinkedNode(this, reference, node),
);
}
}
return _types;
}
if (_unlinkedUnit != null) {
return _types = _unlinkedUnit.classes
.map((c) => new ClassElementImpl.forSerialized(c, this))
.toList(growable: false);
}
return _types ?? const <ClassElement>[];
}
/// Set the types contained in this compilation unit to the given [types].
void set types(List<ClassElement> types) {
_assertNotResynthesized(_unlinkedUnit);
for (ClassElement type in types) {
// Another implementation of ClassElement is _DeferredClassElement,
// which is used to resynthesize classes lazily. We cannot cast it
// to ClassElementImpl, and it already can provide correct values of the
// 'enclosingElement' property.
if (type is ClassElementImpl) {
type.enclosingElement = this;
}
}
this._types = types;
}
@override
bool operator ==(Object object) =>
object is CompilationUnitElementImpl && source == object.source;
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitCompilationUnitElement(this);
@override
void appendTo(StringBuffer buffer) {
if (source == null) {
buffer.write("{compilation unit}");
} else {
buffer.write(source.fullName);
}
}
@deprecated
@override
CompilationUnit computeNode() => unit;
/// Return the annotations associated with the directive at the given
/// [offset], or an empty list if the directive has no annotations or if
/// there is no directive at the given offset.
List<ElementAnnotation> getAnnotations(int offset) {
if (annotationMap == null) {
return const <ElementAnnotation>[];
}
return annotationMap[offset] ?? const <ElementAnnotation>[];
}
@override
ElementImpl getChild(String identifier) {
//
// The casts in this method are safe because the set methods would have
// thrown a CCE if any of the elements in the arrays were not of the
// expected types.
//
for (PropertyAccessorElement accessor in accessors) {
PropertyAccessorElementImpl accessorImpl = accessor;
if (accessorImpl.identifier == identifier) {
return accessorImpl;
}
}
for (TopLevelVariableElement variable in topLevelVariables) {
TopLevelVariableElementImpl variableImpl = variable;
if (variableImpl.identifier == identifier) {
return variableImpl;
}
}
for (FunctionElement function in functions) {
FunctionElementImpl functionImpl = function;
if (functionImpl.identifier == identifier) {
return functionImpl;
}
}
for (GenericTypeAliasElementImpl typeAlias in functionTypeAliases) {
if (typeAlias.identifier == identifier) {
return typeAlias;
}
}
for (ClassElement type in types) {
ClassElementImpl typeImpl = type;
if (typeImpl.name == identifier) {
return typeImpl;
}
}
for (ClassElement type in enums) {
EnumElementImpl typeImpl = type;
if (typeImpl.identifier == identifier) {
return typeImpl;
}
}
return null;
}
@override
ClassElement getEnum(String enumName) {
for (ClassElement enumDeclaration in enums) {
if (enumDeclaration.name == enumName) {
return enumDeclaration;
}
}
return null;
}
@override
ClassElement getType(String className) {
return getTypeFromTypes(className, types);
}
/// Replace the given [from] top-level variable with [to] in this compilation
/// unit.
void replaceTopLevelVariable(
TopLevelVariableElement from, TopLevelVariableElement to) {
if (_unlinkedUnit != null) {
// Getters and setter in different units should be patched to use the
// same variables before these variables were asked and returned.
assert(_variables == null);
_topLevelVariableReplaceMap ??=
<TopLevelVariableElement, TopLevelVariableElement>{};
_topLevelVariableReplaceMap[from] = to;
} else {
int index = _variables.indexOf(from);
_variables[index] = to;
}
}
/// Set the annotations associated with the directive at the given [offset] to
/// the given list of [annotations].
void setAnnotations(int offset, List<ElementAnnotation> annotations) {
annotationMap ??= new HashMap<int, List<ElementAnnotation>>();
annotationMap[offset] = annotations;
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
safelyVisitChildren(accessors, visitor);
safelyVisitChildren(enums, visitor);
safelyVisitChildren(extensions, visitor);
safelyVisitChildren(functions, visitor);
safelyVisitChildren(functionTypeAliases, visitor);
safelyVisitChildren(mixins, visitor);
safelyVisitChildren(types, visitor);
safelyVisitChildren(topLevelVariables, visitor);
}
static ClassElement getTypeFromTypes(
String className, List<ClassElement> types) {
for (ClassElement type in types) {
if (type.name == className) {
return type;
}
}
return null;
}
static void _createPropertiesAndAccessors(CompilationUnitElementImpl unit) {
if (unit._variables != null) return;
assert(unit._accessors == null);
var accessorMap =
<CompilationUnitElementImpl, List<PropertyAccessorElement>>{};
var variableMap =
<CompilationUnitElementImpl, List<TopLevelVariableElement>>{};
var units = unit.library.units;
for (CompilationUnitElementImpl unit in units) {
var context = unit.linkedContext;
var accessorList = <PropertyAccessorElement>[];
accessorMap[unit] = accessorList;
var variableList = <TopLevelVariableElement>[];
variableMap[unit] = variableList;
var unitNode = unit.linkedContext.unit_withDeclarations;
var unitDeclarations = unitNode.declarations;
var variables = context.topLevelVariables(unitNode);
for (var variable in variables) {
var name = variable.name.name;
var reference = unit.reference.getChild('@variable').getChild(name);
var variableElement = TopLevelVariableElementImpl.forLinkedNodeFactory(
unit,
reference,
variable,
);
variableList.add(variableElement);
accessorList.add(variableElement.getter);
if (variableElement.setter != null) {
accessorList.add(variableElement.setter);
}
}
for (var node in unitDeclarations) {
if (node is FunctionDeclaration) {
var isGetter = node.isGetter;
var isSetter = node.isSetter;
if (!isGetter && !isSetter) continue;
var name = node.name.name;
var containerRef = isGetter
? unit.reference.getChild('@getter')
: unit.reference.getChild('@setter');
var accessorElement = PropertyAccessorElementImpl.forLinkedNode(
unit,
containerRef.getChild(name),
node,
);
accessorList.add(accessorElement);
var fieldRef = unit.reference.getChild('@field').getChild(name);
TopLevelVariableElementImpl field = fieldRef.element;
if (field == null) {
field = new TopLevelVariableElementImpl(name, -1);
fieldRef.element = field;
field.enclosingElement = unit;
field.isSynthetic = true;
field.isFinal = isGetter;
variableList.add(field);
} else {
field.isFinal = false;
}
accessorElement.variable = field;
if (isGetter) {
field.getter = accessorElement;
} else {
field.setter = accessorElement;
}
}
}
}
for (CompilationUnitElementImpl unit in units) {
unit._accessors = accessorMap[unit];
unit._variables = variableMap[unit];
}
}
}
/// A [FieldElement] for a 'const' or 'final' field that has an initializer.
///
/// TODO(paulberry): we should rename this class to reflect the fact that it's
/// used for both const and final fields. However, we shouldn't do so until
/// we've created an API for reading the values of constants; until that API is
/// available, clients are likely to read constant values by casting to
/// ConstFieldElementImpl, so it would be a breaking change to rename this
/// class.
class ConstFieldElementImpl extends FieldElementImpl with ConstVariableElement {
/// Initialize a newly created synthetic field element to have the given
/// [name] and [offset].
ConstFieldElementImpl(String name, int offset) : super(name, offset);
ConstFieldElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created field element to have the given [name].
ConstFieldElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
ConstFieldElementImpl.forSerialized(
UnlinkedVariable unlinkedVariable, ElementImpl enclosingElement)
: super.forSerialized(unlinkedVariable, enclosingElement);
}
/// A field element representing an enum constant.
class ConstFieldElementImpl_EnumValue extends ConstFieldElementImpl_ofEnum {
final UnlinkedEnumValue _unlinkedEnumValue;
final int _index;
ConstFieldElementImpl_EnumValue(
EnumElementImpl enumElement, this._unlinkedEnumValue, this._index)
: super(enumElement);
ConstFieldElementImpl_EnumValue.forLinkedNode(EnumElementImpl enumElement,
Reference reference, AstNode linkedNode, this._index)
: _unlinkedEnumValue = null,
super.forLinkedNode(enumElement, reference, linkedNode);
@override
Expression get constantInitializer => null;
@override
String get documentationComment {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var comment = context.getDocumentationComment(linkedNode);
return getCommentNodeRawText(comment);
}
if (_unlinkedEnumValue != null) {
return _unlinkedEnumValue.documentationComment?.text;
}
return super.documentationComment;
}
@override
EvaluationResultImpl get evaluationResult {
if (_evaluationResult == null) {
Map<String, DartObjectImpl> fieldMap = <String, DartObjectImpl>{
name: new DartObjectImpl(
context.typeProvider.intType, new IntState(_index))
};
DartObjectImpl value =
new DartObjectImpl(type, new GenericState(fieldMap));
_evaluationResult = new EvaluationResultImpl(value);
}
return _evaluationResult;
}
@override
List<ElementAnnotation> get metadata {
if (_unlinkedEnumValue != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, _unlinkedEnumValue.annotations);
}
return super.metadata;
}
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
if (_unlinkedEnumValue != null) {
return _unlinkedEnumValue.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == -1) {
if (_unlinkedEnumValue != null) {
return _unlinkedEnumValue.nameOffset;
}
}
return offset;
}
@override
InterfaceType get type => _enum.thisType;
}
/// The synthetic `values` field of an enum.
class ConstFieldElementImpl_EnumValues extends ConstFieldElementImpl_ofEnum {
ConstFieldElementImpl_EnumValues(EnumElementImpl enumElement)
: super(enumElement) {
isSynthetic = true;
}
@override
EvaluationResultImpl get evaluationResult {
if (_evaluationResult == null) {
List<DartObjectImpl> constantValues = <DartObjectImpl>[];
for (FieldElement field in _enum.fields) {
if (field is ConstFieldElementImpl_EnumValue) {
constantValues.add(field.evaluationResult.value);
}
}
_evaluationResult = new EvaluationResultImpl(
new DartObjectImpl(type, new ListState(constantValues)));
}
return _evaluationResult;
}
@override
String get name => 'values';
@override
InterfaceType get type {
if (_type == null) {
return _type = context.typeProvider.listType2(_enum.thisType);
}
return _type;
}
}
/// An abstract constant field of an enum.
abstract class ConstFieldElementImpl_ofEnum extends ConstFieldElementImpl {
final EnumElementImpl _enum;
ConstFieldElementImpl_ofEnum(this._enum) : super(null, -1) {
enclosingElement = _enum;
}
ConstFieldElementImpl_ofEnum.forLinkedNode(
this._enum, Reference reference, AstNode linkedNode)
: super.forLinkedNode(_enum, reference, linkedNode);
@override
void set evaluationResult(_) {
assert(false);
}
@override
bool get isConst => true;
@override
void set isConst(bool isConst) {
assert(false);
}
@override
bool get isConstantEvaluated => true;
@override
void set isFinal(bool isFinal) {
assert(false);
}
@override
bool get isStatic => true;
@override
void set isStatic(bool isStatic) {
assert(false);
}
void set type(DartType type) {
assert(false);
}
}
/// A [LocalVariableElement] for a local 'const' variable that has an
/// initializer.
class ConstLocalVariableElementImpl extends LocalVariableElementImpl
with ConstVariableElement {
/// Initialize a newly created local variable element to have the given [name]
/// and [offset].
ConstLocalVariableElementImpl(String name, int offset) : super(name, offset);
/// Initialize a newly created local variable element to have the given
/// [name].
ConstLocalVariableElementImpl.forNode(Identifier name) : super.forNode(name);
}
/// A concrete implementation of a [ConstructorElement].
class ConstructorElementImpl extends ExecutableElementImpl
implements ConstructorElement {
/// The constructor to which this constructor is redirecting.
ConstructorElement _redirectedConstructor;
/// The initializers for this constructor (used for evaluating constant
/// instance creation expressions).
List<ConstructorInitializer> _constantInitializers;
/// The offset of the `.` before this constructor name or `null` if not named.
int _periodOffset;
/// Return the offset of the character immediately following the last
/// character of this constructor's name, or `null` if not named.
int _nameEnd;
/// For every constructor we initially set this flag to `true`, and then
/// set it to `false` during computing constant values if we detect that it
/// is a part of a cycle.
bool _isCycleFree = true;
@override
bool isConstantEvaluated = false;
/// Initialize a newly created constructor element to have the given [name]
/// and [offset].
ConstructorElementImpl(String name, int offset) : super(name, offset);
ConstructorElementImpl.forLinkedNode(ClassElementImpl enclosingClass,
Reference reference, ConstructorDeclaration linkedNode)
: super.forLinkedNode(enclosingClass, reference, linkedNode);
/// Initialize a newly created constructor element to have the given [name].
ConstructorElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
ConstructorElementImpl.forSerialized(
UnlinkedExecutable serializedExecutable, ClassElementImpl enclosingClass)
: super.forSerialized(serializedExecutable, enclosingClass);
/// Return the constant initializers for this element, which will be empty if
/// there are no initializers, or `null` if there was an error in the source.
List<ConstructorInitializer> get constantInitializers {
if (_constantInitializers != null) return _constantInitializers;
if (linkedNode != null) {
return _constantInitializers = linkedContext.getConstructorInitializers(
linkedNode,
);
}
if (serializedExecutable != null) {
return _constantInitializers = serializedExecutable.constantInitializers
.map((i) => _buildConstructorInitializer(i))
.toList(growable: false);
}
return _constantInitializers;
}
void set constantInitializers(
List<ConstructorInitializer> constantInitializers) {
_assertNotResynthesized(serializedExecutable);
_constantInitializers = constantInitializers;
}
@override
String get displayName {
if (linkedNode != null) {
return reference.name;
}
return super.displayName;
}
@override
ClassElementImpl get enclosingElement =>
super.enclosingElement as ClassElementImpl;
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext =>
super.enclosingElement as ClassElementImpl;
/// Set whether this constructor represents a factory method.
void set factory(bool isFactory) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.FACTORY, isFactory);
}
@override
bool get isConst {
if (linkedNode != null) {
ConstructorDeclaration linkedNode = this.linkedNode;
return linkedNode.constKeyword != null;
}
if (serializedExecutable != null) {
return serializedExecutable.isConst;
}
return hasModifier(Modifier.CONST);
}
/// Set whether this constructor represents a 'const' constructor.
void set isConst(bool isConst) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.CONST, isConst);
}
bool get isCycleFree {
if (serializedExecutable != null) {
return serializedExecutable.isConst &&
!enclosingUnit.resynthesizerContext
.isInConstCycle(serializedExecutable.constCycleSlot);
}
return _isCycleFree;
}
void set isCycleFree(bool isCycleFree) {
// This property is updated in ConstantEvaluationEngine even for
// resynthesized constructors, so we don't have the usual assert here.
_isCycleFree = isCycleFree;
}
@override
bool get isDefaultConstructor {
// unnamed
String name = this.name;
if (name != null && name.isNotEmpty) {
return false;
}
// no required parameters
for (ParameterElement parameter in parameters) {
if (parameter.isNotOptional) {
return false;
}
}
// OK, can be used as default constructor
return true;
}
@override
bool get isFactory {
if (linkedNode != null) {
ConstructorDeclaration linkedNode = this.linkedNode;
return linkedNode.factoryKeyword != null;
}
if (serializedExecutable != null) {
return serializedExecutable.isFactory;
}
return hasModifier(Modifier.FACTORY);
}
@override
bool get isStatic => false;
@override
ElementKind get kind => ElementKind.CONSTRUCTOR;
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
return super.name;
}
@override
int get nameEnd {
if (linkedNode != null) {
var node = linkedNode as ConstructorDeclaration;
if (node.name != null) {
return node.name.end;
} else {
return node.returnType.end;
}
}
if (serializedExecutable != null) {
if (serializedExecutable.name.isNotEmpty) {
return serializedExecutable.nameEnd;
} else {
return serializedExecutable.nameOffset + enclosingElement.name.length;
}
}
return _nameEnd;
}
void set nameEnd(int nameEnd) {
_assertNotResynthesized(serializedExecutable);
_nameEnd = nameEnd;
}
@override
int get periodOffset {
if (linkedNode != null) {
var node = linkedNode as ConstructorDeclaration;
return node.period?.offset;
}
if (serializedExecutable != null) {
if (serializedExecutable.name.isNotEmpty) {
return serializedExecutable.periodOffset;
}
}
return _periodOffset;
}
void set periodOffset(int periodOffset) {
_assertNotResynthesized(serializedExecutable);
_periodOffset = periodOffset;
}
@override
ConstructorElement get redirectedConstructor {
if (_redirectedConstructor != null) return _redirectedConstructor;
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
if (isFactory) {
var node = context.getConstructorRedirected(linkedNode);
return _redirectedConstructor = node?.staticElement;
} else {
var initializers = context.getConstructorInitializers(linkedNode);
for (var initializer in initializers) {
if (initializer is RedirectingConstructorInvocation) {
return _redirectedConstructor = initializer.staticElement;
}
}
}
return null;
}
if (serializedExecutable != null) {
if (serializedExecutable.isRedirectedConstructor) {
if (serializedExecutable.isFactory) {
_redirectedConstructor = enclosingUnit.resynthesizerContext
.resolveConstructorRef(
enclosingElement, serializedExecutable.redirectedConstructor);
} else {
_redirectedConstructor = enclosingElement.getNamedConstructor(
serializedExecutable.redirectedConstructorName);
}
} else {
return null;
}
}
return _redirectedConstructor;
}
void set redirectedConstructor(ConstructorElement redirectedConstructor) {
_assertNotResynthesized(serializedExecutable);
_redirectedConstructor = redirectedConstructor;
}
@override
DartType get returnType => enclosingElement.thisType;
void set returnType(DartType returnType) {
assert(false);
}
@override
FunctionType get type {
return _type ??= new FunctionTypeImpl(this);
}
void set type(FunctionType type) {
assert(false);
}
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitConstructorElement(this);
@override
void appendTo(StringBuffer buffer) {
String name;
String constructorName = displayName;
if (enclosingElement == null) {
String message;
if (constructorName != null && constructorName.isNotEmpty) {
message =
'Found constructor element named $constructorName with no enclosing element';
} else {
message = 'Found unnamed constructor element with no enclosing element';
}
AnalysisEngine.instance.logger.logError(message);
name = '<unknown class>';
} else {
name = enclosingElement.displayName;
}
if (constructorName != null && constructorName.isNotEmpty) {
name = '$name.$constructorName';
}
appendToWithName(buffer, name);
}
/// Ensures that dependencies of this constructor, such as default values
/// of formal parameters, are evaluated.
void computeConstantDependencies() {
if (!isConstantEvaluated) {
AnalysisOptionsImpl analysisOptions = context.analysisOptions;
computeConstants(context.typeProvider, context.typeSystem,
context.declaredVariables, [this], analysisOptions.experimentStatus);
}
}
@deprecated
@override
ConstructorDeclaration computeNode() =>
getNodeMatching((node) => node is ConstructorDeclaration);
/// Resynthesize the AST for the given serialized constructor initializer.
ConstructorInitializer _buildConstructorInitializer(
UnlinkedConstructorInitializer serialized) {
UnlinkedConstructorInitializerKind kind = serialized.kind;
String name = serialized.name;
List<Expression> arguments = <Expression>[];
{
int numArguments = serialized.arguments.length;
int numNames = serialized.argumentNames.length;
for (int i = 0; i < numArguments; i++) {
Expression expression = enclosingUnit.resynthesizerContext
.buildExpression(this, serialized.arguments[i]);
int nameIndex = numNames + i - numArguments;
if (nameIndex >= 0) {
expression = AstTestFactory.namedExpression2(
serialized.argumentNames[nameIndex], expression);
}
arguments.add(expression);
}
}
switch (kind) {
case UnlinkedConstructorInitializerKind.field:
ConstructorFieldInitializer initializer =
AstTestFactory.constructorFieldInitializer(
false,
name,
enclosingUnit.resynthesizerContext
.buildExpression(this, serialized.expression));
initializer.fieldName.staticElement = enclosingElement.getField(name);
return initializer;
case UnlinkedConstructorInitializerKind.assertInvocation:
return AstTestFactory.assertInitializer(
arguments[0], arguments.length > 1 ? arguments[1] : null);
case UnlinkedConstructorInitializerKind.superInvocation:
SuperConstructorInvocation initializer =
AstTestFactory.superConstructorInvocation2(
name.isNotEmpty ? name : null, arguments);
ClassElement superElement = enclosingElement.supertype.element;
ConstructorElement element = name.isEmpty
? superElement.unnamedConstructor
: superElement.getNamedConstructor(name);
initializer.staticElement = element;
initializer.constructorName?.staticElement = element;
return initializer;
case UnlinkedConstructorInitializerKind.thisInvocation:
RedirectingConstructorInvocation initializer =
AstTestFactory.redirectingConstructorInvocation2(
name.isNotEmpty ? name : null, arguments);
ConstructorElement element = name.isEmpty
? enclosingElement.unnamedConstructor
: enclosingElement.getNamedConstructor(name);
initializer.staticElement = element;
initializer.constructorName?.staticElement = element;
return initializer;
}
return null;
}
}
/// A [TopLevelVariableElement] for a top-level 'const' variable that has an
/// initializer.
class ConstTopLevelVariableElementImpl extends TopLevelVariableElementImpl
with ConstVariableElement {
/// Initialize a newly created synthetic top-level variable element to have
/// the given [name] and [offset].
ConstTopLevelVariableElementImpl(String name, int offset)
: super(name, offset);
ConstTopLevelVariableElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created top-level variable element to have the given
/// [name].
ConstTopLevelVariableElementImpl.forNode(Identifier name)
: super.forNode(name);
/// Initialize using the given serialized information.
ConstTopLevelVariableElementImpl.forSerialized(
UnlinkedVariable unlinkedVariable, ElementImpl enclosingElement)
: super.forSerialized(unlinkedVariable, enclosingElement);
}
/// Mixin used by elements that represent constant variables and have
/// initializers.
///
/// Note that in correct Dart code, all constant variables must have
/// initializers. However, analyzer also needs to handle incorrect Dart code,
/// in which case there might be some constant variables that lack initializers.
/// This interface is only used for constant variables that have initializers.
///
/// This class is not intended to be part of the public API for analyzer.
mixin ConstVariableElement implements ElementImpl, ConstantEvaluationTarget {
/// If this element represents a constant variable, and it has an initializer,
/// a copy of the initializer for the constant. Otherwise `null`.
///
/// Note that in correct Dart code, all constant variables must have
/// initializers. However, analyzer also needs to handle incorrect Dart code,
/// in which case there might be some constant variables that lack
/// initializers.
Expression _constantInitializer;
EvaluationResultImpl _evaluationResult;
Expression get constantInitializer {
if (_constantInitializer != null) return _constantInitializer;
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
return _constantInitializer = context.readInitializer(linkedNode);
}
if (_unlinkedConst != null) {
_constantInitializer = enclosingUnit.resynthesizerContext
.buildExpression(this, _unlinkedConst);
}
return _constantInitializer;
}
void set constantInitializer(Expression constantInitializer) {
_assertNotResynthesized(_unlinkedConst);
_constantInitializer = constantInitializer;
}
EvaluationResultImpl get evaluationResult => _evaluationResult;
void set evaluationResult(EvaluationResultImpl evaluationResult) {
_evaluationResult = evaluationResult;
}
@override
bool get isConstantEvaluated => _evaluationResult != null;
/// If this element is resynthesized from the summary, return the unlinked
/// initializer, otherwise return `null`.
UnlinkedExpr get _unlinkedConst;
/// Return a representation of the value of this variable, forcing the value
/// to be computed if it had not previously been computed, or `null` if either
/// this variable was not declared with the 'const' modifier or if the value
/// of this variable could not be computed because of errors.
DartObject computeConstantValue() {
if (evaluationResult == null) {
AnalysisOptionsImpl analysisOptions = context.analysisOptions;
computeConstants(context.typeProvider, context.typeSystem,
context.declaredVariables, [this], analysisOptions.experimentStatus);
}
return evaluationResult?.value;
}
}
/// A [FieldFormalParameterElementImpl] for parameters that have an initializer.
class DefaultFieldFormalParameterElementImpl
extends FieldFormalParameterElementImpl with ConstVariableElement {
/// Initialize a newly created parameter element to have the given [name] and
/// [nameOffset].
DefaultFieldFormalParameterElementImpl(String name, int nameOffset)
: super(name, nameOffset);
DefaultFieldFormalParameterElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created parameter element to have the given [name].
DefaultFieldFormalParameterElementImpl.forNode(Identifier name)
: super.forNode(name);
/// Initialize using the given serialized information.
DefaultFieldFormalParameterElementImpl.forSerialized(
UnlinkedParam unlinkedParam, ElementImpl enclosingElement)
: super.forSerialized(unlinkedParam, enclosingElement);
}
/// A [ParameterElement] for parameters that have an initializer.
class DefaultParameterElementImpl extends ParameterElementImpl
with ConstVariableElement {
/// Initialize a newly created parameter element to have the given [name] and
/// [nameOffset].
DefaultParameterElementImpl(String name, int nameOffset)
: super(name, nameOffset);
DefaultParameterElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created parameter element to have the given [name].
DefaultParameterElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
DefaultParameterElementImpl.forSerialized(
UnlinkedParam unlinkedParam, ElementImpl enclosingElement)
: super.forSerialized(unlinkedParam, enclosingElement);
@deprecated
@override
DefaultFormalParameter computeNode() =>
getNodeMatching((node) => node is DefaultFormalParameter);
}
/// The synthetic element representing the declaration of the type `dynamic`.
class DynamicElementImpl extends ElementImpl implements TypeDefiningElement {
/// Return the unique instance of this class.
static DynamicElementImpl get instance =>
DynamicTypeImpl.instance.element as DynamicElementImpl;
/// Initialize a newly created instance of this class. Instances of this class
/// should <b>not</b> be created except as part of creating the type
/// associated with this element. The single instance of this class should be
/// accessed through the method [instance].
DynamicElementImpl() : super(Keyword.DYNAMIC.lexeme, -1) {
setModifier(Modifier.SYNTHETIC, true);
}
@override
ElementKind get kind => ElementKind.DYNAMIC;
@override
DartType get type => DynamicTypeImpl.instance;
@override
T accept<T>(ElementVisitor<T> visitor) => null;
}
/// A concrete implementation of an [ElementAnnotation].
class ElementAnnotationImpl implements ElementAnnotation {
/// The name of the top-level variable used to mark that a function always
/// throws, for dead code purposes.
static String _ALWAYS_THROWS_VARIABLE_NAME = "alwaysThrows";
/// The name of the class used to mark an element as being deprecated.
static String _DEPRECATED_CLASS_NAME = "Deprecated";
/// The name of the top-level variable used to mark an element as being
/// deprecated.
static String _DEPRECATED_VARIABLE_NAME = "deprecated";
/// The name of the top-level variable used to mark a method as being a
/// factory.
static String _FACTORY_VARIABLE_NAME = "factory";
/// The name of the top-level variable used to mark a class and its subclasses
/// as being immutable.
static String _IMMUTABLE_VARIABLE_NAME = "immutable";
/// The name of the top-level variable used to mark a constructor as being
/// literal.
static String _LITERAL_VARIABLE_NAME = "literal";
/// The name of the top-level variable used to mark a type as having
/// "optional" type arguments.
static String _OPTIONAL_TYPE_ARGS_VARIABLE_NAME = "optionalTypeArgs";
/// The name of the top-level variable used to mark a function as running
/// a single test.
static String _IS_TEST_VARIABLE_NAME = "isTest";
/// The name of the top-level variable used to mark a function as running
/// a test group.
static String _IS_TEST_GROUP_VARIABLE_NAME = "isTestGroup";
/// The name of the class used to JS annotate an element.
static String _JS_CLASS_NAME = "JS";
/// The name of `js` library, used to define JS annotations.
static String _JS_LIB_NAME = "js";
/// The name of `meta` library, used to define analysis annotations.
static String _META_LIB_NAME = "meta";
/// The name of the top-level variable used to mark a method as requiring
/// overriders to call super.
static String _MUST_CALL_SUPER_VARIABLE_NAME = "mustCallSuper";
/// The name of `angular.meta` library, used to define angular analysis
/// annotations.
static String _NG_META_LIB_NAME = "angular.meta";
/// The name of the top-level variable used to mark a method as being expected
/// to override an inherited method.
static String _OVERRIDE_VARIABLE_NAME = "override";
/// The name of the top-level variable used to mark a method as being
/// protected.
static String _PROTECTED_VARIABLE_NAME = "protected";
/// The name of the top-level variable used to mark a class as implementing a
/// proxy object.
static String PROXY_VARIABLE_NAME = "proxy";
/// The name of the class used to mark a parameter as being required.
static String _REQUIRED_CLASS_NAME = "Required";
/// The name of the top-level variable used to mark a parameter as being
/// required.
static String _REQUIRED_VARIABLE_NAME = "required";
/// The name of the top-level variable used to mark a class as being sealed.
static String _SEALED_VARIABLE_NAME = "sealed";
/// The name of the top-level variable used to mark a method as being
/// visible for templates.
static String _VISIBLE_FOR_TEMPLATE_VARIABLE_NAME = "visibleForTemplate";
/// The name of the top-level variable used to mark a method as being
/// visible for testing.
static String _VISIBLE_FOR_TESTING_VARIABLE_NAME = "visibleForTesting";
/// The element representing the field, variable, or constructor being used as
/// an annotation.
Element element;
/// The compilation unit in which this annotation appears.
CompilationUnitElementImpl compilationUnit;
/// The AST of the annotation itself, cloned from the resolved AST for the
/// source code.
Annotation annotationAst;
/// The result of evaluating this annotation as a compile-time constant
/// expression, or `null` if the compilation unit containing the variable has
/// not been resolved.
EvaluationResultImpl evaluationResult;
/// Initialize a newly created annotation. The given [compilationUnit] is the
/// compilation unit in which the annotation appears.
ElementAnnotationImpl(this.compilationUnit);
@override
List<AnalysisError> get constantEvaluationErrors =>
evaluationResult?.errors ?? const <AnalysisError>[];
@override
DartObject get constantValue => evaluationResult?.value;
@override
AnalysisContext get context => compilationUnit.library.context;
@override
bool get isAlwaysThrows =>
element is PropertyAccessorElement &&
element.name == _ALWAYS_THROWS_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isConstantEvaluated => evaluationResult != null;
@override
bool get isDeprecated {
if (element?.library?.isDartCore == true) {
if (element is ConstructorElement) {
return element.enclosingElement.name == _DEPRECATED_CLASS_NAME;
} else if (element is PropertyAccessorElement) {
return element.name == _DEPRECATED_VARIABLE_NAME;
}
}
return false;
}
@override
bool get isFactory =>
element is PropertyAccessorElement &&
element.name == _FACTORY_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isImmutable =>
element is PropertyAccessorElement &&
element.name == _IMMUTABLE_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isIsTest =>
element is PropertyAccessorElement &&
element.name == _IS_TEST_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isIsTestGroup =>
element is PropertyAccessorElement &&
element.name == _IS_TEST_GROUP_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isJS =>
element is ConstructorElement &&
element.enclosingElement.name == _JS_CLASS_NAME &&
element.library?.name == _JS_LIB_NAME;
@override
bool get isLiteral =>
element is PropertyAccessorElement &&
element.name == _LITERAL_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isMustCallSuper =>
element is PropertyAccessorElement &&
element.name == _MUST_CALL_SUPER_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isOptionalTypeArgs =>
element is PropertyAccessorElement &&
element.name == _OPTIONAL_TYPE_ARGS_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isOverride =>
element is PropertyAccessorElement &&
element.name == _OVERRIDE_VARIABLE_NAME &&
element.library?.isDartCore == true;
@override
bool get isProtected =>
element is PropertyAccessorElement &&
element.name == _PROTECTED_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isProxy =>
element is PropertyAccessorElement &&
element.name == PROXY_VARIABLE_NAME &&
element.library?.isDartCore == true;
@override
bool get isRequired =>
element is ConstructorElement &&
element.enclosingElement.name == _REQUIRED_CLASS_NAME &&
element.library?.name == _META_LIB_NAME ||
element is PropertyAccessorElement &&
element.name == _REQUIRED_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isSealed =>
element is PropertyAccessorElement &&
element.name == _SEALED_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
@override
bool get isVisibleForTemplate =>
element is PropertyAccessorElement &&
element.name == _VISIBLE_FOR_TEMPLATE_VARIABLE_NAME &&
element.library?.name == _NG_META_LIB_NAME;
@override
bool get isVisibleForTesting =>
element is PropertyAccessorElement &&
element.name == _VISIBLE_FOR_TESTING_VARIABLE_NAME &&
element.library?.name == _META_LIB_NAME;
/// Get the library containing this annotation.
Source get librarySource => compilationUnit.librarySource;
@override
Source get source => compilationUnit.source;
@override
DartObject computeConstantValue() {
if (evaluationResult == null) {
AnalysisOptionsImpl analysisOptions = context.analysisOptions;
computeConstants(context.typeProvider, context.typeSystem,
context.declaredVariables, [this], analysisOptions.experimentStatus);
}
return constantValue;
}
@override
String toSource() => annotationAst.toSource();
@override
String toString() => '@$element';
}
/// A base class for concrete implementations of an [Element].
abstract class ElementImpl implements Element {
/// An Unicode right arrow.
@deprecated
static final String RIGHT_ARROW = " \u2192 ";
static int _NEXT_ID = 0;
final int id = _NEXT_ID++;
/// The enclosing element of this element, or `null` if this element is at the
/// root of the element structure.
ElementImpl _enclosingElement;
Reference reference;
final AstNode linkedNode;
/// The name of this element.
String _name;
/// The offset of the name of this element in the file that contains the
/// declaration of this element.
int _nameOffset = 0;
/// A bit-encoded form of the modifiers associated with this element.
int _modifiers = 0;
/// A list containing all of the metadata associated with this element.
List<ElementAnnotation> _metadata;
/// A cached copy of the calculated hashCode for this element.
int _cachedHashCode;
/// A cached copy of the calculated location for this element.
ElementLocation _cachedLocation;
/// The documentation comment for this element.
String _docComment;
/// The offset of the beginning of the element's code in the file that
/// contains the element, or `null` if the element is synthetic.
int _codeOffset;
/// The length of the element's code, or `null` if the element is synthetic.
int _codeLength;
/// Initialize a newly created element to have the given [name] at the given
/// [_nameOffset].
ElementImpl(String name, this._nameOffset, {this.reference})
: linkedNode = null {
this._name = StringUtilities.intern(name);
this.reference?.element = this;
}
/// Initialize from linked node.
ElementImpl.forLinkedNode(
this._enclosingElement, this.reference, this.linkedNode) {
reference?.element ??= this;
}
/// Initialize a newly created element to have the given [name].
ElementImpl.forNode(Identifier name)
: this(name == null ? "" : name.name, name == null ? -1 : name.offset);
/// Initialize from serialized information.
ElementImpl.forSerialized(this._enclosingElement)
: reference = null,
linkedNode = null;
/// The length of the element's code, or `null` if the element is synthetic.
int get codeLength => _codeLength;
/// The offset of the beginning of the element's code in the file that
/// contains the element, or `null` if the element is synthetic.
int get codeOffset => _codeOffset;
@override
AnalysisContext get context {
if (_enclosingElement == null) {
return null;
}
return _enclosingElement.context;
}
@override
String get displayName => _name;
@override
String get documentationComment => _docComment;
/// The documentation comment source for this element.
void set documentationComment(String doc) {
assert(!isResynthesized);
_docComment = doc?.replaceAll('\r\n', '\n');
}
@override
Element get enclosingElement => _enclosingElement;
/// Set the enclosing element of this element to the given [element].
void set enclosingElement(Element element) {
_enclosingElement = element as ElementImpl;
}
/// Return the enclosing unit element (which might be the same as `this`), or
/// `null` if this element is not contained in any compilation unit.
CompilationUnitElementImpl get enclosingUnit {
return _enclosingElement?.enclosingUnit;
}
@override
bool get hasAlwaysThrows {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isAlwaysThrows) {
return true;
}
}
return false;
}
@override
bool get hasDeprecated {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isDeprecated) {
return true;
}
}
return false;
}
@override
bool get hasFactory {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isFactory) {
return true;
}
}
return false;
}
@override
int get hashCode {
// TODO: We might want to re-visit this optimization in the future.
// We cache the hash code value as this is a very frequently called method.
if (_cachedHashCode == null) {
_cachedHashCode = location.hashCode;
}
return _cachedHashCode;
}
@override
bool get hasIsTest {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isIsTest) {
return true;
}
}
return false;
}
@override
bool get hasIsTestGroup {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isIsTestGroup) {
return true;
}
}
return false;
}
@override
bool get hasJS {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isJS) {
return true;
}
}
return false;
}
@override
bool get hasLiteral {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isLiteral) {
return true;
}
}
return false;
}
@override
bool get hasMustCallSuper {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isMustCallSuper) {
return true;
}
}
return false;
}
@override
bool get hasOptionalTypeArgs {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isOptionalTypeArgs) {
return true;
}
}
return false;
}
@override
bool get hasOverride {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isOverride) {
return true;
}
}
return false;
}
@override
bool get hasProtected {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isProtected) {
return true;
}
}
return false;
}
@override
bool get hasRequired {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isRequired) {
return true;
}
}
return false;
}
@override
bool get hasSealed {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isSealed) {
return true;
}
}
return false;
}
@override
bool get hasVisibleForTemplate {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isVisibleForTemplate) {
return true;
}
}
return false;
}
@override
bool get hasVisibleForTesting {
var metadata = this.metadata;
for (var i = 0; i < metadata.length; i++) {
var annotation = metadata[i];
if (annotation.isVisibleForTesting) {
return true;
}
}
return false;
}
/// Return an identifier that uniquely identifies this element among the
/// children of this element's parent.
String get identifier => name;
@override
bool get isAlwaysThrows => hasAlwaysThrows;
@override
bool get isDeprecated => hasDeprecated;
@override
bool get isFactory => hasFactory;
@override
bool get isJS => hasJS;
@override
bool get isOverride => hasOverride;
@override
bool get isPrivate {
String name = displayName;
if (name == null) {
return true;
}
return Identifier.isPrivateName(name);
}
@override
bool get isProtected => hasProtected;
@override
bool get isPublic => !isPrivate;
@override
bool get isRequired => hasRequired;
/// Return `true` if this element is resynthesized from a summary.
bool get isResynthesized => enclosingUnit?.resynthesizerContext != null;
@override
bool get isSynthetic {
if (linkedNode != null) {
return linkedNode.isSynthetic;
}
return hasModifier(Modifier.SYNTHETIC);
}
/// Set whether this element is synthetic.
void set isSynthetic(bool isSynthetic) {
setModifier(Modifier.SYNTHETIC, isSynthetic);
}
@override
bool get isVisibleForTesting => hasVisibleForTesting;
@override
LibraryElement get library =>
getAncestor((element) => element is LibraryElement);
@override
Source get librarySource => library?.source;
LinkedUnitContext get linkedContext {
return _enclosingElement.linkedContext;
}
@override
ElementLocation get location {
if (_cachedLocation == null) {
if (library == null) {
return new ElementLocationImpl.con1(this);
}
_cachedLocation = new ElementLocationImpl.con1(this);
}
return _cachedLocation;
}
List<ElementAnnotation> get metadata {
if (linkedNode != null) {
if (_metadata != null) return _metadata;
var metadata = linkedContext.getMetadata(linkedNode);
return _metadata = _buildAnnotations2(enclosingUnit, metadata);
}
return _metadata ?? const <ElementAnnotation>[];
}
void set metadata(List<ElementAnnotation> metadata) {
assert(!isResynthesized);
_metadata = metadata;
}
@override
String get name => _name;
/// Changes the name of this element.
void set name(String name) {
this._name = name;
}
@override
int get nameLength => displayName != null ? displayName.length : 0;
@override
int get nameOffset => _nameOffset;
/// Sets the offset of the name of this element in the file that contains the
/// declaration of this element.
void set nameOffset(int offset) {
_nameOffset = offset;
}
@override
AnalysisSession get session {
return _enclosingElement?.session;
}
@override
Source get source {
if (_enclosingElement == null) {
return null;
}
return _enclosingElement.source;
}
/// Return the context to resolve type parameters in, or `null` if neither
/// this element nor any of its ancestors is of a kind that can declare type
/// parameters.
TypeParameterizedElementMixin get typeParameterContext {
return _enclosingElement?.typeParameterContext;
}
@deprecated
@override
CompilationUnit get unit {
throw UnimplementedError();
}
@override
bool operator ==(Object object) {
if (identical(this, object)) {
return true;
}
return object is Element &&
object.kind == kind &&
object.location == location;
}
/// Append to the given [buffer] a comma-separated list of the names of the
/// types of this element and every enclosing element.
void appendPathTo(StringBuffer buffer) {
Element element = this;
while (element != null) {
if (element != this) {
buffer.write(', ');
}
buffer.write(element.runtimeType);
String name = element.name;
if (name != null) {
buffer.write(' (');
buffer.write(name);
buffer.write(')');
}
element = element.enclosingElement;
}
}
/// Append a textual representation of this element to the given [buffer].
void appendTo(StringBuffer buffer) {
if (_name == null) {
buffer.write("<unnamed ");
buffer.write(runtimeType.toString());
buffer.write(">");
} else {
buffer.write(_name);
}
}
@override
String computeDocumentationComment() => documentationComment;
@deprecated
@override
AstNode computeNode() => getNodeMatching((node) => node is AstNode);
/// Set this element as the enclosing element for given [element].
void encloseElement(ElementImpl element) {
element.enclosingElement = this;
}
/// Set this element as the enclosing element for given [elements].
void encloseElements(List<Element> elements) {
for (Element element in elements) {
(element as ElementImpl)._enclosingElement = this;
}
}
@override
E getAncestor<E extends Element>(Predicate<Element> predicate) {
return getAncestorStatic<E>(_enclosingElement, predicate);
}
/// Return the child of this element that is uniquely identified by the given
/// [identifier], or `null` if there is no such child.
ElementImpl getChild(String identifier) => null;
@override
String getExtendedDisplayName(String shortName) {
if (shortName == null) {
shortName = displayName;
}
Source source = this.source;
if (source != null) {
return "$shortName (${source.fullName})";
}
return shortName;
}
/// Return the resolved [AstNode] of the given type enclosing [getNameOffset].
@deprecated
AstNode getNodeMatching(Predicate<AstNode> predicate) {
CompilationUnit unit = this.unit;
if (unit == null) {
return null;
}
int offset = nameOffset;
AstNode node = new NodeLocator(offset).searchWithin(unit);
if (node == null) {
return null;
}
return node.thisOrAncestorMatching(predicate);
}
/// Return `true` if this element has the given [modifier] associated with it.
bool hasModifier(Modifier modifier) =>
BooleanArray.get(_modifiers, modifier.ordinal);
@override
bool isAccessibleIn(LibraryElement library) {
if (Identifier.isPrivateName(name)) {
return library == this.library;
}
return true;
}
/// Use the given [visitor] to visit all of the [children] in the given array.
void safelyVisitChildren(List<Element> children, ElementVisitor visitor) {
if (children != null) {
for (Element child in children) {
child.accept(visitor);
}
}
}
/// Set the code range for this element.
void setCodeRange(int offset, int length) {
assert(!isResynthesized);
_codeOffset = offset;
_codeLength = length;
}
/// Set whether the given [modifier] is associated with this element to
/// correspond to the given [value].
void setModifier(Modifier modifier, bool value) {
_modifiers = BooleanArray.set(_modifiers, modifier.ordinal, value);
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
appendTo(buffer);
return buffer.toString();
}
@override
void visitChildren(ElementVisitor visitor) {
// There are no children to visit
}
/// Return annotations for the given [unlinkedConsts] in the [unit].
List<ElementAnnotation> _buildAnnotations(
CompilationUnitElementImpl unit, List<UnlinkedExpr> unlinkedConsts) {
int length = unlinkedConsts.length;
if (length != 0) {
List<ElementAnnotation> annotations = new List<ElementAnnotation>(length);
ResynthesizerContext context = unit.resynthesizerContext;
for (int i = 0; i < length; i++) {
annotations[i] = context.buildAnnotation(this, unlinkedConsts[i]);
}
return annotations;
} else {
return const <ElementAnnotation>[];
}
}
/// Return annotations for the given [nodeList] in the [unit].
List<ElementAnnotation> _buildAnnotations2(
CompilationUnitElementImpl unit, List<Annotation> nodeList) {
var length = nodeList.length;
if (length == 0) {
return const <ElementAnnotation>[];
}
var annotations = new List<ElementAnnotation>(length);
for (int i = 0; i < length; i++) {
var ast = nodeList[i];
annotations[i] = ElementAnnotationImpl(unit)
..annotationAst = ast
..element = ast.element;
}
return annotations;
}
/// If the element associated with the given [type] is a generic function type
/// element, then make it a child of this element. Return the [type] as a
/// convenience.
DartType _checkElementOfType(DartType type) {
Element element = type?.element;
if (element is GenericFunctionTypeElementImpl &&
element.enclosingElement == null) {
element.enclosingElement = this;
}
return type;
}
/// If the given [type] is a generic function type, then the element
/// associated with the type is implicitly a child of this element and should
/// be visited by the given [visitor].
void _safelyVisitPossibleChild(DartType type, ElementVisitor visitor) {
Element element = type?.element;
if (element is GenericFunctionTypeElementImpl &&
element.enclosingElement is! GenericTypeAliasElement) {
element.accept(visitor);
}
}
static int findElementIndexUsingIdentical(List items, Object item) {
int length = items.length;
for (int i = 0; i < length; i++) {
if (identical(items[i], item)) {
return i;
}
}
throw new StateError('Unable to find $item in $items');
}
static E getAncestorStatic<E extends Element>(
Element startingPoint, Predicate<Element> predicate) {
Element ancestor = startingPoint;
while (ancestor != null && !predicate(ancestor)) {
ancestor = ancestor.enclosingElement;
}
return ancestor as E;
}
}
/// A concrete implementation of an [ElementLocation].
class ElementLocationImpl implements ElementLocation {
/// The character used to separate components in the encoded form.
static int _SEPARATOR_CHAR = 0x3B;
/// The path to the element whose location is represented by this object.
List<String> _components;
/// The object managing [indexKeyId] and [indexLocationId].
Object indexOwner;
/// A cached id of this location in index.
int indexKeyId;
/// A cached id of this location in index.
int indexLocationId;
/// Initialize a newly created location to represent the given [element].
ElementLocationImpl.con1(Element element) {
List<String> components = new List<String>();
Element ancestor = element;
while (ancestor != null) {
components.insert(0, (ancestor as ElementImpl).identifier);
ancestor = ancestor.enclosingElement;
}
this._components = components;
}
/// Initialize a newly created location from the given [encoding].
ElementLocationImpl.con2(String encoding) {
this._components = _decode(encoding);
}
/// Initialize a newly created location from the given [components].
ElementLocationImpl.con3(List<String> components) {
this._components = components;
}
@override
List<String> get components => _components;
@override
String get encoding {
StringBuffer buffer = new StringBuffer();
int length = _components.length;
for (int i = 0; i < length; i++) {
if (i > 0) {
buffer.writeCharCode(_SEPARATOR_CHAR);
}
_encode(buffer, _components[i]);
}
return buffer.toString();
}
@override
int get hashCode {
int result = 0;
for (int i = 0; i < _components.length; i++) {
String component = _components[i];
result = JenkinsSmiHash.combine(result, component.hashCode);
}
return result;
}
@override
bool operator ==(Object object) {
if (identical(this, object)) {
return true;
}
if (object is ElementLocationImpl) {
List<String> otherComponents = object._components;
int length = _components.length;
if (otherComponents.length != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (_components[i] != otherComponents[i]) {
return false;
}
}
return true;
}
return false;
}
@override
String toString() => encoding;
/// Decode the [encoding] of a location into a list of components and return
/// the components.
List<String> _decode(String encoding) {
List<String> components = new List<String>();
StringBuffer buffer = new StringBuffer();
int index = 0;
int length = encoding.length;
while (index < length) {
int currentChar = encoding.codeUnitAt(index);
if (currentChar == _SEPARATOR_CHAR) {
if (index + 1 < length &&
encoding.codeUnitAt(index + 1) == _SEPARATOR_CHAR) {
buffer.writeCharCode(_SEPARATOR_CHAR);
index += 2;
} else {
components.add(buffer.toString());
buffer = new StringBuffer();
index++;
}
} else {
buffer.writeCharCode(currentChar);
index++;
}
}
components.add(buffer.toString());
return components;
}
/// Append an encoded form of the given [component] to the given [buffer].
void _encode(StringBuffer buffer, String component) {
int length = component.length;
for (int i = 0; i < length; i++) {
int currentChar = component.codeUnitAt(i);
if (currentChar == _SEPARATOR_CHAR) {
buffer.writeCharCode(_SEPARATOR_CHAR);
}
buffer.writeCharCode(currentChar);
}
}
}
/// An [AbstractClassElementImpl] which is an enum.
class EnumElementImpl extends AbstractClassElementImpl {
/// The unlinked representation of the enum in the summary.
final UnlinkedEnum _unlinkedEnum;
/// The type defined by the enum.
InterfaceType _type;
/// Initialize a newly created class element to have the given [name] at the
/// given [offset] in the file that contains the declaration of this element.
EnumElementImpl(String name, int offset)
: _unlinkedEnum = null,
super(name, offset);
EnumElementImpl.forLinkedNode(CompilationUnitElementImpl enclosing,
Reference reference, EnumDeclaration linkedNode)
: _unlinkedEnum = null,
super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created class element to have the given [name].
EnumElementImpl.forNode(Identifier name)
: _unlinkedEnum = null,
super.forNode(name);
/// Initialize using the given serialized information.
EnumElementImpl.forSerialized(
this._unlinkedEnum, CompilationUnitElementImpl enclosingUnit)
: super.forSerialized(enclosingUnit);
@override
List<PropertyAccessorElement> get accessors {
if (_accessors == null) {
if (linkedNode != null) {
_resynthesizeMembers2();
}
if (_unlinkedEnum != null) {
_resynthesizeMembers();
}
}
return _accessors ?? const <PropertyAccessorElement>[];
}
@override
void set accessors(List<PropertyAccessorElement> accessors) {
_assertNotResynthesized(_unlinkedEnum);
super.accessors = accessors;
}
@override
List<InterfaceType> get allSupertypes => <InterfaceType>[supertype];
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (_unlinkedEnum != null) {
return _unlinkedEnum.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (_unlinkedEnum != null) {
return _unlinkedEnum.codeRange?.offset;
}
return super.codeOffset;
}
@override
List<ConstructorElement> get constructors {
// The equivalent code for enums in the spec shows a single constructor,
// but that constructor is not callable (since it is a compile-time error
// to subclass, mix-in, implement, or explicitly instantiate an enum).
// So we represent this as having no constructors.
return const <ConstructorElement>[];
}
@override
String get documentationComment {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var comment = context.getDocumentationComment(linkedNode);
return getCommentNodeRawText(comment);
}
if (_unlinkedEnum != null) {
return _unlinkedEnum.documentationComment?.text;
}
return super.documentationComment;
}
@override
List<FieldElement> get fields {
if (_fields == null) {
if (linkedNode != null) {
_resynthesizeMembers2();
}
if (_unlinkedEnum != null) {
_resynthesizeMembers();
}
}
return _fields ?? const <FieldElement>[];
}
@override
void set fields(List<FieldElement> fields) {
_assertNotResynthesized(_unlinkedEnum);
super.fields = fields;
}
@override
bool get hasNonFinalField => false;
@override
bool get hasReferenceToSuper => false;
@override
bool get hasStaticMember => true;
@override
List<InterfaceType> get interfaces => const <InterfaceType>[];
@override
bool get isAbstract => false;
@override
bool get isEnum => true;
@override
bool get isMixinApplication => false;
@override
bool get isOrInheritsProxy => false;
@override
bool get isProxy => false;
@override
bool get isSimplyBounded => true;
@override
bool get isValidMixin => false;
@override
List<ElementAnnotation> get metadata {
if (_unlinkedEnum != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, _unlinkedEnum.annotations);
}
return super.metadata;
}
@override
List<MethodElement> get methods {
if (_methods == null) {
if (linkedNode != null) {
_resynthesizeMembers2();
}
if (_unlinkedEnum != null) {
_resynthesizeMembers();
}
}
return _methods ?? const <MethodElement>[];
}
@override
List<InterfaceType> get mixins => const <InterfaceType>[];
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
if (_unlinkedEnum != null) {
return _unlinkedEnum.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0 && _unlinkedEnum != null && _unlinkedEnum.nameOffset != 0) {
return _unlinkedEnum.nameOffset;
}
return offset;
}
@override
InterfaceType get supertype => context.typeProvider.objectType;
@override
InterfaceType get type {
if (_type == null) {
InterfaceTypeImpl type = new InterfaceTypeImpl(this);
type.typeArguments = const <DartType>[];
_type = type;
}
return _type;
}
@override
List<TypeParameterElement> get typeParameters =>
const <TypeParameterElement>[];
@override
ConstructorElement get unnamedConstructor => null;
@override
void appendTo(StringBuffer buffer) {
buffer.write('enum ');
String name = displayName;
if (name == null) {
buffer.write("{unnamed enum}");
} else {
buffer.write(name);
}
}
/// Create the only method enums have - `toString()`.
void createToStringMethodElement() {
var method = new MethodElementImpl('toString', -1);
method.isSynthetic = true;
if (linkedNode != null || _unlinkedEnum != null) {
method.returnType = context.typeProvider.stringType;
method.type = new FunctionTypeImpl(method);
}
method.enclosingElement = this;
if (linkedNode != null) {
method.reference = reference.getChild('@method').getChild('toString');
}
_methods = <MethodElement>[method];
}
@override
ConstructorElement getNamedConstructor(String name) => null;
void _resynthesizeMembers() {
List<FieldElementImpl> fields = <FieldElementImpl>[];
// Build the 'index' field.
fields.add(new FieldElementImpl('index', -1)
..enclosingElement = this
..isSynthetic = true
..isFinal = true
..type = context.typeProvider.intType);
// Build the 'values' field.
fields.add(new ConstFieldElementImpl_EnumValues(this));
// Build fields for all enum constants.
if (_unlinkedEnum != null) {
for (int i = 0; i < _unlinkedEnum.values.length; i++) {
UnlinkedEnumValue unlinkedValue = _unlinkedEnum.values[i];
ConstFieldElementImpl_EnumValue field =
new ConstFieldElementImpl_EnumValue(this, unlinkedValue, i);
fields.add(field);
}
}
// done
_fields = fields;
_accessors = fields
.map((FieldElementImpl field) =>
new PropertyAccessorElementImpl_ImplicitGetter(field)
..enclosingElement = this)
.toList(growable: false);
createToStringMethodElement();
}
void _resynthesizeMembers2() {
var fields = <FieldElementImpl>[];
var getters = <PropertyAccessorElementImpl>[];
// Build the 'index' field.
{
var field = FieldElementImpl('index', -1)
..enclosingElement = this
..isSynthetic = true
..isFinal = true
..type = context.typeProvider.intType;
fields.add(field);
getters.add(PropertyAccessorElementImpl_ImplicitGetter(field,
reference: reference.getChild('@getter').getChild('index'))
..enclosingElement = this);
}
// Build the 'values' field.
{
var field = ConstFieldElementImpl_EnumValues(this);
fields.add(field);
getters.add(PropertyAccessorElementImpl_ImplicitGetter(field,
reference: reference.getChild('@getter').getChild('values'))
..enclosingElement = this);
}
// Build fields for all enum constants.
var containerRef = this.reference.getChild('@constant');
var constants = linkedContext.getEnumConstants(linkedNode);
for (var i = 0; i < constants.length; ++i) {
var constant = constants[i];
var name = constant.name.name;
var reference = containerRef.getChild(name);
var field = new ConstFieldElementImpl_EnumValue.forLinkedNode(
this, reference, constant, i);
fields.add(field);
getters.add(field.getter);
}
_fields = fields;
_accessors = getters;
createToStringMethodElement();
}
}
/// A base class for concrete implementations of an [ExecutableElement].
abstract class ExecutableElementImpl extends ElementImpl
with TypeParameterizedElementMixin
implements ExecutableElement {
/// The unlinked representation of the executable in the summary.
final UnlinkedExecutable serializedExecutable;
/// A list containing all of the parameters defined by this executable
/// element.
List<ParameterElement> _parameters;
/// The declared return type of this executable element.
DartType _declaredReturnType;
/// The inferred return type of this executable element.
DartType _returnType;
/// The type of function defined by this executable element.
FunctionType _type;
/// Initialize a newly created executable element to have the given [name] and
/// [offset].
ExecutableElementImpl(String name, int offset, {Reference reference})
: serializedExecutable = null,
super(name, offset, reference: reference);
/// Initialize using the given linked node.
ExecutableElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: serializedExecutable = null,
super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created executable element to have the given [name].
ExecutableElementImpl.forNode(Identifier name)
: serializedExecutable = null,
super.forNode(name);
/// Initialize using the given serialized information.
ExecutableElementImpl.forSerialized(
this.serializedExecutable, ElementImpl enclosingElement)
: super.forSerialized(enclosingElement);
/// Set whether this executable element's body is asynchronous.
void set asynchronous(bool isAsynchronous) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.ASYNCHRONOUS, isAsynchronous);
}
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.codeRange?.offset;
}
return super.codeOffset;
}
void set declaredReturnType(DartType returnType) {
_assertNotResynthesized(serializedExecutable);
_declaredReturnType = _checkElementOfType(returnType);
}
@override
String get displayName {
if (linkedNode != null) {
return reference.name;
}
if (serializedExecutable != null) {
return serializedExecutable.name;
}
return super.displayName;
}
@override
String get documentationComment {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var comment = context.getDocumentationComment(linkedNode);
return getCommentNodeRawText(comment);
}
if (serializedExecutable != null) {
return serializedExecutable.documentationComment?.text;
}
return super.documentationComment;
}
/// Set whether this executable element is external.
void set external(bool isExternal) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.EXTERNAL, isExternal);
}
/// Set whether this method's body is a generator.
void set generator(bool isGenerator) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.GENERATOR, isGenerator);
}
@override
bool get hasImplicitReturnType {
if (linkedNode != null) {
return linkedContext.hasImplicitReturnType(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.returnType == null &&
serializedExecutable.kind != UnlinkedExecutableKind.constructor;
}
return hasModifier(Modifier.IMPLICIT_TYPE);
}
/// Set whether this executable element has an implicit return type.
void set hasImplicitReturnType(bool hasImplicitReturnType) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.IMPLICIT_TYPE, hasImplicitReturnType);
}
@override
bool get isAbstract {
if (linkedNode != null) {
return !isExternal && enclosingUnit.linkedContext.isAbstract(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.isAbstract;
}
return hasModifier(Modifier.ABSTRACT);
}
@override
bool get isAsynchronous {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isAsynchronous(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.isAsynchronous;
}
return hasModifier(Modifier.ASYNCHRONOUS);
}
@override
bool get isExternal {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isExternal(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.isExternal;
}
return hasModifier(Modifier.EXTERNAL);
}
@override
bool get isGenerator {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isGenerator(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.isGenerator;
}
return hasModifier(Modifier.GENERATOR);
}
@override
bool get isOperator => false;
@override
bool get isSynchronous => !isAsynchronous;
@override
List<ElementAnnotation> get metadata {
if (serializedExecutable != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, serializedExecutable.annotations);
}
return super.metadata;
}
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
if (serializedExecutable != null) {
return serializedExecutable.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0 && serializedExecutable != null) {
return serializedExecutable.nameOffset;
}
return offset;
}
@override
List<ParameterElement> get parameters {
if (_parameters != null) return _parameters;
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var containerRef = reference.getChild('@parameter');
var formalParameters = context.getFormalParameters(linkedNode);
_parameters = ParameterElementImpl.forLinkedNodeList(
this,
context,
containerRef,
formalParameters,
);
}
if (serializedExecutable != null) {
_parameters = ParameterElementImpl.resynthesizeList(
serializedExecutable.parameters, this);
}
return _parameters ??= const <ParameterElement>[];
}
/// Set the parameters defined by this executable element to the given
/// [parameters].
void set parameters(List<ParameterElement> parameters) {
_assertNotResynthesized(serializedExecutable);
for (ParameterElement parameter in parameters) {
(parameter as ParameterElementImpl).enclosingElement = this;
}
this._parameters = parameters;
}
@override
DartType get returnType {
if (linkedNode != null) {
if (_returnType != null) return _returnType;
var context = enclosingUnit.linkedContext;
return _returnType = context.getReturnType(linkedNode);
}
if (serializedExecutable != null &&
_declaredReturnType == null &&
_returnType == null) {
bool isSetter =
serializedExecutable.kind == UnlinkedExecutableKind.setter;
_returnType = enclosingUnit.resynthesizerContext
.resolveLinkedType(this, serializedExecutable.inferredReturnTypeSlot);
_declaredReturnType = enclosingUnit.resynthesizerContext.resolveTypeRef(
this, serializedExecutable.returnType,
defaultVoid: isSetter, declaredType: true);
}
return _returnType ?? _declaredReturnType;
}
void set returnType(DartType returnType) {
if (linkedNode != null) {
linkedContext.setReturnType(linkedNode, returnType);
}
_assertNotResynthesized(serializedExecutable);
_returnType = _checkElementOfType(returnType);
}
@override
FunctionType get type {
if (linkedNode != null) {
return _type ??= new FunctionTypeImpl(this);
}
if (serializedExecutable != null) {
return _type ??= new FunctionTypeImpl(this);
}
return _type;
}
void set type(FunctionType type) {
_assertNotResynthesized(serializedExecutable);
_type = type;
}
/// Set the type parameters defined by this executable element to the given
/// [typeParameters].
void set typeParameters(List<TypeParameterElement> typeParameters) {
_assertNotResynthesized(serializedExecutable);
for (TypeParameterElement parameter in typeParameters) {
(parameter as TypeParameterElementImpl).enclosingElement = this;
}
this._typeParameterElements = typeParameters;
}
@override
List<UnlinkedTypeParam> get unlinkedTypeParams =>
serializedExecutable?.typeParameters;
@override
void appendTo(StringBuffer buffer) {
appendToWithName(buffer, displayName);
}
/// Append a textual representation of this element to the given [buffer]. The
/// [name] is the name of the executable element or `null` if the element has
/// no name. If [includeType] is `true` then the return type will be included.
void appendToWithName(StringBuffer buffer, String name) {
FunctionType functionType = type;
if (functionType != null) {
buffer.write(functionType.returnType);
if (name != null) {
buffer.write(' ');
buffer.write(name);
}
} else if (name != null) {
buffer.write(name);
}
if (this.kind != ElementKind.GETTER) {
int typeParameterCount = typeParameters.length;
if (typeParameterCount > 0) {
buffer.write('<');
for (int i = 0; i < typeParameterCount; i++) {
if (i > 0) {
buffer.write(', ');
}
(typeParameters[i] as TypeParameterElementImpl).appendTo(buffer);
}
buffer.write('>');
}
buffer.write('(');
String closing;
ParameterKind kind = ParameterKind.REQUIRED;
int parameterCount = parameters.length;
for (int i = 0; i < parameterCount; i++) {
if (i > 0) {
buffer.write(', ');
}
ParameterElement parameter = parameters[i];
// ignore: deprecated_member_use_from_same_package
ParameterKind parameterKind = parameter.parameterKind;
if (parameterKind != kind) {
if (closing != null) {
buffer.write(closing);
}
if (parameter.isOptionalPositional) {
buffer.write('[');
closing = ']';
} else if (parameter.isNamed) {
buffer.write('{');
if (parameter.isRequiredNamed) {
buffer.write('required ');
}
closing = '}';
} else {
closing = null;
}
}
kind = parameterKind;
parameter.appendToWithoutDelimiters(buffer);
}
if (closing != null) {
buffer.write(closing);
}
buffer.write(')');
}
}
@override
ElementImpl getChild(String identifier) {
for (ParameterElement parameter in parameters) {
ParameterElementImpl parameterImpl = parameter;
if (parameterImpl.identifier == identifier) {
return parameterImpl;
}
}
return null;
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
_safelyVisitPossibleChild(returnType, visitor);
safelyVisitChildren(typeParameters, visitor);
safelyVisitChildren(parameters, visitor);
}
}
/// A concrete implementation of an [ExportElement].
class ExportElementImpl extends UriReferencedElementImpl
implements ExportElement {
/// The unlinked representation of the export in the summary.
final UnlinkedExportPublic _unlinkedExportPublic;
/// The unlinked representation of the export in the summary.
final UnlinkedExportNonPublic _unlinkedExportNonPublic;
/// The library that is exported from this library by this export directive.
LibraryElement _exportedLibrary;
/// The combinators that were specified as part of the export directive in the
/// order in which they were specified.
List<NamespaceCombinator> _combinators;
/// The URI that was selected based on the declared variables.
String _selectedUri;
/// Initialize a newly created export element at the given [offset].
ExportElementImpl(int offset)
: _unlinkedExportPublic = null,
_unlinkedExportNonPublic = null,
super(null, offset);
ExportElementImpl.forLinkedNode(
LibraryElementImpl enclosing, ExportDirective linkedNode)
: _unlinkedExportPublic = null,
_unlinkedExportNonPublic = null,
super.forLinkedNode(enclosing, null, linkedNode);
/// Initialize using the given serialized information.
ExportElementImpl.forSerialized(this._unlinkedExportPublic,
this._unlinkedExportNonPublic, LibraryElementImpl enclosingLibrary)
: super.forSerialized(enclosingLibrary);
@override
List<NamespaceCombinator> get combinators {
if (_combinators != null) return _combinators;
if (linkedNode != null) {
ExportDirective node = linkedNode;
return _combinators = ImportElementImpl._buildCombinators2(
enclosingUnit.linkedContext,
node.combinators,
);
}
if (_unlinkedExportPublic != null) {
return _combinators = ImportElementImpl._buildCombinators(
_unlinkedExportPublic.combinators);
}
return _combinators ?? const <NamespaceCombinator>[];
}
void set combinators(List<NamespaceCombinator> combinators) {
_assertNotResynthesized(_unlinkedExportPublic);
_combinators = combinators;
}
@override
CompilationUnitElementImpl get enclosingUnit {
LibraryElementImpl enclosingLibrary = enclosingElement;
return enclosingLibrary._definingCompilationUnit;
}
@override
LibraryElement get exportedLibrary {
if (_exportedLibrary != null) return _exportedLibrary;
if (linkedNode != null) {
return _exportedLibrary = linkedContext.directiveLibrary(linkedNode);
}
if (_unlinkedExportNonPublic != null) {
LibraryElementImpl library = enclosingElement as LibraryElementImpl;
_exportedLibrary = library.resynthesizerContext.buildExportedLibrary(uri);
}
return _exportedLibrary;
}
void set exportedLibrary(LibraryElement exportedLibrary) {
_assertNotResynthesized(_unlinkedExportNonPublic);
_exportedLibrary = exportedLibrary;
}
@override
String get identifier => exportedLibrary.name;
@override
ElementKind get kind => ElementKind.EXPORT;
@override
List<ElementAnnotation> get metadata {
if (_metadata == null) {
if (_unlinkedExportNonPublic != null) {
return _metadata = _buildAnnotations(library.definingCompilationUnit,
_unlinkedExportNonPublic.annotations);
}
}
return super.metadata;
}
void set metadata(List<ElementAnnotation> metadata) {
_assertNotResynthesized(_unlinkedExportNonPublic);
super.metadata = metadata;
}
@override
int get nameOffset {
if (linkedNode != null) {
return linkedContext.getDirectiveOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0 && _unlinkedExportNonPublic != null) {
return _unlinkedExportNonPublic.offset;
}
return offset;
}
@override
String get uri {
if (linkedNode != null) {
ExportDirective node = linkedNode;
return node.uri.stringValue;
}
if (_unlinkedExportPublic != null) {
return _selectedUri ??= _selectUri(
_unlinkedExportPublic.uri, _unlinkedExportPublic.configurations);
}
return super.uri;
}
@override
void set uri(String uri) {
_assertNotResynthesized(_unlinkedExportPublic);
super.uri = uri;
}
@override
int get uriEnd {
if (_unlinkedExportNonPublic != null) {
return _unlinkedExportNonPublic.uriEnd;
}
return super.uriEnd;
}
@override
void set uriEnd(int uriEnd) {
_assertNotResynthesized(_unlinkedExportNonPublic);
super.uriEnd = uriEnd;
}
@override
int get uriOffset {
if (_unlinkedExportNonPublic != null) {
return _unlinkedExportNonPublic.uriOffset;
}
return super.uriOffset;
}
@override
void set uriOffset(int uriOffset) {
_assertNotResynthesized(_unlinkedExportNonPublic);
super.uriOffset = uriOffset;
}
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitExportElement(this);
@override
void appendTo(StringBuffer buffer) {
buffer.write("export ");
LibraryElementImpl.getImpl(exportedLibrary).appendTo(buffer);
}
}
/// A concrete implementation of an [ExtensionElement].
class ExtensionElementImpl extends ElementImpl
with TypeParameterizedElementMixin
implements ExtensionElement {
/// The unlinked representation of the extension in the summary.
final UnlinkedExtension _unlinkedExtension;
/// The type being extended.
DartType _extendedType;
/// A list containing all of the accessors (getters and setters) contained in
/// this extension.
List<PropertyAccessorElement> _accessors;
/// A list containing all of the fields contained in this extension.
List<FieldElement> _fields;
/// A list containing all of the methods contained in this extension.
List<MethodElement> _methods;
/// Initialize a newly created extension element to have the given [name] at
/// the given [offset] in the file that contains the declaration of this
/// element.
ExtensionElementImpl(String name, int nameOffset)
: _unlinkedExtension = null,
super(name, nameOffset);
/// Initialize using the given linked information.
ExtensionElementImpl.forLinkedNode(CompilationUnitElementImpl enclosing,
Reference reference, AstNode linkedNode)
: _unlinkedExtension = null,
super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created extension element to have the given [name].
ExtensionElementImpl.forNode(Identifier name)
: _unlinkedExtension = null,
super.forNode(name);
/// Initialize using the given serialized information.
ExtensionElementImpl.forSerialized(
this._unlinkedExtension, CompilationUnitElementImpl enclosingUnit)
: super.forSerialized(enclosingUnit);
@override
List<PropertyAccessorElement> get accessors {
if (_accessors != null) {
return _accessors;
}
if (linkedNode != null) {
if (linkedNode is ExtensionDeclaration) {
_createPropertiesAndAccessors();
assert(_accessors != null);
return _accessors;
} else {
return _accessors = const [];
}
} else if (_unlinkedExtension != null) {
_resynthesizeFieldsAndPropertyAccessors();
}
return _accessors ??= const <PropertyAccessorElement>[];
}
void set accessors(List<PropertyAccessorElement> accessors) {
_assertNotResynthesized(_unlinkedExtension);
for (PropertyAccessorElement accessor in accessors) {
(accessor as PropertyAccessorElementImpl).enclosingElement = this;
}
_accessors = accessors;
}
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (_unlinkedExtension != null) {
return _unlinkedExtension.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (_unlinkedExtension != null) {
return _unlinkedExtension.codeRange?.offset;
}
return super.codeOffset;
}
@override
String get displayName => name;
@override
String get documentationComment {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var comment = context.getDocumentationComment(linkedNode);
return getCommentNodeRawText(comment);
}
if (_unlinkedExtension != null) {
return _unlinkedExtension.documentationComment?.text;
}
return super.documentationComment;
}
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext => null;
@override
DartType get extendedType {
if (_extendedType != null) {
return _extendedType;
}
if (linkedNode != null) {
return _extendedType = linkedContext.getExtendedType(linkedNode).type;
} else if (_unlinkedExtension != null) {
return _extendedType = enclosingUnit.resynthesizerContext
.resolveTypeRef(this, _unlinkedExtension.extendedType);
}
return _extendedType;
}
void set extendedType(DartType extendedType) {
_assertNotResynthesized(_unlinkedExtension);
_extendedType = extendedType;
}
@override
List<FieldElement> get fields {
if (_fields != null) {
return _fields;
}
if (linkedNode != null) {
if (linkedNode is ExtensionDeclaration) {
_createPropertiesAndAccessors();
assert(_fields != null);
return _fields;
} else {
return _fields = const [];
}
} else if (_unlinkedExtension != null) {
_resynthesizeFieldsAndPropertyAccessors();
}
return _fields ?? const <FieldElement>[];
}
void set fields(List<FieldElement> fields) {
_assertNotResynthesized(_unlinkedExtension);
for (FieldElement field in fields) {
(field as FieldElementImpl).enclosingElement = this;
}
_fields = fields;
}
@override
String get identifier {
if (linkedNode != null) {
return reference.name;
}
return super.identifier;
}
@override
bool get isSimplyBounded => true;
@override
ElementKind get kind => ElementKind.EXTENSION;
@override
List<ElementAnnotation> get metadata {
if (_unlinkedExtension != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, _unlinkedExtension.annotations);
}
return super.metadata;
}
@override
List<MethodElement> get methods {
if (_methods != null) {
return _methods;
}
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var containerRef = reference.getChild('@method');
return _methods = context
.getMethods(linkedNode)
.where((node) => node.propertyKeyword == null)
.map((node) {
var name = node.name.name;
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
return reference.element as MethodElement;
}
return MethodElementImpl.forLinkedNode(this, reference, node);
}).toList();
} else if (_unlinkedExtension != null) {
var unlinkedExecutables = _unlinkedExtension.executables;
var length = unlinkedExecutables.length;
if (length == 0) {
return _methods = const <MethodElement>[];
}
var count = 0;
for (var i = 0; i < length; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.functionOrMethod) {
count++;
}
}
if (count == 0) {
return _methods = const <MethodElement>[];
}
var methods = new List<MethodElement>(count);
var index = 0;
for (var i = 0; i < length; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.functionOrMethod) {
methods[index++] = new MethodElementImpl.forSerialized(e, this);
}
}
return _methods = methods;
}
return _methods = const <MethodElement>[];
}
/// Set the methods contained in this extension to the given [methods].
void set methods(List<MethodElement> methods) {
_assertNotResynthesized(_unlinkedExtension);
for (MethodElement method in methods) {
(method as MethodElementImpl).enclosingElement = this;
}
_methods = methods;
}
@override
String get name {
if (linkedNode != null) {
return (linkedNode as ExtensionDeclaration).name?.name ?? '';
}
if (_unlinkedExtension != null) {
return _unlinkedExtension.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0 && _unlinkedExtension != null) {
return _unlinkedExtension.nameOffset;
}
return offset;
}
/// Set the type parameters defined by this extension to the given
/// [typeParameters].
void set typeParameters(List<TypeParameterElement> typeParameters) {
_assertNotResynthesized(_unlinkedExtension);
for (TypeParameterElement typeParameter in typeParameters) {
(typeParameter as TypeParameterElementImpl).enclosingElement = this;
}
this._typeParameterElements = typeParameters;
}
@override
List<UnlinkedTypeParam> get unlinkedTypeParams =>
_unlinkedExtension?.typeParameters;
@override
T accept<T>(ElementVisitor<T> visitor) {
return visitor.visitExtensionElement(this);
}
@override
void appendTo(StringBuffer buffer) {
buffer.write('extension ');
String name = displayName;
if (name == null) {
buffer.write("(unnamed)");
} else {
buffer.write(name);
}
int variableCount = typeParameters.length;
if (variableCount > 0) {
buffer.write("<");
for (int i = 0; i < variableCount; i++) {
if (i > 0) {
buffer.write(", ");
}
(typeParameters[i] as TypeParameterElementImpl).appendTo(buffer);
}
buffer.write(">");
}
if (extendedType != null && !extendedType.isObject) {
buffer.write(' on ');
buffer.write(extendedType.displayName);
}
}
@override
PropertyAccessorElement getGetter(String getterName) {
int length = accessors.length;
for (int i = 0; i < length; i++) {
PropertyAccessorElement accessor = accessors[i];
if (accessor.isGetter && accessor.name == getterName) {
return accessor;
}
}
return null;
}
@override
MethodElement getMethod(String methodName) {
int length = methods.length;
for (int i = 0; i < length; i++) {
MethodElement method = methods[i];
if (method.name == methodName) {
return method;
}
}
return null;
}
@override
PropertyAccessorElement getSetter(String setterName) {
return AbstractClassElementImpl.getSetterFromAccessors(
setterName, accessors);
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
safelyVisitChildren(accessors, visitor);
safelyVisitChildren(fields, visitor);
safelyVisitChildren(methods, visitor);
safelyVisitChildren(typeParameters, visitor);
}
/// Create the accessors and fields when [linkedNode] is not `null`.
void _createPropertiesAndAccessors() {
assert(_accessors == null);
assert(_fields == null);
var context = enclosingUnit.linkedContext;
var accessorList = <PropertyAccessorElement>[];
var fieldList = <FieldElement>[];
var fields = context.getFields(linkedNode);
for (var field in fields) {
var name = field.name.name;
var fieldElement = FieldElementImpl.forLinkedNodeFactory(
this,
reference.getChild('@field').getChild(name),
field,
);
fieldList.add(fieldElement);
accessorList.add(fieldElement.getter);
if (fieldElement.setter != null) {
accessorList.add(fieldElement.setter);
}
}
var methods = context.getMethods(linkedNode);
for (var method in methods) {
var isGetter = method.isGetter;
var isSetter = method.isSetter;
if (!isGetter && !isSetter) continue;
var name = method.name.name;
var containerRef = isGetter
? reference.getChild('@getter')
: reference.getChild('@setter');
var accessorElement = PropertyAccessorElementImpl.forLinkedNode(
this,
containerRef.getChild(name),
method,
);
accessorList.add(accessorElement);
var fieldRef = reference.getChild('@field').getChild(name);
FieldElementImpl field = fieldRef.element;
if (field == null) {
field = new FieldElementImpl(name, -1);
fieldRef.element = field;
field.enclosingElement = this;
field.isSynthetic = true;
field.isFinal = isGetter;
field.isStatic = accessorElement.isStatic;
fieldList.add(field);
} else {
// TODO(brianwilkerson) Shouldn't this depend on whether there is a
// setter?
field.isFinal = false;
}
accessorElement.variable = field;
if (isGetter) {
field.getter = accessorElement;
} else {
field.setter = accessorElement;
}
}
_accessors = accessorList;
_fields = fieldList;
}
/// Resynthesize explicit fields and property accessors and fill [_fields] and
/// [_accessors] with explicit and implicit elements.
void _resynthesizeFieldsAndPropertyAccessors() {
assert(_fields == null);
assert(_accessors == null);
var unlinkedFields = _unlinkedExtension.fields;
var unlinkedExecutables = _unlinkedExtension.executables;
// Build explicit fields and implicit property accessors.
List<FieldElement> explicitFields;
List<PropertyAccessorElement> implicitAccessors;
var unlinkedFieldsLength = unlinkedFields.length;
if (unlinkedFieldsLength != 0) {
explicitFields = new List<FieldElement>(unlinkedFieldsLength);
implicitAccessors = <PropertyAccessorElement>[];
for (var i = 0; i < unlinkedFieldsLength; i++) {
var v = unlinkedFields[i];
FieldElementImpl field =
new FieldElementImpl.forSerializedFactory(v, this);
explicitFields[i] = field;
implicitAccessors.add(
new PropertyAccessorElementImpl_ImplicitGetter(field)
..enclosingElement = this);
if (!field.isConst && !field.isFinal) {
implicitAccessors.add(
new PropertyAccessorElementImpl_ImplicitSetter(field)
..enclosingElement = this);
}
}
} else {
explicitFields = const <FieldElement>[];
implicitAccessors = const <PropertyAccessorElement>[];
}
var unlinkedExecutablesLength = unlinkedExecutables.length;
var getterSetterCount = 0;
for (var i = 0; i < unlinkedExecutablesLength; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.getter ||
e.kind == UnlinkedExecutableKind.setter) {
getterSetterCount++;
}
}
// Build explicit property accessors and implicit fields.
List<PropertyAccessorElement> explicitAccessors;
Map<String, FieldElementImpl> implicitFields;
if (getterSetterCount != 0) {
explicitAccessors = new List<PropertyAccessorElement>(getterSetterCount);
implicitFields = <String, FieldElementImpl>{};
var index = 0;
for (var i = 0; i < unlinkedExecutablesLength; i++) {
var e = unlinkedExecutables[i];
if (e.kind == UnlinkedExecutableKind.getter ||
e.kind == UnlinkedExecutableKind.setter) {
PropertyAccessorElementImpl accessor =
new PropertyAccessorElementImpl.forSerialized(e, this);
explicitAccessors[index++] = accessor;
// Create or update the implicit field.
String fieldName = accessor.displayName;
FieldElementImpl field = implicitFields[fieldName];
if (field == null) {
field = new FieldElementImpl(fieldName, -1);
implicitFields[fieldName] = field;
field.enclosingElement = this;
field.isSynthetic = true;
field.isFinal = e.kind == UnlinkedExecutableKind.getter;
field.isStatic = e.isStatic;
} else {
field.isFinal = false;
}
accessor.variable = field;
if (e.kind == UnlinkedExecutableKind.getter) {
field.getter = accessor;
} else {
field.setter = accessor;
}
}
}
} else {
explicitAccessors = const <PropertyAccessorElement>[];
implicitFields = const <String, FieldElementImpl>{};
}
// Combine explicit and implicit fields and property accessors.
if (implicitFields.isEmpty) {
_fields = explicitFields;
} else if (explicitFields.isEmpty) {
_fields = implicitFields.values.toList(growable: false);
} else {
_fields = <FieldElement>[]
..addAll(explicitFields)
..addAll(implicitFields.values);
}
if (explicitAccessors.isEmpty) {
_accessors = implicitAccessors;
} else if (implicitAccessors.isEmpty) {
_accessors = explicitAccessors;
} else {
_accessors = <PropertyAccessorElement>[]
..addAll(explicitAccessors)
..addAll(implicitAccessors);
}
}
}
/// A concrete implementation of a [FieldElement].
class FieldElementImpl extends PropertyInducingElementImpl
implements FieldElement {
/// Initialize a newly created synthetic field element to have the given
/// [name] at the given [offset].
FieldElementImpl(String name, int offset) : super(name, offset);
FieldElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode) {
if (!linkedNode.isSynthetic) {
var enclosingRef = enclosing.reference;
this.getter = PropertyAccessorElementImpl_ImplicitGetter(
this,
reference: enclosingRef.getChild('@getter').getChild(name),
);
if (!isConst && !isFinal) {
this.setter = PropertyAccessorElementImpl_ImplicitSetter(
this,
reference: enclosingRef.getChild('@setter').getChild(name),
);
}
}
}
factory FieldElementImpl.forLinkedNodeFactory(
ElementImpl enclosing, Reference reference, AstNode linkedNode) {
var context = enclosing.enclosingUnit.linkedContext;
if (context.shouldBeConstFieldElement(linkedNode)) {
return ConstFieldElementImpl.forLinkedNode(
enclosing,
reference,
linkedNode,
);
}
return FieldElementImpl.forLinkedNode(enclosing, reference, linkedNode);
}
/// Initialize a newly created field element to have the given [name].
FieldElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
FieldElementImpl.forSerialized(
UnlinkedVariable unlinkedVariable, ElementImpl enclosingElement)
: super.forSerialized(unlinkedVariable, enclosingElement);
/// Initialize using the given serialized information.
factory FieldElementImpl.forSerializedFactory(
UnlinkedVariable unlinkedVariable, ElementImpl enclosingElement) {
if (unlinkedVariable.initializer?.bodyExpr != null &&
(unlinkedVariable.isConst ||
unlinkedVariable.isFinal &&
!unlinkedVariable.isStatic &&
enclosingElement is ClassElementImpl &&
enclosingElement._hasConstConstructor)) {
return new ConstFieldElementImpl.forSerialized(
unlinkedVariable, enclosingElement);
} else {
return new FieldElementImpl.forSerialized(
unlinkedVariable, enclosingElement);
}
}
@override
bool get isCovariant {
if (linkedNode != null) {
return linkedContext.isExplicitlyCovariant(linkedNode);
}
if (_unlinkedVariable != null) {
return _unlinkedVariable.isCovariant;
}
return hasModifier(Modifier.COVARIANT);
}
/// Set whether this field is explicitly marked as being covariant.
void set isCovariant(bool isCovariant) {
_assertNotResynthesized(_unlinkedVariable);
setModifier(Modifier.COVARIANT, isCovariant);
}
@override
bool get isEnumConstant =>
enclosingElement is ClassElement &&
(enclosingElement as ClassElement).isEnum &&
!isSynthetic;
@override
bool get isStatic {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isStatic(linkedNode);
}
if (_unlinkedVariable != null) {
return _unlinkedVariable.isStatic;
}
return hasModifier(Modifier.STATIC);
}
/// Set whether this field is static.
void set isStatic(bool isStatic) {
_assertNotResynthesized(_unlinkedVariable);
setModifier(Modifier.STATIC, isStatic);
}
@deprecated
@override
bool get isVirtual => true;
@override
ElementKind get kind => ElementKind.FIELD;
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitFieldElement(this);
@deprecated
@override
AstNode computeNode() {
if (isEnumConstant) {
return getNodeMatching((node) => node is EnumConstantDeclaration);
} else {
return getNodeMatching((node) => node is VariableDeclaration);
}
}
}
/// A [ParameterElementImpl] that has the additional information of the
/// [FieldElement] associated with the parameter.
class FieldFormalParameterElementImpl extends ParameterElementImpl
implements FieldFormalParameterElement {
/// The field associated with this field formal parameter.
FieldElement _field;
/// Initialize a newly created parameter element to have the given [name] and
/// [nameOffset].
FieldFormalParameterElementImpl(String name, int nameOffset)
: super(name, nameOffset);
FieldFormalParameterElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created parameter element to have the given [name].
FieldFormalParameterElementImpl.forNode(Identifier name)
: super.forNode(name);
/// Initialize using the given serialized information.
FieldFormalParameterElementImpl.forSerialized(
UnlinkedParam unlinkedParam, ElementImpl enclosingElement)
: super.forSerialized(unlinkedParam, enclosingElement);
@override
FieldElement get field {
if (_field == null) {
String fieldName;
if (linkedNode != null) {
fieldName = linkedContext.getFieldFormalParameterName(linkedNode);
}
if (unlinkedParam != null) {
fieldName = unlinkedParam.name;
}
if (fieldName != null) {
Element enclosingConstructor = enclosingElement;
if (enclosingConstructor is ConstructorElement) {
Element enclosingClass = enclosingConstructor.enclosingElement;
if (enclosingClass is ClassElement) {
FieldElement field = enclosingClass.getField(fieldName);
if (field != null && !field.isSynthetic) {
_field = field;
}
}
}
}
}
return _field;
}
void set field(FieldElement field) {
_assertNotResynthesized(unlinkedParam);
_field = field;
}
@override
bool get isInitializingFormal => true;
@override
DartType get type {
if (unlinkedParam != null &&
unlinkedParam.type == null &&
!unlinkedParam.isFunctionTyped &&
field != null) {
_type ??= field?.type ?? DynamicTypeImpl.instance;
}
return super.type;
}
@override
void set type(DartType type) {
_assertNotResynthesized(unlinkedParam);
_type = type;
}
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitFieldFormalParameterElement(this);
}
/// A concrete implementation of a [FunctionElement].
class FunctionElementImpl extends ExecutableElementImpl
implements FunctionElement, FunctionTypedElementImpl {
/// The offset to the beginning of the visible range for this element.
int _visibleRangeOffset = 0;
/// The length of the visible range for this element, or `-1` if this element
/// does not have a visible range.
int _visibleRangeLength = -1;
/// Initialize a newly created function element to have the given [name] and
/// [offset].
FunctionElementImpl(String name, int offset) : super(name, offset);
FunctionElementImpl.forLinkedNode(ElementImpl enclosing, Reference reference,
FunctionDeclaration linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created function element to have the given [name].
FunctionElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize a newly created function element to have no name and the given
/// [nameOffset]. This is used for function expressions, that have no name.
FunctionElementImpl.forOffset(int nameOffset) : super("", nameOffset);
/// Initialize using the given serialized information.
FunctionElementImpl.forSerialized(
UnlinkedExecutable serializedExecutable, ElementImpl enclosingElement)
: super.forSerialized(serializedExecutable, enclosingElement);
/// Synthesize an unnamed function element that takes [parameters] and returns
/// [returnType].
FunctionElementImpl.synthetic(
List<ParameterElement> parameters, DartType returnType)
: super("", -1) {
isSynthetic = true;
this.returnType = returnType;
this.parameters = parameters;
type = new FunctionTypeImpl(this);
}
@override
String get displayName {
if (linkedNode != null) {
return reference.name;
}
return super.displayName;
}
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext {
return (enclosingElement as ElementImpl).typeParameterContext;
}
@override
String get identifier {
String identifier = super.identifier;
Element enclosing = this.enclosingElement;
if (enclosing is ExecutableElement) {
identifier += "@$nameOffset";
}
return identifier;
}
@override
bool get isEntryPoint {
return isStatic && displayName == FunctionElement.MAIN_FUNCTION_NAME;
}
@override
bool get isStatic => enclosingElement is CompilationUnitElement;
@override
ElementKind get kind => ElementKind.FUNCTION;
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
return super.name;
}
@override
SourceRange get visibleRange {
if (serializedExecutable != null) {
if (serializedExecutable.visibleLength == 0) {
return null;
}
return new SourceRange(serializedExecutable.visibleOffset,
serializedExecutable.visibleLength);
}
if (_visibleRangeLength < 0) {
return null;
}
return new SourceRange(_visibleRangeOffset, _visibleRangeLength);
}
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitFunctionElement(this);
@deprecated
@override
FunctionDeclaration computeNode() =>
getNodeMatching((node) => node is FunctionDeclaration);
/// Set the visible range for this element to the range starting at the given
/// [offset] with the given [length].
void setVisibleRange(int offset, int length) {
_assertNotResynthesized(serializedExecutable);
_visibleRangeOffset = offset;
_visibleRangeLength = length;
}
/// Set the parameters defined by this type alias to the given [parameters]
/// without becoming the parent of the parameters. This should only be used by
/// the [TypeResolverVisitor] when creating a synthetic type alias.
void shareParameters(List<ParameterElement> parameters) {
this._parameters = parameters;
}
/// Set the type parameters defined by this type alias to the given
/// [parameters] without becoming the parent of the parameters. This should
/// only be used by the [TypeResolverVisitor] when creating a synthetic type
/// alias.
void shareTypeParameters(List<TypeParameterElement> typeParameters) {
this._typeParameterElements = typeParameters;
}
/// Create and return [FunctionElement]s for the given [unlinkedFunctions].
static List<FunctionElement> resynthesizeList(
ExecutableElementImpl executableElement,
List<UnlinkedExecutable> unlinkedFunctions) {
int length = unlinkedFunctions.length;
if (length != 0) {
List<FunctionElement> elements = new List<FunctionElement>(length);
for (int i = 0; i < length; i++) {
elements[i] = new FunctionElementImpl.forSerialized(
unlinkedFunctions[i], executableElement);
}
return elements;
} else {
return const <FunctionElement>[];
}
}
}
/// Implementation of [FunctionElementImpl] for a function typed parameter.
class FunctionElementImpl_forFunctionTypedParameter
extends FunctionElementImpl {
@override
final CompilationUnitElementImpl enclosingUnit;
/// The enclosing function typed [ParameterElementImpl].
final ParameterElementImpl _parameter;
FunctionElementImpl_forFunctionTypedParameter(
this.enclosingUnit, this._parameter)
: super('', -1);
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext =>
_parameter.typeParameterContext;
@override
bool get isSynthetic => true;
}
/// Common internal interface shared by elements whose type is a function type.
///
/// Clients may not extend, implement or mix-in this class.
abstract class FunctionTypedElementImpl
implements ElementImpl, FunctionTypedElement {
void set returnType(DartType returnType);
}
/// The element used for a generic function type.
///
/// Clients may not extend, implement or mix-in this class.
class GenericFunctionTypeElementImpl extends ElementImpl
with TypeParameterizedElementMixin
implements GenericFunctionTypeElement, FunctionTypedElementImpl {
/// The unlinked representation of the generic function type in the summary.
EntityRef _entityRef;
/// The declared return type of the function.
DartType _returnType;
/// The elements representing the parameters of the function.
List<ParameterElement> _parameters;
/// The type defined by this element.
FunctionType _type;
GenericFunctionTypeElementImpl.forLinkedNode(
ElementImpl enclosingElement, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosingElement, reference, linkedNode);
/// Initialize a newly created function element to have no name and the given
/// [nameOffset]. This is used for function expressions, that have no name.
GenericFunctionTypeElementImpl.forOffset(int nameOffset)
: super("", nameOffset);
/// Initialize from serialized information.
GenericFunctionTypeElementImpl.forSerialized(
ElementImpl enclosingElement, this._entityRef)
: super.forSerialized(enclosingElement);
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext {
return _enclosingElement.typeParameterContext;
}
@override
String get identifier => '-';
@override
ElementKind get kind => ElementKind.GENERIC_FUNCTION_TYPE;
@override
List<ParameterElement> get parameters {
if (_parameters == null) {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
return _parameters = ParameterElementImpl.forLinkedNodeList(
this,
context,
reference.getChild('@parameter'),
context.getFormalParameters(linkedNode),
);
}
if (_entityRef != null) {
_parameters = ParameterElementImpl.resynthesizeList(
_entityRef.syntheticParams, this);
}
}
return _parameters ?? const <ParameterElement>[];
}
/// Set the parameters defined by this function type element to the given
/// [parameters].
void set parameters(List<ParameterElement> parameters) {
_assertNotResynthesized(_entityRef);
for (ParameterElement parameter in parameters) {
(parameter as ParameterElementImpl).enclosingElement = this;
}
this._parameters = parameters;
}
@override
DartType get returnType {
if (_returnType == null) {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
return _returnType = context.getReturnType(linkedNode);
}
if (_entityRef != null) {
_returnType = enclosingUnit.resynthesizerContext.resolveTypeRef(
this, _entityRef.syntheticReturnType,
defaultVoid: false, declaredType: true);
}
}
return _returnType;
}
/// Set the return type defined by this function type element to the given
/// [returnType].
void set returnType(DartType returnType) {
_assertNotResynthesized(_entityRef);
_returnType = _checkElementOfType(returnType);
}
@override
FunctionType get type {
_type ??= new FunctionTypeImpl(this);
return _type;
}
/// Set the function type defined by this function type element to the given
/// [type].
void set type(FunctionType type) {
_assertNotResynthesized(_entityRef);
_type = type;
}
@override
List<TypeParameterElement> get typeParameters {
if (linkedNode != null) {
if (linkedNode is FunctionTypeAlias) {
return const <TypeParameterElement>[];
}
}
return super.typeParameters;
}
/// Set the type parameters defined by this function type element to the given
/// [typeParameters].
void set typeParameters(List<TypeParameterElement> typeParameters) {
_assertNotResynthesized(_entityRef);
for (TypeParameterElement parameter in typeParameters) {
(parameter as TypeParameterElementImpl).enclosingElement = this;
}
this._typeParameterElements = typeParameters;
}
@override
List<UnlinkedTypeParam> get unlinkedTypeParams => _entityRef?.typeParameters;
@override
T accept<T>(ElementVisitor<T> visitor) {
return visitor.visitGenericFunctionTypeElement(this);
}
@override
void appendTo(StringBuffer buffer) {
DartType type = returnType;
if (type is TypeImpl) {
type.appendTo(buffer, new HashSet<TypeImpl>());
buffer.write(' Function');
} else {
buffer.write('Function');
}
List<TypeParameterElement> typeParams = typeParameters;
int typeParameterCount = typeParams.length;
if (typeParameterCount > 0) {
buffer.write('<');
for (int i = 0; i < typeParameterCount; i++) {
if (i > 0) {
buffer.write(', ');
}
(typeParams[i] as TypeParameterElementImpl).appendTo(buffer);
}
buffer.write('>');
}
List<ParameterElement> params = parameters;
buffer.write('(');
for (int i = 0; i < params.length; i++) {
if (i > 0) {
buffer.write(', ');
}
(params[i] as ParameterElementImpl).appendTo(buffer);
}
buffer.write(')');
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
_safelyVisitPossibleChild(returnType, visitor);
safelyVisitChildren(typeParameters, visitor);
safelyVisitChildren(parameters, visitor);
}
}
/// A function type alias of the form
/// `typedef` identifier typeParameters = genericFunctionType;
///
/// Clients may not extend, implement or mix-in this class.
class GenericTypeAliasElementImpl extends ElementImpl
with TypeParameterizedElementMixin, SimplyBoundableMixin
implements GenericTypeAliasElement {
/// The unlinked representation of the type in the summary.
final UnlinkedTypedef _unlinkedTypedef;
/// The element representing the generic function type.
GenericFunctionTypeElementImpl _function;
/// The type of function defined by this type alias.
FunctionType _type;
/// Initialize a newly created type alias element to have the given [name].
GenericTypeAliasElementImpl(String name, int offset)
: _unlinkedTypedef = null,
super(name, offset);
GenericTypeAliasElementImpl.forLinkedNode(
CompilationUnitElementImpl enclosingUnit,
Reference reference,
AstNode linkedNode)
: _unlinkedTypedef = null,
super.forLinkedNode(enclosingUnit, reference, linkedNode);
/// Initialize a newly created type alias element to have the given [name].
GenericTypeAliasElementImpl.forNode(Identifier name)
: _unlinkedTypedef = null,
super.forNode(name);
/// Initialize using the given serialized information.
GenericTypeAliasElementImpl.forSerialized(
this._unlinkedTypedef, CompilationUnitElementImpl enclosingUnit)
: super.forSerialized(enclosingUnit);
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (_unlinkedTypedef != null) {
return _unlinkedTypedef.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (_unlinkedTypedef != null) {
return _unlinkedTypedef.codeRange?.offset;
}
return super.codeOffset;
}
@override
String get displayName => name;
@override
String get documentationComment {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var comment = context.getDocumentationComment(linkedNode);
return getCommentNodeRawText(comment);
}
if (_unlinkedTypedef != null) {
return _unlinkedTypedef.documentationComment?.text;
}
return super.documentationComment;
}
@override
CompilationUnitElement get enclosingElement =>
super.enclosingElement as CompilationUnitElement;
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext => null;
@override
CompilationUnitElementImpl get enclosingUnit =>
_enclosingElement as CompilationUnitElementImpl;
@override
GenericFunctionTypeElementImpl get function {
if (_function != null) return _function;
if (linkedNode != null) {
if (linkedNode is GenericTypeAlias) {
var context = enclosingUnit.linkedContext;
var function = context.getGeneticTypeAliasFunction(linkedNode);
if (function != null) {
var reference = context.getGenericFunctionTypeReference(function);
_function = reference.element;
encloseElement(_function);
return _function;
} else {
return null;
}
} else {
return _function = GenericFunctionTypeElementImpl.forLinkedNode(
this,
reference.getChild('@function'),
linkedNode,
);
}
}
if (_unlinkedTypedef != null) {
if (_unlinkedTypedef.style == TypedefStyle.genericFunctionType) {
DartType type = enclosingUnit.resynthesizerContext.resolveTypeRef(
this, _unlinkedTypedef.returnType,
declaredType: true);
if (type is FunctionType) {
Element element = type.element;
if (element is GenericFunctionTypeElement) {
(element as GenericFunctionTypeElementImpl).enclosingElement = this;
_function = element;
}
}
} else {
_function = new GenericFunctionTypeElementImpl.forOffset(-1);
_function.enclosingElement = this;
_function.returnType = enclosingUnit.resynthesizerContext
.resolveTypeRef(_function, _unlinkedTypedef.returnType,
declaredType: true);
_function.parameters = ParameterElementImpl.resynthesizeList(
_unlinkedTypedef.parameters, _function);
}
}
return _function;
}
/// Set the function element representing the generic function type on the
/// right side of the equals to the given [function].
void set function(GenericFunctionTypeElementImpl function) {
_assertNotResynthesized(_unlinkedTypedef);
if (function != null) {
function.enclosingElement = this;
}
_function = function;
}
bool get hasSelfReference {
if (linkedNode != null) {
return linkedContext.getHasTypedefSelfReference(linkedNode);
}
return false;
}
@override
bool get isSimplyBounded {
if (linkedNode != null) {
return linkedContext.isSimplyBounded(linkedNode);
}
return super.isSimplyBounded;
}
@override
ElementKind get kind => ElementKind.FUNCTION_TYPE_ALIAS;
@override
List<ElementAnnotation> get metadata {
if (_unlinkedTypedef != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, _unlinkedTypedef.annotations);
}
return super.metadata;
}
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
if (_unlinkedTypedef != null) {
return _unlinkedTypedef.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0 && _unlinkedTypedef != null) {
return _unlinkedTypedef.nameOffset;
}
return offset;
}
@override
List<ParameterElement> get parameters =>
function?.parameters ?? const <ParameterElement>[];
@override
DartType get returnType {
if (function == null) {
// TODO(scheglov) The context is null in unit tests.
return context?.typeProvider?.dynamicType;
}
return function?.returnType;
}
@override
FunctionType get type {
_type ??= FunctionTypeImpl.synthetic(
returnType,
typeParameters,
parameters,
element: this,
typeArguments: typeParameters.map((e) {
return e.instantiate(
nullabilitySuffix: NullabilitySuffix.star,
);
}).toList(),
);
return _type;
}
void set type(FunctionType type) {
_assertNotResynthesized(_unlinkedTypedef);
_type = type;
}
/// Set the type parameters defined for this type to the given
/// [typeParameters].
void set typeParameters(List<TypeParameterElement> typeParameters) {
_assertNotResynthesized(_unlinkedTypedef);
for (TypeParameterElement typeParameter in typeParameters) {
(typeParameter as TypeParameterElementImpl).enclosingElement = this;
}
this._typeParameterElements = typeParameters;
}
@override
List<UnlinkedTypeParam> get unlinkedTypeParams =>
_unlinkedTypedef?.typeParameters;
@override
int get _notSimplyBoundedSlot => _unlinkedTypedef?.notSimplyBoundedSlot;
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitFunctionTypeAliasElement(this);
@override
void appendTo(StringBuffer buffer) {
buffer.write("typedef ");
buffer.write(displayName);
var typeParameters = this.typeParameters;
int typeParameterCount = typeParameters.length;
if (typeParameterCount > 0) {
buffer.write("<");
for (int i = 0; i < typeParameterCount; i++) {
if (i > 0) {
buffer.write(", ");
}
(typeParameters[i] as TypeParameterElementImpl).appendTo(buffer);
}
buffer.write(">");
}
buffer.write(" = ");
if (function != null) {
function.appendTo(buffer);
}
}
@deprecated
@override
GenericTypeAlias computeNode() =>
getNodeMatching((node) => node is GenericTypeAlias);
@override
ElementImpl getChild(String identifier) {
for (TypeParameterElement typeParameter in typeParameters) {
TypeParameterElementImpl typeParameterImpl = typeParameter;
if (typeParameterImpl.identifier == identifier) {
return typeParameterImpl;
}
}
return null;
}
@override
FunctionType instantiate(List<DartType> argumentTypes) {
return doInstantiate(this, argumentTypes);
}
@override
FunctionType instantiate2({
@required List<DartType> typeArguments,
@required NullabilitySuffix nullabilitySuffix,
}) {
return FunctionTypeImpl.synthetic(
returnType,
typeParameters,
parameters,
element: this,
typeArguments: typeArguments,
nullabilitySuffix: nullabilitySuffix,
);
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
safelyVisitChildren(typeParameters, visitor);
function?.accept(visitor);
}
static FunctionType doInstantiate(
FunctionTypeAliasElement element, List<DartType> argumentTypes) {
if (argumentTypes.length != element.typeParameters.length) {
throw new ArgumentError('Wrong number of type arguments supplied');
}
if (element.typeParameters.isEmpty) return element.function.type;
return typeAfterSubstitution(element, argumentTypes);
}
/// Return the type of the function defined by this typedef after substituting
/// the given [typeArguments] for the type parameters defined for this typedef
/// (but not the type parameters defined by the function). If the number of
/// [typeArguments] does not match the number of type parameters, then
/// `dynamic` will be used in place of each of the type arguments.
static FunctionType typeAfterSubstitution(
FunctionTypeAliasElement element, List<DartType> typeArguments) {
GenericFunctionTypeElement function = element.function;
if (function == null) {
return null;
}
FunctionType functionType = function.type;
List<TypeParameterElement> parameterElements = element.typeParameters;
int parameterCount = parameterElements.length;
if (typeArguments == null ||
parameterElements.length != typeArguments.length) {
DartType dynamicType = element.context.typeProvider.dynamicType;
typeArguments = new List<DartType>.filled(parameterCount, dynamicType);
}
if (element is GenericTypeAliasElementImpl && element.linkedNode != null) {
return Substitution.fromPairs(parameterElements, typeArguments)
.substituteType(functionType);
}
List<DartType> parameterTypes =
TypeParameterTypeImpl.getTypes(parameterElements);
return functionType.substitute2(typeArguments, parameterTypes);
}
}
/// A concrete implementation of a [HideElementCombinator].
class HideElementCombinatorImpl implements HideElementCombinator {
/// The unlinked representation of the combinator in the summary.
final UnlinkedCombinator _unlinkedCombinator;
final LinkedUnitContext linkedContext;
final HideCombinator linkedNode;
/// The names that are not to be made visible in the importing library even if
/// they are defined in the imported library.
List<String> _hiddenNames;
HideElementCombinatorImpl()
: _unlinkedCombinator = null,
linkedContext = null,
linkedNode = null;
HideElementCombinatorImpl.forLinkedNode(this.linkedContext, this.linkedNode)
: _unlinkedCombinator = null;
/// Initialize using the given serialized information.
HideElementCombinatorImpl.forSerialized(this._unlinkedCombinator)
: linkedContext = null,
linkedNode = null;
@override
List<String> get hiddenNames {
if (_hiddenNames != null) return _hiddenNames;
if (linkedNode != null) {
return _hiddenNames = linkedNode.hiddenNames.map((i) => i.name).toList();
}
if (_unlinkedCombinator != null) {
return _hiddenNames = _unlinkedCombinator.hides.toList(growable: false);
}
return _hiddenNames ?? const <String>[];
}
void set hiddenNames(List<String> hiddenNames) {
_assertNotResynthesized(_unlinkedCombinator);
_hiddenNames = hiddenNames;
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
buffer.write("show ");
int count = hiddenNames.length;
for (int i = 0; i < count; i++) {
if (i > 0) {
buffer.write(", ");
}
buffer.write(hiddenNames[i]);
}
return buffer.toString();
}
}
/// A concrete implementation of an [ImportElement].
class ImportElementImpl extends UriReferencedElementImpl
implements ImportElement {
/// The unlinked representation of the import in the summary.
final UnlinkedImport _unlinkedImport;
/// The index of the dependency in the `imports` list.
final int _linkedDependency;
/// The offset of the prefix of this import in the file that contains the this
/// import directive, or `-1` if this import is synthetic.
int _prefixOffset = 0;
/// The library that is imported into this library by this import directive.
LibraryElement _importedLibrary;
/// The combinators that were specified as part of the import directive in the
/// order in which they were specified.
List<NamespaceCombinator> _combinators;
/// The prefix that was specified as part of the import directive, or `null
///` if there was no prefix specified.
PrefixElement _prefix;
/// The URI that was selected based on the declared variables.
String _selectedUri;
/// The cached value of [namespace].
Namespace _namespace;
/// Initialize a newly created import element at the given [offset].
/// The offset may be `-1` if the import is synthetic.
ImportElementImpl(int offset)
: _unlinkedImport = null,
_linkedDependency = null,
super(null, offset);
ImportElementImpl.forLinkedNode(
LibraryElementImpl enclosing, ImportDirective linkedNode)
: _unlinkedImport = null,
_linkedDependency = null,
super.forLinkedNode(enclosing, null, linkedNode);
/// Initialize using the given serialized information.
ImportElementImpl.forSerialized(this._unlinkedImport, this._linkedDependency,
LibraryElementImpl enclosingLibrary)
: super.forSerialized(enclosingLibrary);
@override
List<NamespaceCombinator> get combinators {
if (_combinators != null) return _combinators;
if (linkedNode != null) {
ImportDirective node = linkedNode;
return _combinators = ImportElementImpl._buildCombinators2(
enclosingUnit.linkedContext,
node.combinators,
);
}
if (_unlinkedImport != null) {
return _combinators = _buildCombinators(_unlinkedImport.combinators);
}
return _combinators ?? const <NamespaceCombinator>[];
}
void set combinators(List<NamespaceCombinator> combinators) {
_assertNotResynthesized(_unlinkedImport);
_combinators = combinators;
}
/// Set whether this import is for a deferred library.
void set deferred(bool isDeferred) {
_assertNotResynthesized(_unlinkedImport);
setModifier(Modifier.DEFERRED, isDeferred);
}
@override
CompilationUnitElementImpl get enclosingUnit {
LibraryElementImpl enclosingLibrary = enclosingElement;
return enclosingLibrary._definingCompilationUnit;
}
@override
String get identifier => "${importedLibrary.identifier}@$nameOffset";
@override
LibraryElement get importedLibrary {
if (_importedLibrary != null) return _importedLibrary;
if (linkedNode != null) {
return _importedLibrary = linkedContext.directiveLibrary(linkedNode);
}
if (_linkedDependency != null) {
if (_importedLibrary == null) {
LibraryElementImpl library = enclosingElement as LibraryElementImpl;
if (_linkedDependency == 0) {
_importedLibrary = library;
} else {
_importedLibrary = library.resynthesizerContext
.buildImportedLibrary(_linkedDependency);
}
}
}
return _importedLibrary;
}
void set importedLibrary(LibraryElement importedLibrary) {
_assertNotResynthesized(_unlinkedImport);
_importedLibrary = importedLibrary;
}
@override
bool get isDeferred {
if (linkedNode != null) {
ImportDirective linkedNode = this.linkedNode;
return linkedNode.deferredKeyword != null;
}
if (_unlinkedImport != null) {
return _unlinkedImport.isDeferred;
}
return hasModifier(Modifier.DEFERRED);
}
@override
bool get isSynthetic {
if (_unlinkedImport != null) {
return _unlinkedImport.isImplicit;
}
return super.isSynthetic;
}
@override
ElementKind get kind => ElementKind.IMPORT;
@override
List<ElementAnnotation> get metadata {
if (_metadata == null) {
if (_unlinkedImport != null) {
return _metadata = _buildAnnotations(
library.definingCompilationUnit, _unlinkedImport.annotations);
}
}
return super.metadata;
}
void set metadata(List<ElementAnnotation> metadata) {
_assertNotResynthesized(_unlinkedImport);
super.metadata = metadata;
}
@override
int get nameOffset {
if (linkedNode != null) {
return linkedContext.getDirectiveOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0 && _unlinkedImport != null) {
if (_unlinkedImport.isImplicit) {
return -1;
}
return _unlinkedImport.offset;
}
return offset;
}
@override
Namespace get namespace {
return _namespace ??=
new NamespaceBuilder().createImportNamespaceForDirective(this);
}
PrefixElement get prefix {
if (_prefix != null) return _prefix;
if (linkedNode != null) {
ImportDirective linkedNode = this.linkedNode;
var prefix = linkedNode.prefix;
if (prefix != null) {
var name = prefix.name;
var library = enclosingElement as LibraryElementImpl;
_prefix = new PrefixElementImpl.forLinkedNode(
library,
library.reference.getChild('@prefix').getChild(name),
prefix,
);
}
}
if (_unlinkedImport != null && _unlinkedImport.prefixReference != 0) {
LibraryElementImpl library = enclosingElement as LibraryElementImpl;
_prefix = new PrefixElementImpl.forSerialized(_unlinkedImport, library);
}
return _prefix;
}
void set prefix(PrefixElement prefix) {
_assertNotResynthesized(_unlinkedImport);
_prefix = prefix;
}
@override
int get prefixOffset {
if (linkedNode != null) {
ImportDirective node = linkedNode;
return node.prefix?.offset ?? -1;
}
if (_unlinkedImport != null) {
return _unlinkedImport.prefixOffset;
}
return _prefixOffset;
}
void set prefixOffset(int prefixOffset) {
_assertNotResynthesized(_unlinkedImport);
_prefixOffset = prefixOffset;
}
@override
String get uri {
if (linkedNode != null) {
ImportDirective node = linkedNode;
return node.uri.stringValue;
}
if (_unlinkedImport != null) {
if (_unlinkedImport.isImplicit) {
return null;
}
return _selectedUri ??=
_selectUri(_unlinkedImport.uri, _unlinkedImport.configurations);
}
return super.uri;
}
@override
void set uri(String uri) {
_assertNotResynthesized(_unlinkedImport);
super.uri = uri;
}
@override
int get uriEnd {
if (_unlinkedImport != null) {
if (_unlinkedImport.isImplicit) {
return -1;
}
return _unlinkedImport.uriEnd;
}
return super.uriEnd;
}
@override
void set uriEnd(int uriEnd) {
_assertNotResynthesized(_unlinkedImport);
super.uriEnd = uriEnd;
}
@override
int get uriOffset {
if (_unlinkedImport != null) {
if (_unlinkedImport.isImplicit) {
return -1;
}
return _unlinkedImport.uriOffset;
}
return super.uriOffset;
}
@override
void set uriOffset(int uriOffset) {
_assertNotResynthesized(_unlinkedImport);
super.uriOffset = uriOffset;
}
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitImportElement(this);
@override
void appendTo(StringBuffer buffer) {
buffer.write("import ");
LibraryElementImpl.getImpl(importedLibrary).appendTo(buffer);
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
prefix?.accept(visitor);
}
static List<NamespaceCombinator> _buildCombinators(
List<UnlinkedCombinator> unlinkedCombinators) {
int length = unlinkedCombinators.length;
if (length != 0) {
List<NamespaceCombinator> combinators =
new List<NamespaceCombinator>(length);
for (int i = 0; i < length; i++) {
UnlinkedCombinator unlinkedCombinator = unlinkedCombinators[i];
combinators[i] = unlinkedCombinator.shows.isNotEmpty
? new ShowElementCombinatorImpl.forSerialized(unlinkedCombinator)
: new HideElementCombinatorImpl.forSerialized(unlinkedCombinator);
}
return combinators;
} else {
return const <NamespaceCombinator>[];
}
}
static List<NamespaceCombinator> _buildCombinators2(
LinkedUnitContext context, List<Combinator> combinators) {
return combinators.map((node) {
if (node is HideCombinator) {
return HideElementCombinatorImpl.forLinkedNode(context, node);
}
if (node is ShowCombinator) {
return ShowElementCombinatorImpl.forLinkedNode(context, node);
}
throw UnimplementedError('${node.runtimeType}');
}).toList();
}
}
/// A concrete implementation of a [LabelElement].
class LabelElementImpl extends ElementImpl implements LabelElement {
/// A flag indicating whether this label is associated with a `switch`
/// statement.
// TODO(brianwilkerson) Make this a modifier.
final bool _onSwitchStatement;
/// A flag indicating whether this label is associated with a `switch` member
/// (`case` or `default`).
// TODO(brianwilkerson) Make this a modifier.
final bool _onSwitchMember;
/// Initialize a newly created label element to have the given [name].
/// [onSwitchStatement] should be `true` if this label is associated with a
/// `switch` statement and [onSwitchMember] should be `true` if this label is
/// associated with a `switch` member.
LabelElementImpl(String name, int nameOffset, this._onSwitchStatement,
this._onSwitchMember)
: super(name, nameOffset);
/// Initialize a newly created label element to have the given [name].
/// [_onSwitchStatement] should be `true` if this label is associated with a
/// `switch` statement and [_onSwitchMember] should be `true` if this label is
/// associated with a `switch` member.
LabelElementImpl.forNode(
Identifier name, this._onSwitchStatement, this._onSwitchMember)
: super.forNode(name);
@override
String get displayName => name;
@override
ExecutableElement get enclosingElement =>
super.enclosingElement as ExecutableElement;
/// Return `true` if this label is associated with a `switch` member (`case
/// ` or`default`).
bool get isOnSwitchMember => _onSwitchMember;
/// Return `true` if this label is associated with a `switch` statement.
bool get isOnSwitchStatement => _onSwitchStatement;
@override
ElementKind get kind => ElementKind.LABEL;
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitLabelElement(this);
}
/// A concrete implementation of a [LibraryElement].
class LibraryElementImpl extends ElementImpl implements LibraryElement {
/// The analysis context in which this library is defined.
final AnalysisContext context;
@override
final AnalysisSession session;
final LibraryResynthesizerContext resynthesizerContext;
final UnlinkedUnit unlinkedDefiningUnit;
/// The context of the defining unit.
final LinkedUnitContext linkedContext;
@override
final bool isNonNullableByDefault;
/// The compilation unit that defines this library.
CompilationUnitElement _definingCompilationUnit;
/// The entry point for this library, or `null` if this library does not have
/// an entry point.
FunctionElement _entryPoint;
/// A list containing specifications of all of the imports defined in this
/// library.
List<ImportElement> _imports;
/// A list containing specifications of all of the exports defined in this
/// library.
List<ExportElement> _exports;
/// A list containing the strongly connected component in the import/export
/// graph in which the current library resides. Computed on demand, null
/// if not present. If _libraryCycle is set, then the _libraryCycle field
/// for all libraries reachable from this library in the import/export graph
/// is also set.
List<LibraryElement> _libraryCycle;
/// A list containing all of the compilation units that are included in this
/// library using a `part` directive.
List<CompilationUnitElement> _parts = const <CompilationUnitElement>[];
/// The element representing the synthetic function `loadLibrary` that is
/// defined for this library, or `null` if the element has not yet been
/// created.
FunctionElement _loadLibraryFunction;
@override
final int nameLength;
/// The export [Namespace] of this library, `null` if it has not been
/// computed yet.
Namespace _exportNamespace;
/// The public [Namespace] of this library, `null` if it has not been
/// computed yet.
Namespace _publicNamespace;
/// A bit-encoded form of the capabilities associated with this library.
int _resolutionCapabilities = 0;
/// The cached list of prefixes.
List<PrefixElement> _prefixes;
/// Initialize a newly created library element in the given [context] to have
/// the given [name] and [offset].
LibraryElementImpl(this.context, this.session, String name, int offset,
this.nameLength, this.isNonNullableByDefault)
: resynthesizerContext = null,
unlinkedDefiningUnit = null,
linkedContext = null,
super(name, offset);
LibraryElementImpl.forLinkedNode(
this.context,
this.session,
String name,
int offset,
this.nameLength,
this.linkedContext,
Reference reference,
CompilationUnit linkedNode)
: resynthesizerContext = null,
unlinkedDefiningUnit = null,
isNonNullableByDefault = linkedContext.isNNBD,
super.forLinkedNode(null, reference, linkedNode) {
_name = name;
_nameOffset = offset;
setResolutionCapability(
LibraryResolutionCapability.resolvedTypeNames, true);
setResolutionCapability(
LibraryResolutionCapability.constantExpressions, true);
}
/// Initialize a newly created library element in the given [context] to have
/// the given [name].
LibraryElementImpl.forNode(this.context, this.session, LibraryIdentifier name,
this.isNonNullableByDefault)
: nameLength = name != null ? name.length : 0,
resynthesizerContext = null,
unlinkedDefiningUnit = null,
linkedContext = null,
super.forNode(name);
/// Initialize using the given serialized information.
LibraryElementImpl.forSerialized(
this.context,
this.session,
String name,
int offset,
this.nameLength,
this.resynthesizerContext,
this.unlinkedDefiningUnit)
: linkedContext = null,
isNonNullableByDefault = unlinkedDefiningUnit.isNNBD,
super.forSerialized(null) {
_name = name;
_nameOffset = offset;
setResolutionCapability(
LibraryResolutionCapability.resolvedTypeNames, true);
setResolutionCapability(
LibraryResolutionCapability.constantExpressions, true);
}
@override
int get codeLength {
CompilationUnitElement unit = _definingCompilationUnit;
if (unit is CompilationUnitElementImpl) {
return unit.codeLength;
}
return null;
}
@override
int get codeOffset {
CompilationUnitElement unit = _definingCompilationUnit;
if (unit is CompilationUnitElementImpl) {
return unit.codeOffset;
}
return null;
}
@override
CompilationUnitElement get definingCompilationUnit =>
_definingCompilationUnit;
/// Set the compilation unit that defines this library to the given
/// compilation[unit].
void set definingCompilationUnit(CompilationUnitElement unit) {
assert((unit as CompilationUnitElementImpl).librarySource == unit.source);
(unit as CompilationUnitElementImpl).enclosingElement = this;
this._definingCompilationUnit = unit;
}
@override
String get documentationComment {
if (linkedNode != null) {
var comment = linkedContext.getLibraryDocumentationComment(linkedNode);
return getCommentNodeRawText(comment);
}
if (unlinkedDefiningUnit != null) {
return unlinkedDefiningUnit.libraryDocumentationComment?.text;
}
return super.documentationComment;
}
FunctionElement get entryPoint {
if (_entryPoint != null) return _entryPoint;
if (linkedContext != null) {
var namespace = library.exportNamespace;
var entryPoint = namespace.get(FunctionElement.MAIN_FUNCTION_NAME);
if (entryPoint is FunctionElement) {
return _entryPoint = entryPoint;
}
return null;
}
if (resynthesizerContext != null) {
return _entryPoint = resynthesizerContext.findEntryPoint();
}
return _entryPoint;
}
void set entryPoint(FunctionElement entryPoint) {
_entryPoint = entryPoint;
}
@override
List<LibraryElement> get exportedLibraries {
HashSet<LibraryElement> libraries = new HashSet<LibraryElement>();
for (ExportElement element in exports) {
LibraryElement library = element.exportedLibrary;
if (library != null) {
libraries.add(library);
}
}
return libraries.toList(growable: false);
}
@override
Namespace get exportNamespace {
if (_exportNamespace != null) return _exportNamespace;
if (linkedNode != null) {
var elements = linkedContext.bundleContext.elementFactory;
return _exportNamespace = elements.buildExportNamespace(source.uri);
}
if (resynthesizerContext != null) {
_exportNamespace ??= resynthesizerContext.buildExportNamespace();
}
return _exportNamespace;
}
void set exportNamespace(Namespace exportNamespace) {
_exportNamespace = exportNamespace;
}
@override
List<ExportElement> get exports {
if (_exports != null) return _exports;
if (linkedNode != null) {
var unit = linkedContext.unit_withDirectives;
return _exports = unit.directives
.whereType<ExportDirective>()
.map((node) => ExportElementImpl.forLinkedNode(this, node))
.toList();
}
if (unlinkedDefiningUnit != null) {
List<UnlinkedExportNonPublic> unlinkedNonPublicExports =
unlinkedDefiningUnit.exports;
List<UnlinkedExportPublic> unlinkedPublicExports =
unlinkedDefiningUnit.publicNamespace.exports;
assert(
unlinkedDefiningUnit.exports.length == unlinkedPublicExports.length);
int length = unlinkedNonPublicExports.length;
if (length != 0) {
List<ExportElement> exports = new List<ExportElement>();
for (int i = 0; i < length; i++) {
UnlinkedExportPublic serializedExportPublic =
unlinkedPublicExports[i];
UnlinkedExportNonPublic serializedExportNonPublic =
unlinkedNonPublicExports[i];
ExportElementImpl exportElement = new ExportElementImpl.forSerialized(
serializedExportPublic, serializedExportNonPublic, library);
exports.add(exportElement);
}
_exports = exports;
} else {
_exports = const <ExportElement>[];
}
}
return _exports ??= const <ExportElement>[];
}
/// Set the specifications of all of the exports defined in this library to
/// the given list of [exports].
void set exports(List<ExportElement> exports) {
_assertNotResynthesized(unlinkedDefiningUnit);
for (ExportElement exportElement in exports) {
(exportElement as ExportElementImpl).enclosingElement = this;
}
this._exports = exports;
}
@override
bool get hasExtUri {
if (linkedNode != null) {
var unit = linkedContext.unit_withDirectives;
for (var import in unit.directives) {
if (import is ImportDirective) {
var uriStr = linkedContext.getSelectedUri(import);
if (DartUriResolver.isDartExtUri(uriStr)) {
return true;
}
}
}
return false;
}
if (unlinkedDefiningUnit != null) {
List<UnlinkedImport> unlinkedImports = unlinkedDefiningUnit.imports;
for (UnlinkedImport import in unlinkedImports) {
if (DartUriResolver.isDartExtUri(import.uri)) {
return true;
}
}
return false;
}
return hasModifier(Modifier.HAS_EXT_URI);
}
/// Set whether this library has an import of a "dart-ext" URI.
void set hasExtUri(bool hasExtUri) {
setModifier(Modifier.HAS_EXT_URI, hasExtUri);
}
@override
bool get hasLoadLibraryFunction {
if (_definingCompilationUnit.hasLoadLibraryFunction) {
return true;
}
for (int i = 0; i < _parts.length; i++) {
if (_parts[i].hasLoadLibraryFunction) {
return true;
}
}
return false;
}
@override
String get identifier => '${_definingCompilationUnit.source.uri}';
@override
List<LibraryElement> get importedLibraries {
HashSet<LibraryElement> libraries = new HashSet<LibraryElement>();
for (ImportElement element in imports) {
LibraryElement library = element.importedLibrary;
if (library != null) {
libraries.add(library);
}
}
return libraries.toList(growable: false);
}
@override
List<ImportElement> get imports {
if (_imports != null) return _imports;
if (linkedNode != null) {
var unit = linkedContext.unit_withDirectives;
_imports = unit.directives
.whereType<ImportDirective>()
.map((node) => ImportElementImpl.forLinkedNode(this, node))
.toList();
var hasCore = _imports.any((import) {
return import.importedLibrary?.isDartCore ?? false;
});
if (!hasCore) {
var elements = linkedContext.bundleContext.elementFactory;
_imports.add(ImportElementImpl(-1)
..importedLibrary = elements.libraryOfUri('dart:core')
..isSynthetic = true);
}
return _imports;
}
if (unlinkedDefiningUnit != null) {
_imports = buildImportsFromSummary(this, unlinkedDefiningUnit.imports,
resynthesizerContext.linkedLibrary.importDependencies);
}
return _imports ??= const <ImportElement>[];
}
/// Set the specifications of all of the imports defined in this library to
/// the given list of [imports].
void set imports(List<ImportElement> imports) {
_assertNotResynthesized(unlinkedDefiningUnit);
for (ImportElement importElement in imports) {
(importElement as ImportElementImpl).enclosingElement = this;
PrefixElementImpl prefix = importElement.prefix as PrefixElementImpl;
if (prefix != null) {
prefix.enclosingElement = this;
}
}
this._imports = imports;
this._prefixes = null;
}
@override
bool get isBrowserApplication =>
entryPoint != null && isOrImportsBrowserLibrary;
@override
bool get isDartAsync => name == "dart.async";
@override
bool get isDartCore => name == "dart.core";
@override
bool get isInSdk {
Uri uri = definingCompilationUnit.source?.uri;
if (uri != null) {
return DartUriResolver.isDartUri(uri);
}
return false;
}
/// Return `true` if the receiver directly or indirectly imports the
/// 'dart:html' libraries.
bool get isOrImportsBrowserLibrary {
List<LibraryElement> visited = new List<LibraryElement>();
Source htmlLibSource = context.sourceFactory.forUri(DartSdk.DART_HTML);
visited.add(this);
for (int index = 0; index < visited.length; index++) {
LibraryElement library = visited[index];
Source source = library.definingCompilationUnit.source;
if (source == htmlLibSource) {
return true;
}
for (LibraryElement importedLibrary in library.importedLibraries) {
if (!visited.contains(importedLibrary)) {
visited.add(importedLibrary);
}
}
for (LibraryElement exportedLibrary in library.exportedLibraries) {
if (!visited.contains(exportedLibrary)) {
visited.add(exportedLibrary);
}
}
}
return false;
}
@override
bool get isResynthesized {
return resynthesizerContext != null;
}
@override
bool get isSynthetic {
if (linkedNode != null) {
return linkedContext.isSynthetic;
}
return super.isSynthetic;
}
@override
ElementKind get kind => ElementKind.LIBRARY;
@override
LibraryElement get library => this;
@override
List<LibraryElement> get libraryCycle {
if (_libraryCycle != null) {
return _libraryCycle;
}
// Global counter for this run of the algorithm
int counter = 0;
// The discovery times of each library
Map<LibraryElementImpl, int> indices = {};
// The set of scc candidates
Set<LibraryElementImpl> active = new Set();
// The stack of discovered elements
List<LibraryElementImpl> stack = [];
// For a given library that has not yet been processed by this run of the
// algorithm, compute the strongly connected components.
int scc(LibraryElementImpl library) {
int index = counter++;
int root = index;
indices[library] = index;
active.add(library);
stack.add(library);
LibraryElementImpl getActualLibrary(LibraryElement lib) {
// TODO(paulberry): this means that computing a library cycle will be
// expensive for libraries resynthesized from summaries, since it will
// require fully resynthesizing all the libraries in the cycle as well
// as any libraries they import or export. Try to find a better way.
if (lib is LibraryElementHandle) {
return lib.actualElement;
} else {
return lib;
}
}
void recurse(LibraryElementImpl child) {
if (!indices.containsKey(child)) {
// We haven't visited this child yet, so recurse on the child,
// returning the lowest numbered node reachable from the child. If
// the child can reach a root which is lower numbered than anything
// we've reached so far, update the root.
root = min(root, scc(child));
} else if (active.contains(child)) {
// The child has been visited, but has not yet been placed into a
// component. If the child is higher than anything we've seen so far
// update the root appropriately.
root = min(root, indices[child]);
}
}
// Recurse on all of the children in the import/export graph, filtering
// out those for which library cycles have already been computed.
library.exportedLibraries
.map(getActualLibrary)
.where((l) => l._libraryCycle == null)
.forEach(recurse);
library.importedLibraries
.map(getActualLibrary)
.where((l) => l._libraryCycle == null)
.forEach(recurse);
if (root == index) {
// This is the root of a strongly connected component.
// Pop the elements, and share the component across all
// of the elements.
List<LibraryElement> component = <LibraryElement>[];
LibraryElementImpl cur;
do {
cur = stack.removeLast();
active.remove(cur);
component.add(cur);
cur._libraryCycle = component;
} while (cur != library);
}
return root;
}
scc(library);
return _libraryCycle;
}
@override
FunctionElement get loadLibraryFunction {
assert(_loadLibraryFunction != null);
return _loadLibraryFunction;
}
@override
List<ElementAnnotation> get metadata {
if (_metadata != null) return _metadata;
if (linkedNode != null) {
var metadata = linkedContext.getLibraryMetadata(linkedNode);
return _metadata = _buildAnnotations2(definingCompilationUnit, metadata);
}
if (unlinkedDefiningUnit != null) {
return _metadata = _buildAnnotations(
_definingCompilationUnit as CompilationUnitElementImpl,
unlinkedDefiningUnit.libraryAnnotations);
}
return super.metadata;
}
@override
List<CompilationUnitElement> get parts => _parts;
/// Set the compilation units that are included in this library using a `part`
/// directive to the given list of [parts].
void set parts(List<CompilationUnitElement> parts) {
for (CompilationUnitElement compilationUnit in parts) {
assert((compilationUnit as CompilationUnitElementImpl).librarySource ==
source);
(compilationUnit as CompilationUnitElementImpl).enclosingElement = this;
}
this._parts = parts;
}
@override
List<PrefixElement> get prefixes =>
_prefixes ??= buildPrefixesFromImports(imports);
@override
Namespace get publicNamespace {
if (_publicNamespace != null) return _publicNamespace;
if (linkedNode != null) {
return _publicNamespace =
NamespaceBuilder().createPublicNamespaceForLibrary(this);
}
if (resynthesizerContext != null) {
return _publicNamespace = resynthesizerContext.buildPublicNamespace();
}
return _publicNamespace;
}
void set publicNamespace(Namespace publicNamespace) {
_publicNamespace = publicNamespace;
}
@override
Source get source {
if (_definingCompilationUnit == null) {
return null;
}
return _definingCompilationUnit.source;
}
@override
Iterable<Element> get topLevelElements sync* {
for (var unit in units) {
yield* unit.accessors;
yield* unit.enums;
yield* unit.functionTypeAliases;
yield* unit.functions;
yield* unit.mixins;
yield* unit.topLevelVariables;
yield* unit.types;
}
}
@override
List<CompilationUnitElement> get units {
List<CompilationUnitElement> units = new List<CompilationUnitElement>();
units.add(_definingCompilationUnit);
units.addAll(_parts);
return units;
}
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitLibraryElement(this);
/// Create the [FunctionElement] to be returned by [loadLibraryFunction],
/// using types provided by [typeProvider].
void createLoadLibraryFunction(TypeProvider typeProvider) {
_loadLibraryFunction =
createLoadLibraryFunctionForLibrary(typeProvider, this);
}
@override
ElementImpl getChild(String identifier) {
CompilationUnitElementImpl unitImpl = _definingCompilationUnit;
if (unitImpl.identifier == identifier) {
return unitImpl;
}
for (CompilationUnitElement part in _parts) {
CompilationUnitElementImpl partImpl = part;
if (partImpl.identifier == identifier) {
return partImpl;
}
}
for (ImportElement importElement in imports) {
ImportElementImpl importElementImpl = importElement;
if (importElementImpl.identifier == identifier) {
return importElementImpl;
}
}
for (ExportElement exportElement in exports) {
ExportElementImpl exportElementImpl = exportElement;
if (exportElementImpl.identifier == identifier) {
return exportElementImpl;
}
}
return null;
}
ClassElement getEnum(String name) {
ClassElement element = _definingCompilationUnit.getEnum(name);
if (element != null) {
return element;
}
for (CompilationUnitElement part in _parts) {
element = part.getEnum(name);
if (element != null) {
return element;
}
}
return null;
}
@override
List<ImportElement> getImportsWithPrefix(PrefixElement prefixElement) {
return getImportsWithPrefixFromImports(prefixElement, imports);
}
@override
ClassElement getType(String className) {
return getTypeFromParts(className, _definingCompilationUnit, _parts);
}
/// Set whether the library has the given [capability] to
/// correspond to the given [value].
void setResolutionCapability(
LibraryResolutionCapability capability, bool value) {
_resolutionCapabilities =
BooleanArray.set(_resolutionCapabilities, capability.index, value);
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
_definingCompilationUnit?.accept(visitor);
safelyVisitChildren(exports, visitor);
safelyVisitChildren(imports, visitor);
safelyVisitChildren(_parts, visitor);
}
static List<ImportElement> buildImportsFromSummary(LibraryElement library,
List<UnlinkedImport> unlinkedImports, List<int> importDependencies) {
int length = unlinkedImports.length;
if (length != 0) {
List<ImportElement> imports = new List<ImportElement>();
for (int i = 0; i < length; i++) {
int dependency = importDependencies[i];
ImportElementImpl importElement = new ImportElementImpl.forSerialized(
unlinkedImports[i], dependency, library);
imports.add(importElement);
}
return imports;
} else {
return const <ImportElement>[];
}
}
static List<PrefixElement> buildPrefixesFromImports(
List<ImportElement> imports) {
HashSet<PrefixElement> prefixes = new HashSet<PrefixElement>();
for (ImportElement element in imports) {
PrefixElement prefix = element.prefix;
if (prefix != null) {
prefixes.add(prefix);
}
}
return prefixes.toList(growable: false);
}
static FunctionElementImpl createLoadLibraryFunctionForLibrary(
TypeProvider typeProvider, LibraryElement library) {
FunctionElementImpl function =
new FunctionElementImpl(FunctionElement.LOAD_LIBRARY_NAME, -1);
function.isSynthetic = true;
function.enclosingElement = library;
function.returnType = typeProvider.futureDynamicType;
function.type = new FunctionTypeImpl(function);
return function;
}
/// Return the [LibraryElementImpl] of the given [element].
static LibraryElementImpl getImpl(LibraryElement element) {
if (element is LibraryElementHandle) {
return getImpl(element.actualElement);
}
return element as LibraryElementImpl;
}
static List<ImportElement> getImportsWithPrefixFromImports(
PrefixElement prefixElement, List<ImportElement> imports) {
int count = imports.length;
List<ImportElement> importList = new List<ImportElement>();
for (int i = 0; i < count; i++) {
if (identical(imports[i].prefix, prefixElement)) {
importList.add(imports[i]);
}
}
return importList;
}
static ClassElement getTypeFromParts(
String className,
CompilationUnitElement definingCompilationUnit,
List<CompilationUnitElement> parts) {
ClassElement type = definingCompilationUnit.getType(className);
if (type != null) {
return type;
}
for (CompilationUnitElement part in parts) {
type = part.getType(className);
if (type != null) {
return type;
}
}
return null;
}
/// Return `true` if the [library] has the given [capability].
static bool hasResolutionCapability(
LibraryElement library, LibraryResolutionCapability capability) {
return library is LibraryElementImpl &&
BooleanArray.get(library._resolutionCapabilities, capability.index);
}
}
/// Enum of possible resolution capabilities that a [LibraryElementImpl] has.
enum LibraryResolutionCapability {
/// All elements have their types resolved.
resolvedTypeNames,
/// All (potentially) constants expressions are set into corresponding
/// elements.
constantExpressions,
}
/// The context in which the library is resynthesized.
abstract class LibraryResynthesizerContext {
/// Return the [LinkedLibrary] that corresponds to the library being
/// resynthesized.
LinkedLibrary get linkedLibrary;
/// Return the exported [LibraryElement] for with the given [relativeUri].
LibraryElement buildExportedLibrary(String relativeUri);
/// Return the export namespace of the library.
Namespace buildExportNamespace();
/// Return the imported [LibraryElement] for the given dependency in the
/// linked library.
LibraryElement buildImportedLibrary(int dependency);
/// Return the public namespace of the library.
Namespace buildPublicNamespace();
/// Find the entry point of the library.
FunctionElement findEntryPoint();
/// Ensure that getters and setters in different units use the same
/// top-level variables.
void patchTopLevelAccessors();
}
/// A concrete implementation of a [LocalVariableElement].
class LocalVariableElementImpl extends NonParameterVariableElementImpl
implements LocalVariableElement {
/// The offset to the beginning of the visible range for this element.
int _visibleRangeOffset = 0;
/// The length of the visible range for this element, or `-1` if this element
/// does not have a visible range.
int _visibleRangeLength = -1;
/// Initialize a newly created method element to have the given [name] and
/// [offset].
LocalVariableElementImpl(String name, int offset) : super(name, offset);
/// Initialize a newly created local variable element to have the given
/// [name].
LocalVariableElementImpl.forNode(Identifier name) : super.forNode(name);
@override
String get identifier {
return '$name$nameOffset';
}
@override
bool get isLate {
if (_unlinkedVariable != null) {
return _unlinkedVariable.isLate;
}
return hasModifier(Modifier.LATE);
}
/// Set whether this variable is late.
void set isLate(bool isLate) {
setModifier(Modifier.LATE, isLate);
}
@override
bool get isPotentiallyMutatedInClosure => true;
@override
bool get isPotentiallyMutatedInScope => true;
@override
ElementKind get kind => ElementKind.LOCAL_VARIABLE;
@override
SourceRange get visibleRange {
if (_visibleRangeLength < 0) {
return null;
}
return new SourceRange(_visibleRangeOffset, _visibleRangeLength);
}
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitLocalVariableElement(this);
@override
void appendTo(StringBuffer buffer) {
buffer.write(type);
buffer.write(" ");
buffer.write(displayName);
}
@deprecated
@override
Declaration computeNode() => getNodeMatching(
(node) => node is DeclaredIdentifier || node is VariableDeclaration);
/// Set the visible range for this element to the range starting at the given
/// [offset] with the given [length].
void setVisibleRange(int offset, int length) {
_visibleRangeOffset = offset;
_visibleRangeLength = length;
}
}
/// A concrete implementation of a [MethodElement].
class MethodElementImpl extends ExecutableElementImpl implements MethodElement {
/// Initialize a newly created method element to have the given [name] at the
/// given [offset].
MethodElementImpl(String name, int offset) : super(name, offset);
MethodElementImpl.forLinkedNode(TypeParameterizedElementMixin enclosingClass,
Reference reference, MethodDeclaration linkedNode)
: super.forLinkedNode(enclosingClass, reference, linkedNode);
/// Initialize a newly created method element to have the given [name].
MethodElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
MethodElementImpl.forSerialized(UnlinkedExecutable serializedExecutable,
TypeParameterizedElementMixin enclosingClass)
: super.forSerialized(serializedExecutable, enclosingClass);
@override
String get displayName {
String displayName = super.displayName;
if ("unary-" == displayName) {
return "-";
}
return displayName;
}
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext =>
super.enclosingElement as TypeParameterizedElementMixin;
/// Set whether this class is abstract.
void set isAbstract(bool isAbstract) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.ABSTRACT, isAbstract);
}
@override
bool get isOperator {
String name = displayName;
if (name.isEmpty) {
return false;
}
int first = name.codeUnitAt(0);
return !((0x61 <= first && first <= 0x7A) ||
(0x41 <= first && first <= 0x5A) ||
first == 0x5F ||
first == 0x24);
}
@override
bool get isStatic {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isStatic(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.isStatic;
}
return hasModifier(Modifier.STATIC);
}
/// Set whether this method is static.
void set isStatic(bool isStatic) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.STATIC, isStatic);
}
@override
ElementKind get kind => ElementKind.METHOD;
@override
String get name {
String name = super.name;
if (name == '-' && parameters.isEmpty) {
return 'unary-';
}
return super.name;
}
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitMethodElement(this);
@deprecated
@override
MethodDeclaration computeNode() =>
getNodeMatching((node) => node is MethodDeclaration);
}
/// A [ClassElementImpl] representing a mixin declaration.
class MixinElementImpl extends ClassElementImpl {
// TODO(brianwilkerson) Consider creating an abstract superclass of
// ClassElementImpl that contains the portions of the API that this class
// needs, and make this class extend the new class.
/// A list containing all of the superclass constraints that are defined for
/// the mixin.
List<InterfaceType> _superclassConstraints;
/// Names of methods, getters, setters, and operators that this mixin
/// declaration super-invokes. For setters this includes the trailing "=".
/// The list will be empty if this class is not a mixin declaration.
List<String> _superInvokedNames;
/// Initialize a newly created class element to have the given [name] at the
/// given [offset] in the file that contains the declaration of this element.
MixinElementImpl(String name, int offset) : super(name, offset);
MixinElementImpl.forLinkedNode(CompilationUnitElementImpl enclosing,
Reference reference, MixinDeclaration linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created class element to have the given [name].
MixinElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
MixinElementImpl.forSerialized(
UnlinkedClass unlinkedClass, CompilationUnitElementImpl enclosingUnit)
: super.forSerialized(unlinkedClass, enclosingUnit);
@override
bool get isAbstract => true;
@override
bool get isMixin => true;
@override
List<InterfaceType> get mixins => const <InterfaceType>[];
@override
List<InterfaceType> get superclassConstraints {
if (_superclassConstraints != null) return _superclassConstraints;
if (linkedNode != null) {
List<InterfaceType> constraints;
var onClause = enclosingUnit.linkedContext.getOnClause(linkedNode);
if (onClause != null) {
constraints = onClause.superclassConstraints
.map((node) => node.type)
.whereType<InterfaceType>()
.where(_isInterfaceTypeInterface)
.toList();
}
if (constraints == null || constraints.isEmpty) {
constraints = [context.typeProvider.objectType];
}
return _superclassConstraints = constraints;
}
if (_unlinkedClass != null) {
List<InterfaceType> constraints;
if (_unlinkedClass.superclassConstraints.isNotEmpty) {
ResynthesizerContext context = enclosingUnit.resynthesizerContext;
constraints = _unlinkedClass.superclassConstraints
.map((EntityRef t) => context.resolveTypeRef(this, t))
.where(_isInterfaceTypeInterface)
.cast<InterfaceType>()
.toList(growable: false);
}
if (constraints == null || constraints.isEmpty) {
constraints = [context.typeProvider.objectType];
}
return _superclassConstraints = constraints;
}
return _superclassConstraints ?? const <InterfaceType>[];
}
void set superclassConstraints(List<InterfaceType> superclassConstraints) {
_assertNotResynthesized(_unlinkedClass);
// Note: if we are using the analysis driver, the set of superclass
// constraints has already been computed, and it's more accurate. So we
// only store superclass constraints if we are using the old task model.
if (_unlinkedClass == null) {
_superclassConstraints = superclassConstraints;
}
}
@override
List<String> get superInvokedNames {
if (_superInvokedNames != null) return _superInvokedNames;
if (linkedNode != null) {
return _superInvokedNames =
linkedContext.getMixinSuperInvokedNames(linkedNode);
}
if (_unlinkedClass != null) {
return _superInvokedNames = _unlinkedClass.superInvokedNames;
}
return _superInvokedNames ?? const <String>[];
}
void set superInvokedNames(List<String> superInvokedNames) {
_assertNotResynthesized(_unlinkedClass);
if (_unlinkedClass == null) {
_superInvokedNames = superInvokedNames;
}
}
@override
InterfaceType get supertype => null;
@override
void set supertype(InterfaceType supertype) {
throw new StateError('Attempt to set a supertype for a mixin declaratio.');
}
@override
void appendTo(StringBuffer buffer) {
buffer.write('mixin ');
String name = displayName;
if (name == null) {
// TODO(brianwilkerson) Can this happen (for either classes or mixins)?
buffer.write("{unnamed mixin}");
} else {
buffer.write(name);
}
int variableCount = typeParameters.length;
if (variableCount > 0) {
buffer.write("<");
for (int i = 0; i < variableCount; i++) {
if (i > 0) {
buffer.write(", ");
}
(typeParameters[i] as TypeParameterElementImpl).appendTo(buffer);
}
buffer.write(">");
}
if (superclassConstraints.isNotEmpty) {
buffer.write(' on ');
buffer.write(superclassConstraints.map((t) => t.displayName).join(', '));
}
if (interfaces.isNotEmpty) {
buffer.write(' implements ');
buffer.write(interfaces.map((t) => t.displayName).join(', '));
}
}
}
/// The constants for all of the modifiers defined by the Dart language and for
/// a few additional flags that are useful.
///
/// Clients may not extend, implement or mix-in this class.
class Modifier implements Comparable<Modifier> {
/// Indicates that the modifier 'abstract' was applied to the element.
static const Modifier ABSTRACT = const Modifier('ABSTRACT', 0);
/// Indicates that an executable element has a body marked as being
/// asynchronous.
static const Modifier ASYNCHRONOUS = const Modifier('ASYNCHRONOUS', 1);
/// Indicates that the modifier 'const' was applied to the element.
static const Modifier CONST = const Modifier('CONST', 2);
/// Indicates that the modifier 'covariant' was applied to the element.
static const Modifier COVARIANT = const Modifier('COVARIANT', 3);
/// Indicates that the import element represents a deferred library.
static const Modifier DEFERRED = const Modifier('DEFERRED', 4);
/// Indicates that a class element was defined by an enum declaration.
static const Modifier ENUM = const Modifier('ENUM', 5);
/// Indicates that a class element was defined by an enum declaration.
static const Modifier EXTERNAL = const Modifier('EXTERNAL', 6);
/// Indicates that the modifier 'factory' was applied to the element.
static const Modifier FACTORY = const Modifier('FACTORY', 7);
/// Indicates that the modifier 'final' was applied to the element.
static const Modifier FINAL = const Modifier('FINAL', 8);
/// Indicates that an executable element has a body marked as being a
/// generator.
static const Modifier GENERATOR = const Modifier('GENERATOR', 9);
/// Indicates that the pseudo-modifier 'get' was applied to the element.
static const Modifier GETTER = const Modifier('GETTER', 10);
/// A flag used for libraries indicating that the defining compilation unit
/// contains at least one import directive whose URI uses the "dart-ext"
/// scheme.
static const Modifier HAS_EXT_URI = const Modifier('HAS_EXT_URI', 11);
/// Indicates that the associated element did not have an explicit type
/// associated with it. If the element is an [ExecutableElement], then the
/// type being referred to is the return type.
static const Modifier IMPLICIT_TYPE = const Modifier('IMPLICIT_TYPE', 12);
/// Indicates that modifier 'lazy' was applied to the element.
static const Modifier LATE = const Modifier('LATE', 13);
/// Indicates that a class is a mixin application.
static const Modifier MIXIN_APPLICATION =
const Modifier('MIXIN_APPLICATION', 14);
/// Indicates that a class contains an explicit reference to 'super'.
static const Modifier REFERENCES_SUPER =
const Modifier('REFERENCES_SUPER', 15);
/// Indicates that the pseudo-modifier 'set' was applied to the element.
static const Modifier SETTER = const Modifier('SETTER', 16);
/// Indicates that the modifier 'static' was applied to the element.
static const Modifier STATIC = const Modifier('STATIC', 17);
/// Indicates that the element does not appear in the source code but was
/// implicitly created. For example, if a class does not define any
/// constructors, an implicit zero-argument constructor will be created and it
/// will be marked as being synthetic.
static const Modifier SYNTHETIC = const Modifier('SYNTHETIC', 18);
static const List<Modifier> values = const [
ABSTRACT,
ASYNCHRONOUS,
CONST,
COVARIANT,
DEFERRED,
ENUM,
EXTERNAL,
FACTORY,
FINAL,
GENERATOR,
GETTER,
HAS_EXT_URI,
IMPLICIT_TYPE,
LATE,
MIXIN_APPLICATION,
REFERENCES_SUPER,
SETTER,
STATIC,
SYNTHETIC
];
/// The name of this modifier.
final String name;
/// The ordinal value of the modifier.
final int ordinal;
const Modifier(this.name, this.ordinal);
@override
int get hashCode => ordinal;
@override
int compareTo(Modifier other) => ordinal - other.ordinal;
@override
String toString() => name;
}
/// A concrete implementation of a [MultiplyDefinedElement].
class MultiplyDefinedElementImpl implements MultiplyDefinedElement {
/// The unique integer identifier of this element.
final int id = ElementImpl._NEXT_ID++;
/// The analysis context in which the multiply defined elements are defined.
@override
final AnalysisContext context;
@override
final AnalysisSession session;
/// The name of the conflicting elements.
@override
final String name;
@override
final List<Element> conflictingElements;
/// Initialize a newly created element in the given [context] to represent
/// the given non-empty [conflictingElements].
MultiplyDefinedElementImpl(
this.context, this.session, this.name, this.conflictingElements);
@override
String get displayName => name;
@override
String get documentationComment => null;
@override
Element get enclosingElement => null;
@override
bool get hasAlwaysThrows => false;
@override
bool get hasDeprecated => false;
@override
bool get hasFactory => false;
@override
bool get hasIsTest => false;
@override
bool get hasIsTestGroup => false;
@override
bool get hasJS => false;
@override
bool get hasLiteral => false;
@override
bool get hasMustCallSuper => false;
@override
bool get hasOptionalTypeArgs => false;
@override
bool get hasOverride => false;
@override
bool get hasProtected => false;
@override
bool get hasRequired => false;
@override
bool get hasSealed => false;
@override
bool get hasVisibleForTemplate => false;
@override
bool get hasVisibleForTesting => false;
@override
bool get isAlwaysThrows => false;
@override
bool get isDeprecated => false;
@override
bool get isFactory => false;
@override
bool get isJS => false;
@override
bool get isOverride => false;
@override
bool get isPrivate {
String name = displayName;
if (name == null) {
return false;
}
return Identifier.isPrivateName(name);
}
@override
bool get isProtected => false;
@override
bool get isPublic => !isPrivate;
@override
bool get isRequired => false;
@override
bool get isSynthetic => true;
bool get isVisibleForTemplate => false;
@override
bool get isVisibleForTesting => false;
@override
ElementKind get kind => ElementKind.ERROR;
@override
LibraryElement get library => null;
@override
Source get librarySource => null;
@override
ElementLocation get location => null;
@override
List<ElementAnnotation> get metadata => const <ElementAnnotation>[];
@override
int get nameLength => displayName != null ? displayName.length : 0;
@override
int get nameOffset => -1;
@override
Source get source => null;
@override
DartType get type => DynamicTypeImpl.instance;
@override
CompilationUnit get unit => null;
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitMultiplyDefinedElement(this);
@override
String computeDocumentationComment() => null;
@deprecated
@override
AstNode computeNode() => null;
@override
E getAncestor<E extends Element>(Predicate<Element> predicate) => null;
@override
String getExtendedDisplayName(String shortName) {
if (shortName != null) {
return shortName;
}
return displayName;
}
@override
bool isAccessibleIn(LibraryElement library) {
for (Element element in conflictingElements) {
if (element.isAccessibleIn(library)) {
return true;
}
}
return false;
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
bool needsSeparator = false;
void writeList(List<Element> elements) {
for (Element element in elements) {
if (needsSeparator) {
buffer.write(", ");
} else {
needsSeparator = true;
}
if (element is ElementImpl) {
element.appendTo(buffer);
} else {
buffer.write(element);
}
}
}
buffer.write("[");
writeList(conflictingElements);
buffer.write("]");
return buffer.toString();
}
@override
void visitChildren(ElementVisitor visitor) {
// There are no children to visit
}
}
/// A [MethodElementImpl], with the additional information of a list of
/// [ExecutableElement]s from which this element was composed.
class MultiplyInheritedMethodElementImpl extends MethodElementImpl
implements MultiplyInheritedExecutableElement {
/// A list the array of executable elements that were used to compose this
/// element.
List<ExecutableElement> _elements = const <MethodElement>[];
MultiplyInheritedMethodElementImpl(Identifier name) : super.forNode(name) {
isSynthetic = true;
}
@override
List<ExecutableElement> get inheritedElements => _elements;
void set inheritedElements(List<ExecutableElement> elements) {
this._elements = elements;
}
}
/// A [PropertyAccessorElementImpl], with the additional information of a list
/// of[ExecutableElement]s from which this element was composed.
class MultiplyInheritedPropertyAccessorElementImpl
extends PropertyAccessorElementImpl
implements MultiplyInheritedExecutableElement {
/// A list the array of executable elements that were used to compose this
/// element.
List<ExecutableElement> _elements = const <PropertyAccessorElement>[];
MultiplyInheritedPropertyAccessorElementImpl(Identifier name)
: super.forNode(name) {
isSynthetic = true;
}
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext => null;
@override
List<ExecutableElement> get inheritedElements => _elements;
void set inheritedElements(List<ExecutableElement> elements) {
this._elements = elements;
}
}
/// The synthetic element representing the declaration of the type `Never`.
class NeverElementImpl extends ElementImpl implements TypeDefiningElement {
/// Return the unique instance of this class.
static NeverElementImpl get instance =>
BottomTypeImpl.instance.element as NeverElementImpl;
/// Initialize a newly created instance of this class. Instances of this class
/// should <b>not</b> be created except as part of creating the type
/// associated with this element. The single instance of this class should be
/// accessed through the method [instance].
NeverElementImpl() : super('Never', -1) {
setModifier(Modifier.SYNTHETIC, true);
}
@override
ElementKind get kind => ElementKind.NEVER;
@override
DartType get type {
throw StateError('Should not be accessed.');
}
@override
T accept<T>(ElementVisitor<T> visitor) => null;
DartType instantiate({
@required NullabilitySuffix nullabilitySuffix,
}) {
switch (nullabilitySuffix) {
case NullabilitySuffix.question:
return BottomTypeImpl.instanceNullable;
case NullabilitySuffix.star:
return BottomTypeImpl.instanceLegacy;
case NullabilitySuffix.none:
return BottomTypeImpl.instance;
}
throw StateError('Unsupported nullability: $nullabilitySuffix');
}
}
/// A [VariableElementImpl], which is not a parameter.
abstract class NonParameterVariableElementImpl extends VariableElementImpl {
/// The unlinked representation of the variable in the summary.
final UnlinkedVariable _unlinkedVariable;
/// Initialize a newly created variable element to have the given [name] and
/// [offset].
NonParameterVariableElementImpl(String name, int offset)
: _unlinkedVariable = null,
super(name, offset);
NonParameterVariableElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: _unlinkedVariable = null,
super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created variable element to have the given [name].
NonParameterVariableElementImpl.forNode(Identifier name)
: _unlinkedVariable = null,
super.forNode(name);
/// Initialize using the given serialized information.
NonParameterVariableElementImpl.forSerialized(
this._unlinkedVariable, ElementImpl enclosingElement)
: super.forSerialized(enclosingElement);
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (_unlinkedVariable != null) {
return _unlinkedVariable.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (_unlinkedVariable != null) {
return _unlinkedVariable.codeRange?.offset;
}
return super.codeOffset;
}
@override
String get documentationComment {
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var comment = context.getDocumentationComment(linkedNode);
return getCommentNodeRawText(comment);
}
if (_unlinkedVariable != null) {
return _unlinkedVariable.documentationComment?.text;
}
return super.documentationComment;
}
@override
bool get hasImplicitType {
if (linkedNode != null) {
return linkedContext.hasImplicitType(linkedNode);
}
if (_unlinkedVariable != null) {
return _unlinkedVariable.type == null;
}
return super.hasImplicitType;
}
@override
void set hasImplicitType(bool hasImplicitType) {
_assertNotResynthesized(_unlinkedVariable);
super.hasImplicitType = hasImplicitType;
}
@override
FunctionElement get initializer {
if (_initializer == null) {
if (linkedNode != null) {
if (linkedContext.hasInitializer(linkedNode)) {
_initializer = new FunctionElementImpl('', -1)
..isSynthetic = true
.._type = FunctionTypeImpl.synthetic(type, [], [])
..enclosingElement = this;
}
}
if (_unlinkedVariable != null) {
UnlinkedExecutable unlinkedInitializer = _unlinkedVariable.initializer;
if (unlinkedInitializer != null) {
_initializer =
new FunctionElementImpl.forSerialized(unlinkedInitializer, this)
..isSynthetic = true;
} else {
return null;
}
}
}
return super.initializer;
}
/// Set the function representing this variable's initializer to the given
/// [function].
void set initializer(FunctionElement function) {
_assertNotResynthesized(_unlinkedVariable);
super.initializer = function;
}
@override
bool get isConst {
if (_unlinkedVariable != null) {
return _unlinkedVariable.isConst;
}
return super.isConst;
}
@override
void set isConst(bool isConst) {
_assertNotResynthesized(_unlinkedVariable);
super.isConst = isConst;
}
@override
bool get isFinal {
if (_unlinkedVariable != null) {
return _unlinkedVariable.isFinal;
}
return super.isFinal;
}
@override
void set isFinal(bool isFinal) {
_assertNotResynthesized(_unlinkedVariable);
super.isFinal = isFinal;
}
@override
List<ElementAnnotation> get metadata {
if (_unlinkedVariable != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, _unlinkedVariable.annotations);
}
return super.metadata;
}
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
if (_unlinkedVariable != null) {
return _unlinkedVariable.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0) {
if (_unlinkedVariable != null) {
return _unlinkedVariable.nameOffset;
}
}
return offset;
}
@override
DartType get type {
if (_unlinkedVariable != null && _declaredType == null && _type == null) {
_type = enclosingUnit.resynthesizerContext
.resolveLinkedType(this, _unlinkedVariable.inferredTypeSlot);
declaredType = enclosingUnit.resynthesizerContext
.resolveTypeRef(this, _unlinkedVariable.type, declaredType: true);
}
return super.type;
}
@override
void set type(DartType type) {
if (linkedNode != null) {
return linkedContext.setVariableType(linkedNode, type);
}
_assertNotResynthesized(_unlinkedVariable);
_type = _checkElementOfType(type);
}
@override
TopLevelInferenceError get typeInferenceError {
if (linkedNode != null) {
return linkedContext.getTypeInferenceError(linkedNode);
}
if (_unlinkedVariable != null) {
return enclosingUnit.resynthesizerContext
.getTypeInferenceError(_unlinkedVariable.inferredTypeSlot);
}
// We don't support type inference errors without linking.
return null;
}
/// Subclasses need this getter, see [ConstVariableElement._unlinkedConst].
UnlinkedExpr get _unlinkedConst => _unlinkedVariable?.initializer?.bodyExpr;
}
/// A concrete implementation of a [ParameterElement].
class ParameterElementImpl extends VariableElementImpl
with ParameterElementMixin
implements ParameterElement {
/// The unlinked representation of the parameter in the summary.
final UnlinkedParam unlinkedParam;
/// A list containing all of the parameters defined by this parameter element.
/// There will only be parameters if this parameter is a function typed
/// parameter.
List<ParameterElement> _parameters;
/// A list containing all of the type parameters defined for this parameter
/// element. There will only be parameters if this parameter is a function
/// typed parameter.
List<TypeParameterElement> _typeParameters;
/// The kind of this parameter.
ParameterKind _parameterKind;
/// The Dart code of the default value.
String _defaultValueCode;
/// The offset to the beginning of the visible range for this element.
int _visibleRangeOffset = 0;
/// The length of the visible range for this element, or `-1` if this element
/// does not have a visible range.
int _visibleRangeLength = -1;
bool _inheritsCovariant = false;
/// Initialize a newly created parameter element to have the given [name] and
/// [nameOffset].
ParameterElementImpl(String name, int nameOffset)
: unlinkedParam = null,
super(name, nameOffset);
ParameterElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, FormalParameter linkedNode)
: unlinkedParam = null,
super.forLinkedNode(enclosing, reference, linkedNode);
factory ParameterElementImpl.forLinkedNodeFactory(
ElementImpl enclosing, Reference reference, FormalParameter node) {
if (node is FieldFormalParameter) {
return FieldFormalParameterElementImpl.forLinkedNode(
enclosing,
reference,
node,
);
} else if (node is FunctionTypedFormalParameter ||
node is SimpleFormalParameter) {
return ParameterElementImpl.forLinkedNode(enclosing, reference, node);
} else {
throw UnimplementedError('${node.runtimeType}');
}
}
/// Initialize a newly created parameter element to have the given [name].
ParameterElementImpl.forNode(Identifier name)
: unlinkedParam = null,
super.forNode(name);
/// Initialize using the given serialized information.
ParameterElementImpl.forSerialized(
this.unlinkedParam, ElementImpl enclosingElement)
: super.forSerialized(enclosingElement);
/// Initialize using the given serialized information.
factory ParameterElementImpl.forSerializedFactory(
UnlinkedParam unlinkedParameter, ElementImpl enclosingElement,
{bool synthetic: false}) {
ParameterElementImpl element;
if (unlinkedParameter.isInitializingFormal) {
if (unlinkedParameter.kind == UnlinkedParamKind.requiredPositional) {
element = new FieldFormalParameterElementImpl.forSerialized(
unlinkedParameter, enclosingElement);
} else {
element = new DefaultFieldFormalParameterElementImpl.forSerialized(
unlinkedParameter, enclosingElement);
}
} else {
if (unlinkedParameter.kind == UnlinkedParamKind.requiredPositional) {
element = new ParameterElementImpl.forSerialized(
unlinkedParameter, enclosingElement);
} else {
element = new DefaultParameterElementImpl.forSerialized(
unlinkedParameter, enclosingElement);
}
}
element.isSynthetic = synthetic;
return element;
}
/// Creates a synthetic parameter with [name], [type] and [kind].
factory ParameterElementImpl.synthetic(
String name, DartType type, ParameterKind kind) {
ParameterElementImpl element = new ParameterElementImpl(name, -1);
element.type = type;
element.isSynthetic = true;
element.parameterKind = kind;
return element;
}
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (unlinkedParam != null) {
return unlinkedParam.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (unlinkedParam != null) {
return unlinkedParam.codeRange?.offset;
}
return super.codeOffset;
}
@override
String get defaultValueCode {
if (linkedNode != null) {
return linkedContext.getDefaultValueCode(linkedNode);
}
if (unlinkedParam != null) {
if (unlinkedParam.initializer?.bodyExpr == null) {
return null;
}
return unlinkedParam.defaultValueCode;
}
return _defaultValueCode;
}
/// Set Dart code of the default value.
void set defaultValueCode(String defaultValueCode) {
_assertNotResynthesized(unlinkedParam);
this._defaultValueCode = StringUtilities.intern(defaultValueCode);
}
@override
bool get hasImplicitType {
if (linkedNode != null) {
return linkedContext.hasImplicitType(linkedNode);
}
if (unlinkedParam != null) {
return unlinkedParam.type == null && !unlinkedParam.isFunctionTyped;
}
return super.hasImplicitType;
}
@override
void set hasImplicitType(bool hasImplicitType) {
_assertNotResynthesized(unlinkedParam);
super.hasImplicitType = hasImplicitType;
}
/// True if this parameter inherits from a covariant parameter. This happens
/// when it overrides a method in a supertype that has a corresponding
/// covariant parameter.
bool get inheritsCovariant {
if (linkedNode != null) {
return linkedContext.getInheritsCovariant(linkedNode);
}
if (unlinkedParam != null) {
return enclosingUnit.resynthesizerContext
.inheritsCovariant(unlinkedParam.inheritsCovariantSlot);
} else {
return _inheritsCovariant;
}
}
/// Record whether or not this parameter inherits from a covariant parameter.
void set inheritsCovariant(bool value) {
if (linkedNode != null) {
linkedContext.setInheritsCovariant(linkedNode, value);
return;
}
_assertNotResynthesized(unlinkedParam);
_inheritsCovariant = value;
}
@override
FunctionElement get initializer {
if (_initializer == null) {
if (linkedNode != null) {
if (linkedContext.hasDefaultValue(linkedNode)) {
_initializer = FunctionElementImpl('', -1)
..enclosingElement = this
..isSynthetic = true;
}
}
if (unlinkedParam != null) {
UnlinkedExecutable unlinkedInitializer = unlinkedParam.initializer;
if (unlinkedInitializer != null) {
_initializer =
new FunctionElementImpl.forSerialized(unlinkedInitializer, this)
..isSynthetic = true;
} else {
return null;
}
}
}
return super.initializer;
}
/// Set the function representing this variable's initializer to the given
/// [function].
void set initializer(FunctionElement function) {
_assertNotResynthesized(unlinkedParam);
super.initializer = function;
}
@override
bool get isConst {
if (unlinkedParam != null) {
return false;
}
return super.isConst;
}
@override
void set isConst(bool isConst) {
_assertNotResynthesized(unlinkedParam);
super.isConst = isConst;
}
@override
bool get isCovariant {
if (isExplicitlyCovariant || inheritsCovariant) {
return true;
}
return false;
}
/// Return true if this parameter is explicitly marked as being covariant.
bool get isExplicitlyCovariant {
if (linkedNode != null) {
return linkedContext.isExplicitlyCovariant(linkedNode);
}
if (unlinkedParam != null) {
return unlinkedParam.isExplicitlyCovariant;
}
return hasModifier(Modifier.COVARIANT);
}
/// Set whether this variable parameter is explicitly marked as being
/// covariant.
void set isExplicitlyCovariant(bool isCovariant) {
_assertNotResynthesized(unlinkedParam);
setModifier(Modifier.COVARIANT, isCovariant);
}
@override
bool get isFinal {
if (linkedNode != null) {
FormalParameter linkedNode = this.linkedNode;
return linkedNode.isFinal;
}
if (unlinkedParam != null) {
return unlinkedParam.isFinal;
}
return super.isFinal;
}
@override
void set isFinal(bool isFinal) {
_assertNotResynthesized(unlinkedParam);
super.isFinal = isFinal;
}
@override
bool get isInitializingFormal => false;
@override
bool get isLate => false;
@override
bool get isPotentiallyMutatedInClosure => true;
@override
bool get isPotentiallyMutatedInScope => true;
@override
ElementKind get kind => ElementKind.PARAMETER;
@override
List<ElementAnnotation> get metadata {
if (unlinkedParam != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, unlinkedParam.annotations);
}
return super.metadata;
}
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
if (unlinkedParam != null) {
return unlinkedParam.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0) {
if (unlinkedParam != null) {
if (isSynthetic ||
(unlinkedParam.name.isEmpty &&
unlinkedParam.kind != UnlinkedParamKind.requiredNamed &&
unlinkedParam.kind != UnlinkedParamKind.optionalNamed &&
enclosingElement is GenericFunctionTypeElement)) {
return -1;
}
return unlinkedParam.nameOffset;
}
}
return offset;
}
@override
ParameterKind get parameterKind {
if (_parameterKind != null) return _parameterKind;
if (linkedNode != null) {
FormalParameter linkedNode = this.linkedNode;
// ignore: deprecated_member_use_from_same_package
return linkedNode.kind;
}
if (unlinkedParam != null) {
switch (unlinkedParam.kind) {
case UnlinkedParamKind.optionalNamed:
_parameterKind = ParameterKind.NAMED;
break;
case UnlinkedParamKind.optionalPositional:
_parameterKind = ParameterKind.POSITIONAL;
break;
case UnlinkedParamKind.requiredPositional:
_parameterKind = ParameterKind.REQUIRED;
break;
case UnlinkedParamKind.requiredNamed:
_parameterKind = ParameterKind.NAMED_REQUIRED;
break;
}
}
return _parameterKind;
}
void set parameterKind(ParameterKind parameterKind) {
_assertNotResynthesized(unlinkedParam);
_parameterKind = parameterKind;
}
@override
List<ParameterElement> get parameters {
if (_parameters != null) return _parameters;
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
var formalParameters = context.getFormalParameters(linkedNode);
if (formalParameters != null) {
var containerRef = reference.getChild('@parameter');
return _parameters = ParameterElementImpl.forLinkedNodeList(
this,
context,
containerRef,
formalParameters,
);
} else {
return _parameters ??= const <ParameterElement>[];
}
}
if (unlinkedParam != null) {
_resynthesizeTypeAndParameters();
return _parameters ??= const <ParameterElement>[];
}
return _parameters ??= const <ParameterElement>[];
}
/// Set the parameters defined by this executable element to the given
/// [parameters].
void set parameters(List<ParameterElement> parameters) {
for (ParameterElement parameter in parameters) {
(parameter as ParameterElementImpl).enclosingElement = this;
}
this._parameters = parameters;
}
@override
DartType get type {
if (linkedNode != null) {
if (_type != null) return _type;
var context = enclosingUnit.linkedContext;
return _type = context.getType(linkedNode);
}
_resynthesizeTypeAndParameters();
return super.type;
}
@override
TopLevelInferenceError get typeInferenceError {
if (linkedNode != null) {
return linkedContext.getTypeInferenceError(linkedNode);
}
if (unlinkedParam != null) {
return enclosingUnit.resynthesizerContext
.getTypeInferenceError(unlinkedParam.inferredTypeSlot);
}
// We don't support type inference errors without linking.
return null;
}
@override
List<TypeParameterElement> get typeParameters {
if (_typeParameters != null) return _typeParameters;
if (linkedNode != null) {
var typeParameters = linkedContext.getTypeParameters2(linkedNode);
if (typeParameters == null) {
return _typeParameters = const [];
}
var containerRef = reference.getChild('@typeParameter');
return _typeParameters =
typeParameters.typeParameters.map<TypeParameterElement>((node) {
var reference = containerRef.getChild(node.name.name);
if (reference.hasElementFor(node)) {
return reference.element as TypeParameterElement;
}
return TypeParameterElementImpl.forLinkedNode(this, reference, node);
}).toList();
}
return _typeParameters ??= const <TypeParameterElement>[];
}
/// Set the type parameters defined by this parameter element to the given
/// [typeParameters].
void set typeParameters(List<TypeParameterElement> typeParameters) {
for (TypeParameterElement parameter in typeParameters) {
(parameter as TypeParameterElementImpl).enclosingElement = this;
}
this._typeParameters = typeParameters;
}
@override
SourceRange get visibleRange {
if (unlinkedParam != null) {
if (unlinkedParam.visibleLength == 0) {
return null;
}
return new SourceRange(
unlinkedParam.visibleOffset, unlinkedParam.visibleLength);
}
if (_visibleRangeLength < 0) {
return null;
}
return new SourceRange(_visibleRangeOffset, _visibleRangeLength);
}
/// Subclasses need this getter, see [ConstVariableElement._unlinkedConst].
UnlinkedExpr get _unlinkedConst => unlinkedParam?.initializer?.bodyExpr;
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitParameterElement(this);
@override
void appendTo(StringBuffer buffer) {
if (isNamed) {
buffer.write('{');
if (isRequiredNamed) {
buffer.write('required ');
}
appendToWithoutDelimiters(buffer);
buffer.write('}');
} else if (isOptionalPositional) {
buffer.write('[');
appendToWithoutDelimiters(buffer);
buffer.write(']');
} else {
appendToWithoutDelimiters(buffer);
}
}
@deprecated
@override
FormalParameter computeNode() =>
getNodeMatching((node) => node is FormalParameter);
/// Set the visible range for this element to the range starting at the given
/// [offset] with the given [length].
void setVisibleRange(int offset, int length) {
_assertNotResynthesized(unlinkedParam);
_visibleRangeOffset = offset;
_visibleRangeLength = length;
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
safelyVisitChildren(parameters, visitor);
}
/// If this element is resynthesized, and its type and parameters have not
/// been build yet, build them and remember in the corresponding fields.
void _resynthesizeTypeAndParameters() {
if (unlinkedParam != null && _declaredType == null && _type == null) {
if (unlinkedParam.isFunctionTyped) {
CompilationUnitElementImpl enclosingUnit = this.enclosingUnit;
var typeElement = new GenericFunctionTypeElementImpl.forOffset(-1);
typeElement.enclosingElement = this;
_parameters = ParameterElementImpl.resynthesizeList(
unlinkedParam.parameters, typeElement,
synthetic: isSynthetic);
typeElement.parameters = _parameters;
typeElement.returnType = enclosingUnit.resynthesizerContext
.resolveTypeRef(this, unlinkedParam.type);
_type = new FunctionTypeImpl(typeElement);
typeElement.type = _type;
} else {
if (unlinkedParam.inferredTypeSlot != 0) {
_type = enclosingUnit.resynthesizerContext
.resolveLinkedType(this, unlinkedParam.inferredTypeSlot);
}
declaredType = enclosingUnit.resynthesizerContext
.resolveTypeRef(this, unlinkedParam.type, declaredType: true);
}
}
}
static List<ParameterElement> forLinkedNodeList(
ElementImpl enclosing,
LinkedUnitContext context,
Reference containerRef,
List<FormalParameter> formalParameters) {
if (formalParameters == null) {
return const [];
}
return formalParameters.map((node) {
if (node is DefaultFormalParameter) {
NormalFormalParameter parameterNode = node.parameter;
var name = parameterNode.identifier?.name ?? '';
var reference = containerRef.getChild(name);
reference.node = node;
if (parameterNode is FieldFormalParameter) {
return DefaultFieldFormalParameterElementImpl.forLinkedNode(
enclosing,
reference,
node,
);
} else {
return DefaultParameterElementImpl.forLinkedNode(
enclosing,
reference,
node,
);
}
} else {
if (node.identifier == null) {
return ParameterElementImpl.forLinkedNodeFactory(
enclosing,
containerRef.getChild(''),
node,
);
} else {
var name = node.identifier.name;
var reference = containerRef.getChild(name);
if (reference.hasElementFor(node)) {
return reference.element as ParameterElement;
}
return ParameterElementImpl.forLinkedNodeFactory(
enclosing,
reference,
node,
);
}
}
}).toList();
}
/// Create and return [ParameterElement]s for the given [unlinkedParameters].
static List<ParameterElement> resynthesizeList(
List<UnlinkedParam> unlinkedParameters, ElementImpl enclosingElement,
{bool synthetic: false}) {
int length = unlinkedParameters.length;
if (length != 0) {
List<ParameterElement> parameters = new List<ParameterElement>(length);
for (int i = 0; i < length; i++) {
parameters[i] = new ParameterElementImpl.forSerializedFactory(
unlinkedParameters[i], enclosingElement,
synthetic: synthetic);
}
return parameters;
} else {
return const <ParameterElement>[];
}
}
}
/// The parameter of an implicit setter.
class ParameterElementImpl_ofImplicitSetter extends ParameterElementImpl {
final PropertyAccessorElementImpl_ImplicitSetter setter;
ParameterElementImpl_ofImplicitSetter(
PropertyAccessorElementImpl_ImplicitSetter setter)
: setter = setter,
super('_${setter.variable.name}', setter.variable.nameOffset) {
enclosingElement = setter;
isSynthetic = true;
parameterKind = ParameterKind.REQUIRED;
}
@override
bool get inheritsCovariant {
PropertyInducingElement variable = setter.variable;
if (variable is FieldElementImpl) {
if (variable.linkedNode != null) {
var context = variable.linkedContext;
return context.getInheritsCovariant(variable.linkedNode);
}
if (variable._unlinkedVariable != null) {
return enclosingUnit.resynthesizerContext.inheritsCovariant(
variable._unlinkedVariable.inheritsCovariantSlot);
}
}
return false;
}
@override
void set inheritsCovariant(bool value) {
PropertyInducingElement variable = setter.variable;
if (variable is FieldElementImpl) {
if (variable.linkedNode != null) {
var context = variable.linkedContext;
return context.setInheritsCovariant(variable.linkedNode, value);
}
}
}
@override
bool get isCovariant {
if (isExplicitlyCovariant || inheritsCovariant) {
return true;
}
return false;
}
@override
bool get isExplicitlyCovariant {
PropertyInducingElement variable = setter.variable;
if (variable is FieldElementImpl) {
return variable.isCovariant;
}
return false;
}
@override
DartType get type => setter.variable.type;
@override
void set type(DartType type) {
assert(false); // Should never be called.
}
}
/// A mixin that provides a common implementation for methods defined in
/// [ParameterElement].
mixin ParameterElementMixin implements ParameterElement {
@override
bool get isNamed =>
parameterKind == ParameterKind.NAMED ||
parameterKind == ParameterKind.NAMED_REQUIRED;
@override
bool get isNotOptional =>
parameterKind == ParameterKind.REQUIRED ||
parameterKind == ParameterKind.NAMED_REQUIRED;
@override
bool get isOptional =>
parameterKind == ParameterKind.NAMED ||
parameterKind == ParameterKind.POSITIONAL;
@override
bool get isOptionalNamed => parameterKind == ParameterKind.NAMED;
@override
bool get isOptionalPositional => parameterKind == ParameterKind.POSITIONAL;
@override
bool get isPositional =>
parameterKind == ParameterKind.POSITIONAL ||
parameterKind == ParameterKind.REQUIRED;
@override
bool get isRequiredNamed => parameterKind == ParameterKind.NAMED_REQUIRED;
@override
bool get isRequiredPositional => parameterKind == ParameterKind.REQUIRED;
@override
// Overridden to remove the 'deprecated' annotation.
ParameterKind get parameterKind;
@override
void appendToWithoutDelimiters(StringBuffer buffer) {
buffer.write(type);
buffer.write(' ');
buffer.write(displayName);
if (defaultValueCode != null) {
buffer.write(' = ');
buffer.write(defaultValueCode);
}
}
}
/// A concrete implementation of a [PrefixElement].
class PrefixElementImpl extends ElementImpl implements PrefixElement {
/// The unlinked representation of the import in the summary.
final UnlinkedImport _unlinkedImport;
/// Initialize a newly created method element to have the given [name] and
/// [nameOffset].
PrefixElementImpl(String name, int nameOffset)
: _unlinkedImport = null,
super(name, nameOffset);
PrefixElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, SimpleIdentifier linkedNode)
: _unlinkedImport = null,
super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created prefix element to have the given [name].
PrefixElementImpl.forNode(Identifier name)
: _unlinkedImport = null,
super.forNode(name);
/// Initialize using the given serialized information.
PrefixElementImpl.forSerialized(
this._unlinkedImport, LibraryElementImpl enclosingLibrary)
: super.forSerialized(enclosingLibrary);
@override
String get displayName => name;
@override
LibraryElement get enclosingElement =>
super.enclosingElement as LibraryElement;
@override
List<LibraryElement> get importedLibraries => const <LibraryElement>[];
@override
ElementKind get kind => ElementKind.PREFIX;
@override
String get name {
if (linkedNode != null) {
return reference.name;
}
if (_name == null) {
if (_unlinkedImport != null) {
LibraryElementImpl library = enclosingElement as LibraryElementImpl;
int prefixId = _unlinkedImport.prefixReference;
return _name = library.unlinkedDefiningUnit.references[prefixId].name;
}
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return (linkedNode as SimpleIdentifier).offset;
}
int offset = super.nameOffset;
if (offset == 0 && _unlinkedImport != null) {
return _unlinkedImport.prefixOffset;
}
return offset;
}
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitPrefixElement(this);
@override
void appendTo(StringBuffer buffer) {
buffer.write("as ");
super.appendTo(buffer);
}
}
/// A concrete implementation of a [PropertyAccessorElement].
class PropertyAccessorElementImpl extends ExecutableElementImpl
implements PropertyAccessorElement {
/// The variable associated with this accessor.
PropertyInducingElement variable;
/// Initialize a newly created property accessor element to have the given
/// [name] and [offset].
PropertyAccessorElementImpl(String name, int offset) : super(name, offset);
PropertyAccessorElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created property accessor element to have the given
/// [name].
PropertyAccessorElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
PropertyAccessorElementImpl.forSerialized(
UnlinkedExecutable serializedExecutable, ElementImpl enclosingElement)
: super.forSerialized(serializedExecutable, enclosingElement);
/// Initialize a newly created synthetic property accessor element to be
/// associated with the given [variable].
PropertyAccessorElementImpl.forVariable(PropertyInducingElementImpl variable,
{Reference reference})
: super(variable.name, variable.nameOffset, reference: reference) {
this.variable = variable;
isStatic = variable.isStatic;
isSynthetic = true;
}
@override
PropertyAccessorElement get correspondingGetter {
if (isGetter || variable == null) {
return null;
}
return variable.getter;
}
@override
PropertyAccessorElement get correspondingSetter {
if (isSetter || variable == null) {
return null;
}
return variable.setter;
}
@override
String get displayName {
if (serializedExecutable != null && isSetter) {
String name = serializedExecutable.name;
assert(name.endsWith('='));
return name.substring(0, name.length - 1);
}
return super.displayName;
}
@override
TypeParameterizedElementMixin get enclosingTypeParameterContext {
return (enclosingElement as ElementImpl).typeParameterContext;
}
/// Set whether this accessor is a getter.
void set getter(bool isGetter) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.GETTER, isGetter);
}
@override
String get identifier {
String name = displayName;
String suffix = isGetter ? "?" : "=";
return "$name$suffix";
}
/// Set whether this class is abstract.
void set isAbstract(bool isAbstract) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.ABSTRACT, isAbstract);
}
@override
bool get isGetter {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isGetter(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.kind == UnlinkedExecutableKind.getter;
}
return hasModifier(Modifier.GETTER);
}
@override
bool get isSetter {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isSetter(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.kind == UnlinkedExecutableKind.setter;
}
return hasModifier(Modifier.SETTER);
}
@override
bool get isStatic {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isStatic(linkedNode);
}
if (serializedExecutable != null) {
return serializedExecutable.isStatic ||
variable is TopLevelVariableElement;
}
return hasModifier(Modifier.STATIC);
}
/// Set whether this accessor is static.
void set isStatic(bool isStatic) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.STATIC, isStatic);
}
@override
ElementKind get kind {
if (isGetter) {
return ElementKind.GETTER;
}
return ElementKind.SETTER;
}
@override
String get name {
if (linkedNode != null) {
var name = reference.name;
if (isSetter) {
return '$name=';
}
return name;
}
if (serializedExecutable != null) {
return serializedExecutable.name;
}
if (isSetter) {
return "${super.name}=";
}
return super.name;
}
/// Set whether this accessor is a setter.
void set setter(bool isSetter) {
_assertNotResynthesized(serializedExecutable);
setModifier(Modifier.SETTER, isSetter);
}
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitPropertyAccessorElement(this);
@override
void appendTo(StringBuffer buffer) {
super.appendToWithName(
buffer, (isGetter ? 'get ' : 'set ') + variable.displayName);
}
@deprecated
@override
AstNode computeNode() {
if (isSynthetic) {
return null;
}
if (enclosingElement is ClassElement) {
return getNodeMatching((node) => node is MethodDeclaration);
} else if (enclosingElement is CompilationUnitElement) {
return getNodeMatching((node) => node is FunctionDeclaration);
}
return null;
}
}
/// Implicit getter for a [PropertyInducingElementImpl].
class PropertyAccessorElementImpl_ImplicitGetter
extends PropertyAccessorElementImpl {
/// Create the implicit getter and bind it to the [property].
PropertyAccessorElementImpl_ImplicitGetter(
PropertyInducingElementImpl property,
{Reference reference})
: super.forVariable(property, reference: reference) {
property.getter = this;
enclosingElement = property.enclosingElement;
}
@override
bool get hasImplicitReturnType => variable.hasImplicitType;
@override
bool get isGetter => true;
@override
DartType get returnType => variable.type;
@override
void set returnType(DartType returnType) {
assert(false); // Should never be called.
}
@override
FunctionType get type {
return _type ??= new FunctionTypeImpl(this);
}
@override
void set type(FunctionType type) {
assert(false); // Should never be called.
}
}
/// Implicit setter for a [PropertyInducingElementImpl].
class PropertyAccessorElementImpl_ImplicitSetter
extends PropertyAccessorElementImpl {
/// Create the implicit setter and bind it to the [property].
PropertyAccessorElementImpl_ImplicitSetter(
PropertyInducingElementImpl property,
{Reference reference})
: super.forVariable(property, reference: reference) {
property.setter = this;
enclosingElement = property.enclosingElement;
}
@override
bool get isSetter => true;
@override
List<ParameterElement> get parameters {
return _parameters ??= <ParameterElement>[
new ParameterElementImpl_ofImplicitSetter(this)
];
}
@override
DartType get returnType => VoidTypeImpl.instance;
@override
void set returnType(DartType returnType) {
assert(false); // Should never be called.
}
@override
FunctionType get type {
return _type ??= new FunctionTypeImpl(this);
}
@override
void set type(FunctionType type) {
assert(false); // Should never be called.
}
}
/// A concrete implementation of a [PropertyInducingElement].
abstract class PropertyInducingElementImpl
extends NonParameterVariableElementImpl implements PropertyInducingElement {
/// The getter associated with this element.
PropertyAccessorElement getter;
/// The setter associated with this element, or `null` if the element is
/// effectively `final` and therefore does not have a setter associated with
/// it.
PropertyAccessorElement setter;
/// Initialize a newly created synthetic element to have the given [name] and
/// [offset].
PropertyInducingElementImpl(String name, int offset) : super(name, offset);
PropertyInducingElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created element to have the given [name].
PropertyInducingElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
PropertyInducingElementImpl.forSerialized(
UnlinkedVariable unlinkedVariable, ElementImpl enclosingElement)
: super.forSerialized(unlinkedVariable, enclosingElement);
@override
bool get isConstantEvaluated => true;
@override
bool get isLate {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isLate(linkedNode);
}
if (_unlinkedVariable != null) {
return _unlinkedVariable.isLate;
}
return hasModifier(Modifier.LATE);
}
@deprecated
@override
DartType get propagatedType => null;
@deprecated
void set propagatedType(DartType propagatedType) {}
@override
DartType get type {
if (linkedNode != null) {
if (_type != null) return _type;
return _type = linkedContext.getType(linkedNode);
}
if (isSynthetic && _type == null) {
if (getter != null) {
_type = getter.returnType;
} else if (setter != null) {
List<ParameterElement> parameters = setter.parameters;
_type = parameters.isNotEmpty
? parameters[0].type
: DynamicTypeImpl.instance;
} else {
_type = DynamicTypeImpl.instance;
}
}
return super.type;
}
}
/// The context in which elements are resynthesized.
abstract class ResynthesizerContext {
@deprecated
bool get isStrongMode;
/// Build [ElementAnnotationImpl] for the given [UnlinkedExpr].
ElementAnnotationImpl buildAnnotation(ElementImpl context, UnlinkedExpr uc);
/// Build [Expression] for the given [UnlinkedExpr].
Expression buildExpression(ElementImpl context, UnlinkedExpr uc);
/// Build explicit top-level property accessors.
UnitExplicitTopLevelAccessors buildTopLevelAccessors();
/// Build explicit top-level variables.
UnitExplicitTopLevelVariables buildTopLevelVariables();
/// Return the error reported during type inference for the given [slot],
/// or `null` if there was no error.
TopLevelInferenceError getTypeInferenceError(int slot);
/// Return `true` if the given parameter [slot] inherits `@covariant`
/// behavior.
bool inheritsCovariant(int slot);
/// Return `true` if the given const constructor [slot] is a part of a cycle.
bool isInConstCycle(int slot);
bool isSimplyBounded(int notSimplyBoundedSlot);
/// Resolve an [EntityRef] into a constructor. If the reference is
/// unresolved, return `null`.
ConstructorElement resolveConstructorRef(
ElementImpl context, EntityRef entry);
/// Build the appropriate [DartType] object corresponding to a slot id in the
/// [LinkedUnit.types] table.
DartType resolveLinkedType(ElementImpl context, int slot);
/// Resolve an [EntityRef] into a type. If the reference is
/// unresolved, return [DynamicTypeImpl.instance].
///
/// TODO(paulberry): or should we have a class representing an
/// unresolved type, for consistency with the full element model?
DartType resolveTypeRef(ElementImpl context, EntityRef type,
{bool defaultVoid: false,
bool instantiateToBoundsAllowed: true,
bool declaredType: false});
}
/// A concrete implementation of a [ShowElementCombinator].
class ShowElementCombinatorImpl implements ShowElementCombinator {
/// The unlinked representation of the combinator in the summary.
final UnlinkedCombinator _unlinkedCombinator;
final LinkedUnitContext linkedContext;
final ShowCombinator linkedNode;
/// The names that are to be made visible in the importing library if they are
/// defined in the imported library.
List<String> _shownNames;
/// The offset of the character immediately following the last character of
/// this node.
int _end = -1;
/// The offset of the 'show' keyword of this element.
int _offset = 0;
ShowElementCombinatorImpl()
: _unlinkedCombinator = null,
linkedContext = null,
linkedNode = null;
ShowElementCombinatorImpl.forLinkedNode(this.linkedContext, this.linkedNode)
: _unlinkedCombinator = null;
/// Initialize using the given serialized information.
ShowElementCombinatorImpl.forSerialized(this._unlinkedCombinator)
: linkedContext = null,
linkedNode = null;
@override
int get end {
if (linkedNode != null) {
return linkedContext.getCombinatorEnd(linkedNode);
}
if (_unlinkedCombinator != null) {
return _unlinkedCombinator.end;
}
return _end;
}
void set end(int end) {
_assertNotResynthesized(_unlinkedCombinator);
_end = end;
}
@override
int get offset {
if (linkedNode != null) {
return linkedNode.keyword.offset;
}
if (_unlinkedCombinator != null) {
return _unlinkedCombinator.offset;
}
return _offset;
}
void set offset(int offset) {
_assertNotResynthesized(_unlinkedCombinator);
_offset = offset;
}
@override
List<String> get shownNames {
if (_shownNames != null) return _shownNames;
if (linkedNode != null) {
return _shownNames = linkedNode.shownNames.map((i) => i.name).toList();
}
if (_unlinkedCombinator != null) {
return _shownNames = _unlinkedCombinator.shows.toList(growable: false);
}
return _shownNames ?? const <String>[];
}
void set shownNames(List<String> shownNames) {
_assertNotResynthesized(_unlinkedCombinator);
_shownNames = shownNames;
}
@override
String toString() {
StringBuffer buffer = new StringBuffer();
buffer.write("show ");
int count = shownNames.length;
for (int i = 0; i < count; i++) {
if (i > 0) {
buffer.write(", ");
}
buffer.write(shownNames[i]);
}
return buffer.toString();
}
}
/// Mixin providing the implementation of
/// [TypeParameterizedElement.isSimplyBounded] for elements that define a type.
mixin SimplyBoundableMixin implements TypeParameterizedElement {
CompilationUnitElementImpl get enclosingUnit;
@override
bool get isSimplyBounded {
var notSimplyBoundedSlot = _notSimplyBoundedSlot;
if (notSimplyBoundedSlot == null) {
// No summary is in use; we must be on the old task model. Not supported.
// TODO(paulberry): remove this check when the old task model is gone.
return true;
}
if (notSimplyBoundedSlot == 0) {
return true;
}
return enclosingUnit.resynthesizerContext
.isSimplyBounded(_notSimplyBoundedSlot);
}
int get _notSimplyBoundedSlot;
}
/// A concrete implementation of a [TopLevelVariableElement].
class TopLevelVariableElementImpl extends PropertyInducingElementImpl
implements TopLevelVariableElement {
/// Initialize a newly created synthetic top-level variable element to have
/// the given [name] and [offset].
TopLevelVariableElementImpl(String name, int offset) : super(name, offset);
TopLevelVariableElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode) {
if (!linkedNode.isSynthetic) {
var enclosingRef = enclosing.reference;
this.getter = PropertyAccessorElementImpl_ImplicitGetter(
this,
reference: enclosingRef.getChild('@getter').getChild(name),
);
if (!isConst && !isFinal) {
this.setter = PropertyAccessorElementImpl_ImplicitSetter(
this,
reference: enclosingRef.getChild('@setter').getChild(name),
);
}
}
}
factory TopLevelVariableElementImpl.forLinkedNodeFactory(
ElementImpl enclosing, Reference reference, AstNode linkedNode) {
if (enclosing.enclosingUnit.linkedContext.isConst(linkedNode)) {
return ConstTopLevelVariableElementImpl.forLinkedNode(
enclosing,
reference,
linkedNode,
);
}
return TopLevelVariableElementImpl.forLinkedNode(
enclosing,
reference,
linkedNode,
);
}
/// Initialize a newly created top-level variable element to have the given
/// [name].
TopLevelVariableElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
TopLevelVariableElementImpl.forSerialized(
UnlinkedVariable unlinkedVariable, ElementImpl enclosingElement)
: super.forSerialized(unlinkedVariable, enclosingElement);
@override
bool get isStatic => true;
@override
ElementKind get kind => ElementKind.TOP_LEVEL_VARIABLE;
UnlinkedVariable get unlinkedVariableForTesting => _unlinkedVariable;
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitTopLevelVariableElement(this);
@deprecated
@override
VariableDeclaration computeNode() =>
getNodeMatching((node) => node is VariableDeclaration);
}
/// A concrete implementation of a [TypeParameterElement].
class TypeParameterElementImpl extends ElementImpl
implements TypeParameterElement {
/// The unlinked representation of the type parameter in the summary.
final UnlinkedTypeParam _unlinkedTypeParam;
/// The default value of the type parameter. It is used to provide the
/// corresponding missing type argument in type annotations and as the
/// fall-back type value in type inference.
DartType _defaultType;
/// The type defined by this type parameter.
TypeParameterType _type;
/// The type representing the bound associated with this parameter, or `null`
/// if this parameter does not have an explicit bound.
DartType _bound;
/// Initialize a newly created method element to have the given [name] and
/// [offset].
TypeParameterElementImpl(String name, int offset)
: _unlinkedTypeParam = null,
super(name, offset);
TypeParameterElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, TypeParameter linkedNode)
: _unlinkedTypeParam = null,
super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created type parameter element to have the given
/// [name].
TypeParameterElementImpl.forNode(Identifier name)
: _unlinkedTypeParam = null,
super.forNode(name);
/// Initialize using the given serialized information.
TypeParameterElementImpl.forSerialized(
this._unlinkedTypeParam, ElementImpl enclosingElement)
: super.forSerialized(enclosingElement);
/// Initialize a newly created synthetic type parameter element to have the
/// given [name], and with [synthetic] set to true.
TypeParameterElementImpl.synthetic(String name)
: _unlinkedTypeParam = null,
super(name, -1) {
isSynthetic = true;
}
DartType get bound {
if (_bound != null) return _bound;
if (linkedNode != null) {
var context = enclosingUnit.linkedContext;
return _bound = context.getTypeParameterBound(linkedNode)?.type;
}
if (_unlinkedTypeParam != null) {
if (_unlinkedTypeParam.bound == null) {
return null;
}
return _bound = enclosingUnit.resynthesizerContext.resolveTypeRef(
this, _unlinkedTypeParam.bound,
instantiateToBoundsAllowed: false, declaredType: true);
}
return _bound;
}
void set bound(DartType bound) {
_assertNotResynthesized(_unlinkedTypeParam);
_bound = _checkElementOfType(bound);
}
@override
int get codeLength {
if (linkedNode != null) {
return linkedContext.getCodeLength(linkedNode);
}
if (_unlinkedTypeParam != null) {
return _unlinkedTypeParam.codeRange?.length;
}
return super.codeLength;
}
@override
int get codeOffset {
if (linkedNode != null) {
return linkedContext.getCodeOffset(linkedNode);
}
if (_unlinkedTypeParam != null) {
return _unlinkedTypeParam.codeRange?.offset;
}
return super.codeOffset;
}
/// The default value of the type parameter. It is used to provide the
/// corresponding missing type argument in type annotations and as the
/// fall-back type value in type inference.
DartType get defaultType {
if (_defaultType != null) return _defaultType;
if (linkedNode != null) {
return _defaultType = linkedContext.getDefaultType(linkedNode);
}
return null;
}
set defaultType(DartType defaultType) {
_defaultType = defaultType;
}
@override
String get displayName => name;
@override
ElementKind get kind => ElementKind.TYPE_PARAMETER;
@override
List<ElementAnnotation> get metadata {
if (_unlinkedTypeParam != null) {
return _metadata ??=
_buildAnnotations(enclosingUnit, _unlinkedTypeParam.annotations);
}
return super.metadata;
}
@override
String get name {
if (linkedNode != null) {
TypeParameter node = this.linkedNode;
return node.name.name;
}
if (_unlinkedTypeParam != null) {
return _unlinkedTypeParam.name;
}
return super.name;
}
@override
int get nameOffset {
if (linkedNode != null) {
return enclosingUnit.linkedContext.getNameOffset(linkedNode);
}
int offset = super.nameOffset;
if (offset == 0 && _unlinkedTypeParam != null) {
return _unlinkedTypeParam.nameOffset;
}
return offset;
}
TypeParameterType get type {
// Note: TypeParameterElement.type has nullability suffix `star` regardless
// of whether it appears in a migrated library. This is because for type
// parameters of synthetic function types, the ancestor chain is broken and
// we can't find the enclosing library to tell whether it is migrated.
return _type ??= new TypeParameterTypeImpl(this);
}
void set type(TypeParameterType type) {
_type = type;
}
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitTypeParameterElement(this);
@override
void appendTo(StringBuffer buffer) {
buffer.write(displayName);
if (bound != null) {
buffer.write(" extends ");
buffer.write(bound);
}
}
@override
TypeParameterType instantiate({
@required NullabilitySuffix nullabilitySuffix,
}) {
return TypeParameterTypeImpl(this, nullabilitySuffix: nullabilitySuffix);
}
}
/// Mixin representing an element which can have type parameters.
mixin TypeParameterizedElementMixin
implements
TypeParameterizedElement,
ElementImpl,
TypeParameterSerializationContext {
/// A cached list containing the type parameters declared by this element
/// directly, or `null` if the elements have not been created yet. This does
/// not include type parameters that are declared by any enclosing elements.
List<TypeParameterElement> _typeParameterElements;
/// A cached list containing the type parameter types declared by this element
/// directly, or `null` if the list has not been computed yet.
List<TypeParameterType> _typeParameterTypes;
/// Get the type parameter context enclosing this one, if any.
TypeParameterizedElementMixin get enclosingTypeParameterContext;
@override
bool get isSimplyBounded => true;
@override
TypeParameterizedElementMixin get typeParameterContext => this;
@override
List<TypeParameterElement> get typeParameters {
if (_typeParameterElements != null) return _typeParameterElements;
if (linkedNode != null) {
var typeParameters = linkedContext.getTypeParameters2(linkedNode);
if (typeParameters == null) {
return _typeParameterElements = const [];
}
var containerRef = reference.getChild('@typeParameter');
return _typeParameterElements =
typeParameters.typeParameters.map<TypeParameterElement>((node) {
var reference = containerRef.getChild(node.name.name);
if (reference.hasElementFor(node)) {
return reference.element as TypeParameterElement;
}
return TypeParameterElementImpl.forLinkedNode(this, reference, node);
}).toList();
}
List<UnlinkedTypeParam> unlinkedParams = unlinkedTypeParams;
if (unlinkedParams != null) {
int numTypeParameters = unlinkedParams.length;
_typeParameterElements =
new List<TypeParameterElement>(numTypeParameters);
for (int i = 0; i < numTypeParameters; i++) {
_typeParameterElements[i] =
new TypeParameterElementImpl.forSerialized(unlinkedParams[i], this);
}
}
return _typeParameterElements ?? const <TypeParameterElement>[];
}
/// Get a list of [TypeParameterType] objects corresponding to the
/// element's type parameters.
List<TypeParameterType> get typeParameterTypes {
return _typeParameterTypes ??= typeParameters
.map((TypeParameterElement e) =>
e.instantiate(nullabilitySuffix: NullabilitySuffix.star))
.toList(growable: false);
}
/// Get the [UnlinkedTypeParam]s representing the type parameters declared by
/// this element, or `null` if this element isn't from a summary.
///
/// TODO(scheglov) make private after switching linker to Impl
List<UnlinkedTypeParam> get unlinkedTypeParams;
@override
int computeDeBruijnIndex(TypeParameterElement typeParameter,
{int offset = 0}) {
if (typeParameter.enclosingElement == this) {
var index = typeParameters.indexOf(typeParameter);
assert(index >= 0);
return typeParameters.length - index + offset;
} else if (enclosingTypeParameterContext != null) {
return enclosingTypeParameterContext.computeDeBruijnIndex(typeParameter,
offset: offset + typeParameters.length);
} else {
return null;
}
}
/// Convert the given [index] into a type parameter type.
TypeParameterType getTypeParameterType(int index) {
List<TypeParameterType> types = typeParameterTypes;
if (index <= types.length) {
return types[types.length - index];
} else if (enclosingTypeParameterContext != null) {
return enclosingTypeParameterContext
.getTypeParameterType(index - types.length);
} else {
// If we get here, it means that a summary contained a type parameter
// index that was out of range.
throw new RangeError('Invalid type parameter index');
}
}
}
/// Interface used by linker serialization methods to convert type parameter
/// references into De Bruijn indices.
abstract class TypeParameterSerializationContext {
/// Return the given [typeParameter]'s de Bruijn index in this context, or
/// `null` if it's not in scope.
///
/// If an [offset] is provided, then it is added to the computed index.
int computeDeBruijnIndex(TypeParameterElement typeParameter, {int offset: 0});
}
/// Container with information about explicit top-level property accessors and
/// corresponding implicit top-level variables.
class UnitExplicitTopLevelAccessors {
final List<PropertyAccessorElementImpl> accessors =
<PropertyAccessorElementImpl>[];
final List<TopLevelVariableElementImpl> implicitVariables =
<TopLevelVariableElementImpl>[];
}
/// Container with information about explicit top-level variables and
/// corresponding implicit top-level property accessors.
class UnitExplicitTopLevelVariables {
final List<TopLevelVariableElementImpl> variables;
final List<PropertyAccessorElementImpl> implicitAccessors =
<PropertyAccessorElementImpl>[];
UnitExplicitTopLevelVariables(int numberOfVariables)
: variables = numberOfVariables != 0
? new List<TopLevelVariableElementImpl>(numberOfVariables)
: const <TopLevelVariableElementImpl>[];
}
/// A concrete implementation of a [UriReferencedElement].
abstract class UriReferencedElementImpl extends ElementImpl
implements UriReferencedElement {
/// The offset of the URI in the file, or `-1` if this node is synthetic.
int _uriOffset = -1;
/// The offset of the character immediately following the last character of
/// this node's URI, or `-1` if this node is synthetic.
int _uriEnd = -1;
/// The URI that is specified by this directive.
String _uri;
/// Initialize a newly created import element to have the given [name] and
/// [offset]. The offset may be `-1` if the element is synthetic.
UriReferencedElementImpl(String name, int offset) : super(name, offset);
UriReferencedElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize using the given serialized information.
UriReferencedElementImpl.forSerialized(ElementImpl enclosingElement)
: super.forSerialized(enclosingElement);
/// Return the URI that is specified by this directive.
String get uri => _uri;
/// Set the URI that is specified by this directive to be the given [uri].
void set uri(String uri) {
_uri = uri;
}
/// Return the offset of the character immediately following the last
/// character of this node's URI, or `-1` if this node is synthetic.
int get uriEnd => _uriEnd;
/// Set the offset of the character immediately following the last character
/// of this node's URI to the given [offset].
void set uriEnd(int offset) {
_uriEnd = offset;
}
/// Return the offset of the URI in the file, or `-1` if this node is
/// synthetic.
int get uriOffset => _uriOffset;
/// Set the offset of the URI in the file to the given [offset].
void set uriOffset(int offset) {
_uriOffset = offset;
}
String _selectUri(
String defaultUri, List<UnlinkedConfiguration> configurations) {
for (UnlinkedConfiguration configuration in configurations) {
if (context.declaredVariables.get(configuration.name) ==
configuration.value) {
return configuration.uri;
}
}
return defaultUri;
}
}
/// A concrete implementation of a [VariableElement].
abstract class VariableElementImpl extends ElementImpl
implements VariableElement {
/// The declared type of this variable.
DartType _declaredType;
/// The inferred type of this variable.
DartType _type;
/// A synthetic function representing this variable's initializer, or `null
///` if this variable does not have an initializer.
FunctionElement _initializer;
/// Initialize a newly created variable element to have the given [name] and
/// [offset].
VariableElementImpl(String name, int offset) : super(name, offset);
VariableElementImpl.forLinkedNode(
ElementImpl enclosing, Reference reference, AstNode linkedNode)
: super.forLinkedNode(enclosing, reference, linkedNode);
/// Initialize a newly created variable element to have the given [name].
VariableElementImpl.forNode(Identifier name) : super.forNode(name);
/// Initialize using the given serialized information.
VariableElementImpl.forSerialized(ElementImpl enclosingElement)
: super.forSerialized(enclosingElement);
/// If this element represents a constant variable, and it has an initializer,
/// a copy of the initializer for the constant. Otherwise `null`.
///
/// Note that in correct Dart code, all constant variables must have
/// initializers. However, analyzer also needs to handle incorrect Dart code,
/// in which case there might be some constant variables that lack
/// initializers.
Expression get constantInitializer => null;
@override
DartObject get constantValue => evaluationResult?.value;
void set declaredType(DartType type) {
_declaredType = _checkElementOfType(type);
}
@override
String get displayName => name;
/// Return the result of evaluating this variable's initializer as a
/// compile-time constant expression, or `null` if this variable is not a
/// 'const' variable, if it does not have an initializer, or if the
/// compilation unit containing the variable has not been resolved.
EvaluationResultImpl get evaluationResult => null;
/// Set the result of evaluating this variable's initializer as a compile-time
/// constant expression to the given [result].
void set evaluationResult(EvaluationResultImpl result) {
throw new StateError(
"Invalid attempt to set a compile-time constant result");
}
@override
bool get hasImplicitType {
return hasModifier(Modifier.IMPLICIT_TYPE);
}
/// Set whether this variable element has an implicit type.
void set hasImplicitType(bool hasImplicitType) {
setModifier(Modifier.IMPLICIT_TYPE, hasImplicitType);
}
@override
FunctionElement get initializer => _initializer;
/// Set the function representing this variable's initializer to the given
/// [function].
void set initializer(FunctionElement function) {
if (function != null) {
(function as FunctionElementImpl).enclosingElement = this;
}
this._initializer = function;
}
@override
bool get isConst {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isConst(linkedNode);
}
return hasModifier(Modifier.CONST);
}
/// Set whether this variable is const.
void set isConst(bool isConst) {
setModifier(Modifier.CONST, isConst);
}
@override
bool get isConstantEvaluated => true;
@override
bool get isFinal {
if (linkedNode != null) {
return enclosingUnit.linkedContext.isFinal(linkedNode);
}
return hasModifier(Modifier.FINAL);
}
/// Set whether this variable is final.
void set isFinal(bool isFinal) {
setModifier(Modifier.FINAL, isFinal);
}
@override
bool get isPotentiallyMutatedInClosure => false;
@override
bool get isPotentiallyMutatedInScope => false;
@override
bool get isStatic => hasModifier(Modifier.STATIC);
@override
DartType get type => _type ?? _declaredType;
void set type(DartType type) {
if (linkedNode != null) {
return linkedContext.setVariableType(linkedNode, type);
}
_type = _checkElementOfType(type);
}
/// Return the error reported during type inference for this variable, or
/// `null` if this variable is not a subject of type inference, or there was
/// no error.
TopLevelInferenceError get typeInferenceError {
return null;
}
@override
void appendTo(StringBuffer buffer) {
buffer.write(type);
buffer.write(" ");
buffer.write(displayName);
}
@override
DartObject computeConstantValue() => null;
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
_initializer?.accept(visitor);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/inheritance_manager2.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/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/inheritance_manager3.dart'
show InheritanceManagerBase, InheritanceManager3;
import 'package:analyzer/src/dart/element/inheritance_manager3.dart';
import 'package:analyzer/src/generated/type_system.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
/// Description of a failure to find a valid override from superinterfaces.
class Conflict {
/// The name of an instance member for which we failed to find a valid
/// override.
final Name name;
/// The list of candidates for a valid override for a member [name]. It has
/// at least two items, because otherwise the only candidate is always valid.
final List<FunctionType> candidates;
/// The getter that conflicts with the [method], or `null`, if the conflict
/// is inconsistent inheritance.
final FunctionType getter;
/// The method tha conflicts with the [getter], or `null`, if the conflict
/// is inconsistent inheritance.
final FunctionType method;
Conflict(this.name, this.candidates, [this.getter, this.method]);
}
/// Manages knowledge about interface types and their members.
class InheritanceManager2 extends InheritanceManagerBase {
static final _noSuchMethodName = Name(null, 'noSuchMethod');
final TypeSystem _typeSystem;
/// Cached instance interfaces for [InterfaceType].
final Map<InterfaceType, Interface> _interfaces = {};
/// The set of classes that are currently being processed, used to detect
/// self-referencing cycles.
final Set<ClassElement> _processingClasses = new Set<ClassElement>();
InheritanceManager2(this._typeSystem);
@override
InheritanceManager3 get asInheritanceManager3 =>
InheritanceManager3(_typeSystem);
/// Return the most specific signature of the member with the given [name]
/// that the [type] inherits from the mixins, superclasses, or interfaces;
/// or `null` if no member is inherited because the member is not declared
/// at all, or because there is no the most specific signature.
///
/// This is equivalent to `getInheritedMap(type)[name]`.
FunctionType getInherited(InterfaceType type, Name name) {
return getInheritedMap(type)[name];
}
/// Return signatures of all concrete members that the given [type] inherits
/// from the superclasses and mixins.
Map<Name, FunctionType> getInheritedConcreteMap(InterfaceType type) {
var interface = getInterface(type);
return interface._superImplemented.last;
}
/// Return the mapping from names to most specific signatures of members
/// inherited from the super-interfaces (superclasses, mixins, and
/// interfaces). If there is no most specific signature for a name, the
/// corresponding name will not be included.
Map<Name, FunctionType> getInheritedMap(InterfaceType type) {
var interface = getInterface(type);
if (interface._inheritedMap == null) {
interface._inheritedMap = {};
_findMostSpecificFromNamedCandidates(
interface._inheritedMap,
interface._overridden,
);
}
return interface._inheritedMap;
}
/// Return the interface of the given [type]. It might include private
/// members, not necessary accessible in all libraries.
Interface getInterface(InterfaceType type) {
if (type == null) {
return Interface._empty;
}
var result = _interfaces[type];
if (result != null) {
return result;
}
_interfaces[type] = Interface._empty;
var classElement = type.element;
if (!_processingClasses.add(classElement)) {
return Interface._empty;
}
Map<Name, List<FunctionType>> namedCandidates = {};
List<Map<Name, FunctionType>> superImplemented = [];
Map<Name, FunctionType> declared;
Interface superInterface;
Map<Name, FunctionType> implemented;
Map<Name, FunctionType> implementedForMixing;
try {
// If a class declaration has a member declaration, the signature of that
// member declaration becomes the signature in the interface.
declared = _getTypeMembers(type);
for (var interface in type.interfaces) {
var interfaceObj = getInterface(interface);
_addCandidates(namedCandidates, interfaceObj);
}
if (classElement.isMixin) {
var superClassCandidates = <Name, List<FunctionType>>{};
for (var constraint in type.superclassConstraints) {
var interfaceObj = getInterface(constraint);
_addCandidates(superClassCandidates, interfaceObj);
_addCandidates(namedCandidates, interfaceObj);
}
implemented = {};
// `mixin M on S1, S2 {}` can call using `super` any instance member
// from its superclass constraints, whether it is abstract or concrete.
var superClass = <Name, FunctionType>{};
_findMostSpecificFromNamedCandidates(superClass, superClassCandidates);
superImplemented.add(superClass);
} else {
if (type.superclass != null) {
superInterface = getInterface(type.superclass);
_addCandidates(namedCandidates, superInterface);
implemented = superInterface.implemented;
superImplemented.add(implemented);
} else {
implemented = {};
}
implementedForMixing = {};
for (var mixin in type.mixins) {
var interfaceObj = getInterface(mixin);
_addCandidates(namedCandidates, interfaceObj);
implemented = <Name, FunctionType>{}
..addAll(implemented)
..addAll(interfaceObj._implementedForMixing);
superImplemented.add(implemented);
implementedForMixing.addAll(interfaceObj._implementedForMixing);
}
}
} finally {
_processingClasses.remove(classElement);
}
var thisImplemented = <Name, FunctionType>{};
_addImplemented(thisImplemented, type);
if (classElement.isMixin) {
implementedForMixing = thisImplemented;
} else {
implementedForMixing.addAll(thisImplemented);
}
implemented = <Name, FunctionType>{}..addAll(implemented);
_addImplemented(implemented, type);
// If a class declaration does not have a member declaration with a
// particular name, but some super-interfaces do have a member with that
// name, it's a compile-time error if there is no signature among the
// super-interfaces that is a valid override of all the other
// super-interface signatures with the same name. That "most specific"
// signature becomes the signature of the class's interface.
Map<Name, FunctionType> map = new Map.of(declared);
List<Conflict> conflicts = _findMostSpecificFromNamedCandidates(
map,
namedCandidates,
);
var noSuchMethodForwarders = Set<Name>();
if (classElement.isAbstract) {
if (superInterface != null) {
noSuchMethodForwarders = superInterface._noSuchMethodForwarders;
}
} else {
var noSuchMethod = implemented[_noSuchMethodName]?.element;
if (noSuchMethod != null && !_isDeclaredInObject(noSuchMethod)) {
var superForwarders = superInterface?._noSuchMethodForwarders;
for (var name in map.keys) {
if (!implemented.containsKey(name) ||
superForwarders != null && superForwarders.contains(name)) {
implemented[name] = map[name];
noSuchMethodForwarders.add(name);
}
}
}
}
var interface = new Interface._(
map,
declared,
implemented,
noSuchMethodForwarders,
implementedForMixing,
namedCandidates,
superImplemented,
conflicts ?? const [],
);
_interfaces[type] = interface;
return interface;
}
/// Return the member with the given [name].
///
/// If [concrete] is `true`, the the concrete implementation is returned,
/// from the given [type], or its superclass.
///
/// If [forSuper] is `true`, then [concrete] is implied, and only concrete
/// members from the superclass are considered.
///
/// If [forMixinIndex] is specified, only the nominal superclass, and the
/// given number of mixins after it are considered. For example for `1` in
/// `class C extends S with M1, M2, M3`, only `S` and `M1` are considered.
FunctionType getMember(
InterfaceType type,
Name name, {
bool concrete: false,
int forMixinIndex: -1,
bool forSuper: false,
}) {
var interface = getInterface(type);
if (forSuper) {
var superImplemented = interface._superImplemented;
if (forMixinIndex >= 0) {
return superImplemented[forMixinIndex][name];
}
return superImplemented.last[name];
}
if (concrete) {
return interface.implemented[name];
}
return interface.map[name];
}
/// Return all members of mixins, superclasses, and interfaces that a member
/// with the given [name], defined in the [type], would override; or `null`
/// if no members would be overridden.
List<FunctionType> getOverridden(InterfaceType type, Name name) {
var interface = getInterface(type);
return interface._overridden[name];
}
void _addCandidate(Map<Name, List<FunctionType>> namedCandidates, Name name,
FunctionType candidate) {
var candidates = namedCandidates[name];
if (candidates == null) {
candidates = <FunctionType>[];
namedCandidates[name] = candidates;
}
candidates.add(candidate);
}
void _addCandidates(
Map<Name, List<FunctionType>> namedCandidates, Interface interface) {
var map = interface.map;
for (var name in map.keys) {
var candidate = map[name];
_addCandidate(namedCandidates, name, candidate);
}
}
void _addImplemented(
Map<Name, FunctionType> implemented, InterfaceType type) {
var libraryUri = type.element.librarySource.uri;
void addMember(ExecutableElement member) {
if (!member.isAbstract && !member.isStatic) {
var name = new Name(libraryUri, member.name);
implemented[name] = member.type;
}
}
void addMembers(InterfaceType type) {
type.methods.forEach(addMember);
type.accessors.forEach(addMember);
}
addMembers(type);
}
/// Check that all [candidates] for the given [name] have the same kind, all
/// getters, all methods, or all setter. If a conflict found, return the
/// new [Conflict] instance that describes it.
Conflict _checkForGetterMethodConflict(
Name name, List<FunctionType> candidates) {
assert(candidates.length > 1);
bool allGetters = true;
bool allMethods = true;
bool allSetters = true;
for (var candidate in candidates) {
var kind = candidate.element.kind;
if (kind != ElementKind.GETTER) {
allGetters = false;
}
if (kind != ElementKind.METHOD) {
allMethods = false;
}
if (kind != ElementKind.SETTER) {
allSetters = false;
}
}
if (allGetters || allMethods || allSetters) {
return null;
}
FunctionType getterType;
FunctionType methodType;
for (var candidate in candidates) {
var kind = candidate.element.kind;
if (kind == ElementKind.GETTER) {
getterType ??= candidate;
}
if (kind == ElementKind.METHOD) {
methodType ??= candidate;
}
}
return new Conflict(name, candidates, getterType, methodType);
}
/// The given [namedCandidates] maps names to candidates from direct
/// superinterfaces. Find the most specific signature, and put it into the
/// [map], if there is no one yet (from the class itself). If there is no
/// such single most specific signature (i.e. no valid override), then add a
/// new conflict description.
List<Conflict> _findMostSpecificFromNamedCandidates(
Map<Name, FunctionType> map,
Map<Name, List<FunctionType>> namedCandidates) {
List<Conflict> conflicts;
for (var name in namedCandidates.keys) {
if (map.containsKey(name)) {
continue;
}
var candidates = namedCandidates[name];
// If just one candidate, it is always valid.
if (candidates.length == 1) {
map[name] = candidates[0];
continue;
}
// Check for a getter/method conflict.
var conflict = _checkForGetterMethodConflict(name, candidates);
if (conflict != null) {
conflicts ??= <Conflict>[];
conflicts.add(conflict);
}
// Candidates are recorded in forward order, so
// `class X extends S with M1, M2 implements I1, I2 {}` will record
// candidates from [I1, I2, S, M1, M2]. But during method lookup
// candidates should be considered in backward order, i.e. from `M2`,
// then from `M1`, then from `S`.
FunctionType validOverride;
for (var i = candidates.length - 1; i >= 0; i--) {
validOverride = candidates[i];
for (var j = 0; j < candidates.length; j++) {
var candidate = candidates[j];
if (!_typeSystem.isOverrideSubtypeOf(validOverride, candidate)) {
validOverride = null;
break;
}
}
if (validOverride != null) {
break;
}
}
if (validOverride != null) {
map[name] = validOverride;
} else {
conflicts ??= <Conflict>[];
conflicts.add(new Conflict(name, candidates));
}
}
return conflicts;
}
Map<Name, FunctionType> _getTypeMembers(InterfaceType type) {
var declared = <Name, FunctionType>{};
var libraryUri = type.element.librarySource.uri;
var methods = type.methods;
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
if (!method.isStatic) {
var name = new Name(libraryUri, method.name);
declared[name] = method.type;
}
}
var accessors = type.accessors;
for (var i = 0; i < accessors.length; i++) {
var accessor = accessors[i];
if (!accessor.isStatic) {
var name = new Name(libraryUri, accessor.name);
declared[name] = accessor.type;
}
}
return declared;
}
static bool _isDeclaredInObject(ExecutableElement element) {
var enclosing = element.enclosingElement;
return enclosing is ClassElement &&
enclosing.supertype == null &&
!enclosing.isMixin;
}
}
/// The instance interface of an [InterfaceType].
class Interface {
static final _empty = Interface._(
const {},
const {},
const {},
Set<Name>(),
const {},
const {},
const [{}],
const [],
);
/// The map of names to their signature in the interface.
final Map<Name, FunctionType> map;
/// The map of declared names to their signatures.
final Map<Name, FunctionType> declared;
/// The map of names to their concrete implementations.
final Map<Name, FunctionType> implemented;
/// The set of names that are `noSuchMethod` forwarders in [implemented].
final Set<Name> _noSuchMethodForwarders;
/// The map of names to their concrete implementations that can be mixed
/// when this type is used as a mixin.
final Map<Name, FunctionType> _implementedForMixing;
/// The map of names to their signatures from the mixins, superclasses,
/// or interfaces.
final Map<Name, List<FunctionType>> _overridden;
/// Each item of this list maps names to their concrete implementations.
/// The first item of the list is the nominal superclass, next the nominal
/// superclass plus the first mixin, etc. So, for the class like
/// `class C extends S with M1, M2`, we get `[S, S&M1, S&M1&M2]`.
final List<Map<Name, FunctionType>> _superImplemented;
/// The list of conflicts between superinterfaces - the nominal superclass,
/// mixins, and interfaces. Does not include conflicts with the declared
/// members of the class.
final List<Conflict> conflicts;
/// The map of names to the most specific signatures from the mixins,
/// superclasses, or interfaces.
Map<Name, FunctionType> _inheritedMap;
Interface._(
this.map,
this.declared,
this.implemented,
this._noSuchMethodForwarders,
this._implementedForMixing,
this._overridden,
this._superImplemented,
this.conflicts,
);
/// Return `true` if the [name] is implemented in the supertype.
bool isSuperImplemented(Name name) {
return _superImplemented.last.containsKey(name);
}
}
/// A public name, or a private name qualified by a library URI.
class Name {
/// If the name is private, the URI of the defining library.
/// Otherwise, it is `null`.
final Uri libraryUri;
/// The name of this name object.
/// If the name starts with `_`, then the name is private.
/// Names of setters end with `=`.
final String name;
/// Precomputed
final bool isPublic;
/// The cached, pre-computed hash code.
final int hashCode;
factory Name(Uri libraryUri, String name) {
if (name.startsWith('_')) {
var hashCode = JenkinsSmiHash.hash2(libraryUri.hashCode, name.hashCode);
return new Name._internal(libraryUri, name, false, hashCode);
} else {
return new Name._internal(null, name, true, name.hashCode);
}
}
Name._internal(this.libraryUri, this.name, this.isPublic, this.hashCode);
@override
bool operator ==(other) {
return other is Name &&
name == other.name &&
libraryUri == other.libraryUri;
}
bool isAccessibleFor(Uri libraryUri) {
return isPublic || this.libraryUri == libraryUri;
}
@override
String toString() => libraryUri != null ? '$libraryUri::$name' : name;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/wrapped.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/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart' hide Directive;
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/src/dart/resolver/scope.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisContext;
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
/// Implementation of [CompilationUnitElement] that wraps a
/// [CompilationUnitElement] and defers all method calls to it.
///
/// This is intended to be used by the rare clients that must reimplement
/// [CompilationUnitElement], so that they won't be broken if new methods are
/// added.
class WrappedCompilationUnitElement implements CompilationUnitElement {
final CompilationUnitElement wrappedUnit;
WrappedCompilationUnitElement(this.wrappedUnit);
@override
List<PropertyAccessorElement> get accessors => wrappedUnit.accessors;
@override
AnalysisContext get context => wrappedUnit.context;
@override
String get displayName => wrappedUnit.displayName;
@override
String get documentationComment => wrappedUnit.documentationComment;
@override
LibraryElement get enclosingElement => wrappedUnit.enclosingElement;
@override
List<ClassElement> get enums => wrappedUnit.enums;
@override
List<ExtensionElement> get extensions => wrappedUnit.extensions;
@override
List<FunctionElement> get functions => wrappedUnit.functions;
@override
List<FunctionTypeAliasElement> get functionTypeAliases =>
wrappedUnit.functionTypeAliases;
@override
bool get hasAlwaysThrows => wrappedUnit.hasAlwaysThrows;
@override
bool get hasDeprecated => wrappedUnit.hasDeprecated;
@override
bool get hasFactory => wrappedUnit.hasFactory;
@override
bool get hasIsTest => wrappedUnit.hasIsTest;
@override
bool get hasIsTestGroup => wrappedUnit.hasIsTestGroup;
@override
bool get hasJS => wrappedUnit.hasJS;
@override
bool get hasLiteral => wrappedUnit.hasLiteral;
@override
bool get hasLoadLibraryFunction => wrappedUnit.hasLoadLibraryFunction;
@override
bool get hasMustCallSuper => wrappedUnit.hasMustCallSuper;
@override
bool get hasOptionalTypeArgs => wrappedUnit.hasOptionalTypeArgs;
@override
bool get hasOverride => wrappedUnit.hasOverride;
@override
bool get hasProtected => wrappedUnit.hasProtected;
@override
bool get hasRequired => wrappedUnit.hasRequired;
@override
bool get hasSealed => wrappedUnit.hasSealed;
@override
bool get hasVisibleForTemplate => wrappedUnit.hasVisibleForTemplate;
@override
bool get hasVisibleForTesting => wrappedUnit.hasVisibleForTesting;
@override
int get id => wrappedUnit.id;
@override
bool get isAlwaysThrows => hasAlwaysThrows;
@override
bool get isDeprecated => hasDeprecated;
@override
bool get isFactory => hasFactory;
@override
bool get isJS => hasJS;
@override
bool get isOverride => hasOverride;
@override
bool get isPrivate => wrappedUnit.isPrivate;
@override
bool get isProtected => hasProtected;
@override
bool get isPublic => wrappedUnit.isPublic;
@override
bool get isRequired => hasRequired;
@override
bool get isSynthetic => wrappedUnit.isSynthetic;
@override
bool get isVisibleForTesting => hasVisibleForTesting;
@override
ElementKind get kind => wrappedUnit.kind;
@override
LibraryElement get library => wrappedUnit.library;
@override
Source get librarySource => wrappedUnit.librarySource;
@override
LineInfo get lineInfo => wrappedUnit.lineInfo;
@override
ElementLocation get location => wrappedUnit.location;
@override
List<ElementAnnotation> get metadata => wrappedUnit.metadata;
@override
List<ClassElement> get mixins => wrappedUnit.mixins;
@override
String get name => wrappedUnit.name;
@override
int get nameLength => wrappedUnit.nameLength;
@override
int get nameOffset => wrappedUnit.nameOffset;
@override
AnalysisSession get session => wrappedUnit.session;
@override
Source get source => wrappedUnit.source;
@override
List<TopLevelVariableElement> get topLevelVariables =>
wrappedUnit.topLevelVariables;
@override
List<ClassElement> get types => wrappedUnit.types;
@deprecated
@override
CompilationUnit get unit => wrappedUnit.unit;
@override
String get uri => wrappedUnit.uri;
@override
int get uriEnd => wrappedUnit.uriEnd;
@override
int get uriOffset => wrappedUnit.uriOffset;
@override
T accept<T>(ElementVisitor<T> visitor) => wrappedUnit
.accept(visitor); // ignore: deprecated_member_use_from_same_package
@override
String computeDocumentationComment() {
// ignore: deprecated_member_use_from_same_package
return wrappedUnit.computeDocumentationComment();
}
@deprecated
@override
CompilationUnit computeNode() => wrappedUnit.computeNode();
@override
E getAncestor<E extends Element>(Predicate<Element> predicate) =>
wrappedUnit.getAncestor(predicate);
@override
ClassElement getEnum(String name) => wrappedUnit.getEnum(name);
@override
String getExtendedDisplayName(String shortName) =>
wrappedUnit.getExtendedDisplayName(shortName);
@override
ClassElement getType(String className) => wrappedUnit.getType(className);
@override
bool isAccessibleIn(LibraryElement library) =>
wrappedUnit.isAccessibleIn(library);
@override
void visitChildren(ElementVisitor visitor) =>
wrappedUnit.visitChildren(visitor);
}
/// Implementation of [ImportElement] that wraps an [ImportElement] and defers
/// all method calls to it.
///
/// This is intended to be used by the rare clients that must reimplement
/// [ImportElement], so that they won't be broken if new methods are added.
class WrappedImportElement implements ImportElement {
final ImportElement wrappedImport;
WrappedImportElement(this.wrappedImport);
@override
List<NamespaceCombinator> get combinators => wrappedImport.combinators;
@override
AnalysisContext get context => wrappedImport.context;
@override
String get displayName => wrappedImport.displayName;
@override
String get documentationComment => wrappedImport.documentationComment;
@override
LibraryElement get enclosingElement => wrappedImport.enclosingElement;
@override
bool get hasAlwaysThrows => wrappedImport.hasAlwaysThrows;
@override
bool get hasDeprecated => wrappedImport.hasDeprecated;
@override
bool get hasFactory => wrappedImport.hasFactory;
@override
bool get hasIsTest => wrappedImport.hasIsTest;
@override
bool get hasIsTestGroup => wrappedImport.hasIsTestGroup;
@override
bool get hasJS => wrappedImport.hasJS;
@override
bool get hasLiteral => wrappedImport.hasLiteral;
@override
bool get hasMustCallSuper => wrappedImport.hasMustCallSuper;
@override
bool get hasOptionalTypeArgs => wrappedImport.hasOptionalTypeArgs;
@override
bool get hasOverride => wrappedImport.hasOverride;
@override
bool get hasProtected => wrappedImport.hasProtected;
@override
bool get hasRequired => wrappedImport.hasRequired;
@override
bool get hasSealed => wrappedImport.hasSealed;
@override
bool get hasVisibleForTemplate => wrappedImport.hasVisibleForTemplate;
@override
bool get hasVisibleForTesting => wrappedImport.hasVisibleForTesting;
@override
int get id => wrappedImport.id;
@override
LibraryElement get importedLibrary => wrappedImport.importedLibrary;
@override
bool get isAlwaysThrows => hasAlwaysThrows;
@override
bool get isDeferred => wrappedImport.isDeferred;
@override
bool get isDeprecated => hasDeprecated;
@override
bool get isFactory => hasFactory;
@override
bool get isJS => hasJS;
@override
bool get isOverride => hasOverride;
@override
bool get isPrivate => wrappedImport.isPrivate;
@override
bool get isProtected => hasProtected;
@override
bool get isPublic => wrappedImport.isPublic;
@override
bool get isRequired => hasRequired;
@override
bool get isSynthetic => wrappedImport.isSynthetic;
@override
bool get isVisibleForTesting => hasVisibleForTesting;
@override
ElementKind get kind => wrappedImport.kind;
@override
LibraryElement get library => wrappedImport.library;
@override
Source get librarySource => wrappedImport.librarySource;
@override
ElementLocation get location => wrappedImport.location;
@override
List<ElementAnnotation> get metadata => wrappedImport.metadata;
@override
String get name => wrappedImport.name;
@override
int get nameLength => wrappedImport.nameLength;
@override
int get nameOffset => wrappedImport.nameOffset;
@override
Namespace get namespace => wrappedImport.namespace;
@override
PrefixElement get prefix => wrappedImport.prefix;
@override
int get prefixOffset => wrappedImport.prefixOffset;
@override
AnalysisSession get session => wrappedImport.session;
@override
Source get source => wrappedImport.source;
@deprecated
@override
CompilationUnit get unit => wrappedImport.unit;
@override
String get uri => wrappedImport.uri;
@override
int get uriEnd => wrappedImport.uriEnd;
@override
int get uriOffset => wrappedImport.uriOffset;
@override
T accept<T>(ElementVisitor<T> visitor) => wrappedImport.accept(visitor);
@override
String computeDocumentationComment() => wrappedImport
.computeDocumentationComment(); // ignore: deprecated_member_use_from_same_package
@deprecated
@override
AstNode computeNode() => wrappedImport.computeNode();
@override
E getAncestor<E extends Element>(Predicate<Element> predicate) =>
wrappedImport.getAncestor(predicate);
@override
String getExtendedDisplayName(String shortName) =>
wrappedImport.getExtendedDisplayName(shortName);
@override
bool isAccessibleIn(LibraryElement library) =>
wrappedImport.isAccessibleIn(library);
@override
void visitChildren(ElementVisitor visitor) =>
wrappedImport.visitChildren(visitor);
}
/// Implementation of [LibraryElement] that wraps a [LibraryElement] and defers
/// all method calls to it.
///
/// This is intended to be used by the rare clients that must reimplement
/// [LibraryElement], so that they won't be broken if new methods are added.
class WrappedLibraryElement implements LibraryElement {
final LibraryElement wrappedLib;
WrappedLibraryElement(this.wrappedLib);
@override
AnalysisContext get context => wrappedLib.context;
@override
CompilationUnitElement get definingCompilationUnit =>
wrappedLib.definingCompilationUnit;
@override
String get displayName => wrappedLib.displayName;
@override
String get documentationComment => wrappedLib.documentationComment;
@override
Element get enclosingElement => wrappedLib.enclosingElement;
@override
FunctionElement get entryPoint => wrappedLib.entryPoint;
@override
List<LibraryElement> get exportedLibraries => wrappedLib.exportedLibraries;
@override
Namespace get exportNamespace => wrappedLib.exportNamespace;
@override
List<ExportElement> get exports => wrappedLib.exports;
@override
bool get hasAlwaysThrows => wrappedLib.hasAlwaysThrows;
@override
bool get hasDeprecated => wrappedLib.hasDeprecated;
@override
bool get hasExtUri => wrappedLib.hasExtUri;
@override
bool get hasFactory => wrappedLib.hasFactory;
@override
bool get hasIsTest => wrappedLib.hasIsTest;
@override
bool get hasIsTestGroup => wrappedLib.hasIsTestGroup;
@override
bool get hasJS => wrappedLib.hasJS;
@override
bool get hasLiteral => wrappedLib.hasLiteral;
@override
bool get hasLoadLibraryFunction => wrappedLib.hasLoadLibraryFunction;
@override
bool get hasMustCallSuper => wrappedLib.hasMustCallSuper;
@override
bool get hasOptionalTypeArgs => wrappedLib.hasOptionalTypeArgs;
@override
bool get hasOverride => wrappedLib.hasOverride;
@override
bool get hasProtected => wrappedLib.hasProtected;
@override
bool get hasRequired => wrappedLib.hasRequired;
@override
bool get hasSealed => wrappedLib.hasSealed;
@override
bool get hasVisibleForTemplate => wrappedLib.hasVisibleForTemplate;
@override
bool get hasVisibleForTesting => wrappedLib.hasVisibleForTesting;
@override
int get id => wrappedLib.id;
@override
String get identifier => wrappedLib.identifier;
@override
List<LibraryElement> get importedLibraries => wrappedLib.importedLibraries;
@override
List<ImportElement> get imports => wrappedLib.imports;
@override
bool get isAlwaysThrows => hasAlwaysThrows;
@override
bool get isBrowserApplication => wrappedLib.isBrowserApplication;
@override
bool get isDartAsync => wrappedLib.isDartAsync;
@override
bool get isDartCore => wrappedLib.isDartCore;
@override
bool get isDeprecated => hasDeprecated;
@override
bool get isFactory => hasFactory;
@override
bool get isInSdk => wrappedLib.isInSdk;
@override
bool get isJS => hasJS;
@override
bool get isNonNullableByDefault => wrappedLib.isNonNullableByDefault;
@override
bool get isOverride => hasOverride;
@override
bool get isPrivate => wrappedLib.isPrivate;
@override
bool get isProtected => hasProtected;
@override
bool get isPublic => wrappedLib.isPublic;
@override
bool get isRequired => hasRequired;
@override
bool get isSynthetic => wrappedLib.isSynthetic;
@override
bool get isVisibleForTesting => hasVisibleForTesting;
@override
ElementKind get kind => wrappedLib.kind;
@override
LibraryElement get library => wrappedLib.library;
@override
List<LibraryElement> get libraryCycle => wrappedLib.libraryCycle;
@override
Source get librarySource => wrappedLib.librarySource;
@override
FunctionElement get loadLibraryFunction => wrappedLib.loadLibraryFunction;
@override
ElementLocation get location => wrappedLib.location;
@override
List<ElementAnnotation> get metadata => wrappedLib.metadata;
@override
String get name => wrappedLib.name;
@override
int get nameLength => wrappedLib.nameLength;
@override
int get nameOffset => wrappedLib.nameOffset;
@override
List<CompilationUnitElement> get parts => wrappedLib.parts;
@override
List<PrefixElement> get prefixes => wrappedLib.prefixes;
@override
Namespace get publicNamespace => wrappedLib.publicNamespace;
@override
AnalysisSession get session => wrappedLib.session;
@override
Source get source => wrappedLib.source;
@override
Iterable<Element> get topLevelElements => wrappedLib.topLevelElements;
@deprecated
@override
CompilationUnit get unit => wrappedLib.unit;
@override
List<CompilationUnitElement> get units => wrappedLib.units;
@override
T accept<T>(ElementVisitor<T> visitor) => wrappedLib.accept(visitor);
@override
String computeDocumentationComment() => wrappedLib
.computeDocumentationComment(); // ignore: deprecated_member_use_from_same_package
@deprecated
@override
AstNode computeNode() => wrappedLib.computeNode();
@override
E getAncestor<E extends Element>(Predicate<Element> predicate) =>
wrappedLib.getAncestor(predicate);
@override
String getExtendedDisplayName(String shortName) =>
wrappedLib.getExtendedDisplayName(shortName);
@override
List<ImportElement> getImportsWithPrefix(PrefixElement prefix) =>
wrappedLib.getImportsWithPrefix(prefix);
@override
ClassElement getType(String className) => wrappedLib.getType(className);
@override
bool isAccessibleIn(LibraryElement library) =>
wrappedLib.isAccessibleIn(library);
@override
void visitChildren(ElementVisitor visitor) =>
wrappedLib.visitChildren(visitor);
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/type_provider.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:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/constant/value.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/generated/resolver.dart';
/// Provide common functionality shared by the various TypeProvider
/// implementations.
abstract class TypeProviderBase implements TypeProvider {
@override
List<InterfaceType> get nonSubtypableTypes => <InterfaceType>[
boolType,
doubleType,
intType,
nullType,
numType,
stringType
];
@override
bool isObjectGetter(String id) {
PropertyAccessorElement element = objectType.element.getGetter(id);
return (element != null && !element.isStatic);
}
@override
bool isObjectMember(String id) {
return isObjectGetter(id) || isObjectMethod(id);
}
@override
bool isObjectMethod(String id) {
MethodElement element = objectType.element.getMethod(id);
return (element != null && !element.isStatic);
}
}
class TypeProviderImpl extends TypeProviderBase {
final NullabilitySuffix _nullabilitySuffix;
final LibraryElement _coreLibrary;
final LibraryElement _asyncLibrary;
ClassElement _futureElement;
ClassElement _futureOrElement;
ClassElement _iterableElement;
ClassElement _listElement;
ClassElement _mapElement;
ClassElement _setElement;
ClassElement _streamElement;
ClassElement _symbolElement;
InterfaceType _boolType;
InterfaceType _deprecatedType;
InterfaceType _doubleType;
InterfaceType _functionType;
InterfaceType _futureDynamicType;
InterfaceType _futureNullType;
InterfaceType _futureOrNullType;
InterfaceType _futureOrType;
InterfaceType _futureType;
InterfaceType _intType;
InterfaceType _iterableDynamicType;
InterfaceType _iterableObjectType;
InterfaceType _iterableType;
InterfaceType _listType;
InterfaceType _mapType;
InterfaceType _mapObjectObjectType;
DartObjectImpl _nullObject;
InterfaceType _nullType;
InterfaceType _numType;
InterfaceType _objectType;
InterfaceType _setType;
InterfaceType _stackTraceType;
InterfaceType _streamDynamicType;
InterfaceType _streamType;
InterfaceType _stringType;
InterfaceType _symbolType;
InterfaceType _typeType;
/// Initialize a newly created type provider to provide the types defined in
/// the given [coreLibrary] and [asyncLibrary].
TypeProviderImpl(
LibraryElement coreLibrary,
LibraryElement asyncLibrary, {
NullabilitySuffix nullabilitySuffix = NullabilitySuffix.star,
}) : _nullabilitySuffix = nullabilitySuffix,
_coreLibrary = coreLibrary,
_asyncLibrary = asyncLibrary;
@override
InterfaceType get boolType {
_boolType ??= _getType(_coreLibrary, "bool");
return _boolType;
}
@override
DartType get bottomType {
if (_nullabilitySuffix == NullabilitySuffix.none) {
return BottomTypeImpl.instance;
}
return BottomTypeImpl.instanceLegacy;
}
@override
InterfaceType get deprecatedType {
_deprecatedType ??= _getType(_coreLibrary, "Deprecated");
return _deprecatedType;
}
@override
InterfaceType get doubleType {
_doubleType ??= _getType(_coreLibrary, "double");
return _doubleType;
}
@override
DartType get dynamicType => DynamicTypeImpl.instance;
@override
InterfaceType get functionType {
_functionType ??= _getType(_coreLibrary, "Function");
return _functionType;
}
@override
InterfaceType get futureDynamicType {
_futureDynamicType ??= InterfaceTypeImpl.explicit(
futureElement,
[dynamicType],
nullabilitySuffix: _nullabilitySuffix,
);
return _futureDynamicType;
}
ClassElement get futureElement {
return _futureElement ??= _getClassElement(_asyncLibrary, 'Future');
}
@override
InterfaceType get futureNullType {
_futureNullType ??= InterfaceTypeImpl.explicit(
futureElement,
[nullType],
nullabilitySuffix: _nullabilitySuffix,
);
return _futureNullType;
}
ClassElement get futureOrElement {
return _futureOrElement ??= _getClassElement(_asyncLibrary, 'FutureOr');
}
@override
InterfaceType get futureOrNullType {
_futureOrNullType ??= InterfaceTypeImpl.explicit(
futureOrElement,
[nullType],
nullabilitySuffix: _nullabilitySuffix,
);
return _futureOrNullType;
}
@override
InterfaceType get futureOrType {
_futureOrType ??= _getType(_asyncLibrary, "FutureOr");
return _futureOrType;
}
@override
InterfaceType get futureType {
_futureType ??= _getType(_asyncLibrary, "Future");
return _futureType;
}
@override
InterfaceType get intType {
_intType ??= _getType(_coreLibrary, "int");
return _intType;
}
@override
InterfaceType get iterableDynamicType {
_iterableDynamicType ??= InterfaceTypeImpl.explicit(
iterableElement,
[dynamicType],
nullabilitySuffix: _nullabilitySuffix,
);
return _iterableDynamicType;
}
@override
ClassElement get iterableElement {
return _iterableElement ??= _getClassElement(_coreLibrary, 'Iterable');
}
@override
InterfaceType get iterableObjectType {
_iterableObjectType ??= InterfaceTypeImpl.explicit(
iterableElement,
[objectType],
nullabilitySuffix: _nullabilitySuffix,
);
return _iterableObjectType;
}
@override
InterfaceType get iterableType {
_iterableType ??= _getType(_coreLibrary, "Iterable");
return _iterableType;
}
@override
ClassElement get listElement {
return _listElement ??= _getClassElement(_coreLibrary, 'List');
}
@override
InterfaceType get listType {
_listType ??= _getType(_coreLibrary, "List");
return _listType;
}
@override
ClassElement get mapElement {
return _mapElement ??= _getClassElement(_coreLibrary, 'Map');
}
@override
InterfaceType get mapObjectObjectType {
_mapObjectObjectType ??= InterfaceTypeImpl.explicit(
mapElement,
[objectType, objectType],
nullabilitySuffix: _nullabilitySuffix,
);
return _mapObjectObjectType;
}
@override
InterfaceType get mapType {
_mapType ??= _getType(_coreLibrary, "Map");
return _mapType;
}
@override
DartType get neverType => BottomTypeImpl.instance;
@override
DartObjectImpl get nullObject {
if (_nullObject == null) {
_nullObject = new DartObjectImpl(nullType, NullState.NULL_STATE);
}
return _nullObject;
}
@override
InterfaceType get nullType {
_nullType ??= _getType(_coreLibrary, "Null");
return _nullType;
}
@override
InterfaceType get numType {
_numType ??= _getType(_coreLibrary, "num");
return _numType;
}
@override
InterfaceType get objectType {
_objectType ??= _getType(_coreLibrary, "Object");
return _objectType;
}
@override
ClassElement get setElement {
return _setElement ??= _getClassElement(_coreLibrary, 'Set');
}
@override
InterfaceType get setType {
return _setType ??= _getType(_coreLibrary, "Set");
}
@override
InterfaceType get stackTraceType {
_stackTraceType ??= _getType(_coreLibrary, "StackTrace");
return _stackTraceType;
}
@override
InterfaceType get streamDynamicType {
_streamDynamicType ??= InterfaceTypeImpl.explicit(
streamElement,
[dynamicType],
nullabilitySuffix: _nullabilitySuffix,
);
return _streamDynamicType;
}
@override
ClassElement get streamElement {
return _streamElement ??= _getClassElement(_asyncLibrary, 'Stream');
}
@override
InterfaceType get streamType {
_streamType ??= _getType(_asyncLibrary, "Stream");
return _streamType;
}
@override
InterfaceType get stringType {
_stringType ??= _getType(_coreLibrary, "String");
return _stringType;
}
@override
ClassElement get symbolElement {
return _symbolElement ??= _getClassElement(_coreLibrary, 'Symbol');
}
@override
InterfaceType get symbolType {
_symbolType ??= _getType(_coreLibrary, "Symbol");
return _symbolType;
}
@override
InterfaceType get typeType {
_typeType ??= _getType(_coreLibrary, "Type");
return _typeType;
}
@override
VoidType get voidType => VoidTypeImpl.instance;
@override
InterfaceType futureOrType2(DartType valueType) {
return futureOrElement.instantiate(
typeArguments: [valueType],
nullabilitySuffix: _nullabilitySuffix,
);
}
@override
InterfaceType futureType2(DartType valueType) {
return futureElement.instantiate(
typeArguments: [valueType],
nullabilitySuffix: _nullabilitySuffix,
);
}
@override
InterfaceType iterableType2(DartType elementType) {
return iterableElement.instantiate(
typeArguments: [elementType],
nullabilitySuffix: _nullabilitySuffix,
);
}
@override
InterfaceType listType2(DartType elementType) {
return listElement.instantiate(
typeArguments: [elementType],
nullabilitySuffix: _nullabilitySuffix,
);
}
@override
InterfaceType mapType2(DartType keyType, DartType valueType) {
return mapElement.instantiate(
typeArguments: [keyType, valueType],
nullabilitySuffix: _nullabilitySuffix,
);
}
@override
InterfaceType setType2(DartType elementType) {
return setElement.instantiate(
typeArguments: [elementType],
nullabilitySuffix: _nullabilitySuffix,
);
}
@override
InterfaceType streamType2(DartType elementType) {
return streamElement.instantiate(
typeArguments: [elementType],
nullabilitySuffix: _nullabilitySuffix,
);
}
TypeProviderImpl withNullability(NullabilitySuffix nullabilitySuffix) {
if (_nullabilitySuffix == nullabilitySuffix) {
return this;
}
return TypeProviderImpl(_coreLibrary, _asyncLibrary,
nullabilitySuffix: nullabilitySuffix);
}
/// Return the class with the given [name] from the given [library], or
/// throw a [StateError] if there is no class with the given name.
ClassElement _getClassElement(LibraryElement library, String name) {
var element = library.getType(name);
if (element == null) {
throw StateError('No definition of type $name');
}
return element;
}
/// Return the type with the given [name] from the given [library], or
/// throw a [StateError] if there is no class with the given name.
InterfaceType _getType(LibraryElement library, String name) {
var element = _getClassElement(library, name);
var typeArguments = const <DartType>[];
var typeParameters = element.typeParameters;
if (typeParameters.isNotEmpty) {
typeArguments = typeParameters.map((e) {
return TypeParameterTypeImpl(
e,
nullabilitySuffix: _nullabilitySuffix,
);
}).toList(growable: false);
}
return InterfaceTypeImpl.explicit(
element,
typeArguments,
nullabilitySuffix: _nullabilitySuffix,
);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/type_visitor.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:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/generated/type_system.dart';
import 'package:analyzer/src/summary2/function_type_builder.dart';
import 'package:analyzer/src/summary2/named_type_builder.dart';
class DartTypeVisitor<R> {
const DartTypeVisitor();
R defaultDartType(DartType type) => null;
R visitBottomType(BottomTypeImpl type) => defaultDartType(type);
R visitDynamicType(DynamicTypeImpl type) => defaultDartType(type);
R visitFunctionType(FunctionType type) => defaultDartType(type);
R visitFunctionTypeBuilder(FunctionTypeBuilder type) => defaultDartType(type);
R visitInterfaceType(InterfaceType type) => defaultDartType(type);
R visitNamedTypeBuilder(NamedTypeBuilder type) => defaultDartType(type);
R visitTypeParameterType(TypeParameterType type) => defaultDartType(type);
R visitUnknownInferredType(UnknownInferredType type) => defaultDartType(type);
R visitVoidType(VoidType type) => defaultDartType(type);
static R visit<R>(DartType type, DartTypeVisitor<R> visitor) {
if (type is BottomTypeImpl) {
return visitor.visitBottomType(type);
}
if (type is DynamicTypeImpl) {
return visitor.visitDynamicType(type);
}
if (type is FunctionType) {
return visitor.visitFunctionType(type);
}
if (type is FunctionTypeBuilder) {
return visitor.visitFunctionTypeBuilder(type);
}
if (type is InterfaceType) {
return visitor.visitInterfaceType(type);
}
if (type is NamedTypeBuilder) {
return visitor.visitNamedTypeBuilder(type);
}
if (type is TypeParameterType) {
return visitor.visitTypeParameterType(type);
}
if (type is UnknownInferredType) {
return visitor.visitUnknownInferredType(type);
}
if (type is VoidType) {
return visitor.visitVoidType(type);
}
throw UnimplementedError('(${type.runtimeType}) $type');
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/inheritance_manager3.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:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/generated/type_system.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
/// Description of a failure to find a valid override from superinterfaces.
class Conflict {
/// The name of an instance member for which we failed to find a valid
/// override.
final Name name;
/// The list of candidates for a valid override for a member [name]. It has
/// at least two items, because otherwise the only candidate is always valid.
final List<ExecutableElement> candidates;
/// The getter that conflicts with the [method], or `null`, if the conflict
/// is inconsistent inheritance.
final ExecutableElement getter;
/// The method tha conflicts with the [getter], or `null`, if the conflict
/// is inconsistent inheritance.
final ExecutableElement method;
Conflict(this.name, this.candidates, [this.getter, this.method]);
}
/// Manages knowledge about interface types and their members.
class InheritanceManager3 extends InheritanceManagerBase {
static final _noSuchMethodName = Name(null, 'noSuchMethod');
final TypeSystem _typeSystem;
/// Cached instance interfaces for [InterfaceType].
final Map<InterfaceType, Interface> _interfaces = {};
/// The set of classes that are currently being processed, used to detect
/// self-referencing cycles.
final Set<ClassElement> _processingClasses = new Set<ClassElement>();
InheritanceManager3(this._typeSystem);
@override
InheritanceManager3 get asInheritanceManager3 => this;
/// Return the most specific signature of the member with the given [name]
/// that the [type] inherits from the mixins, superclasses, or interfaces;
/// or `null` if no member is inherited because the member is not declared
/// at all, or because there is no the most specific signature.
///
/// This is equivalent to `getInheritedMap(type)[name]`.
ExecutableElement getInherited(InterfaceType type, Name name) {
return getInheritedMap(type)[name];
}
/// Return signatures of all concrete members that the given [type] inherits
/// from the superclasses and mixins.
Map<Name, ExecutableElement> getInheritedConcreteMap(InterfaceType type) {
var interface = getInterface(type);
return interface._superImplemented.last;
}
/// Return the mapping from names to most specific signatures of members
/// inherited from the super-interfaces (superclasses, mixins, and
/// interfaces). If there is no most specific signature for a name, the
/// corresponding name will not be included.
Map<Name, ExecutableElement> getInheritedMap(InterfaceType type) {
var interface = getInterface(type);
if (interface._inheritedMap == null) {
interface._inheritedMap = {};
_findMostSpecificFromNamedCandidates(
interface._inheritedMap,
interface._overridden,
);
}
return interface._inheritedMap;
}
/// Return the interface of the given [type]. It might include private
/// members, not necessary accessible in all libraries.
Interface getInterface(InterfaceType type) {
if (type == null) {
return Interface._empty;
}
var result = _interfaces[type];
if (result != null) {
return result;
}
_interfaces[type] = Interface._empty;
var classElement = type.element;
if (!_processingClasses.add(classElement)) {
return Interface._empty;
}
Map<Name, List<ExecutableElement>> namedCandidates = {};
List<Map<Name, ExecutableElement>> superImplemented = [];
Map<Name, ExecutableElement> declared;
Interface superInterface;
Map<Name, ExecutableElement> implemented;
Map<Name, ExecutableElement> implementedForMixing;
try {
// If a class declaration has a member declaration, the signature of that
// member declaration becomes the signature in the interface.
declared = _getTypeMembers(type);
for (var interface in type.interfaces) {
var interfaceObj = getInterface(interface);
_addCandidates(namedCandidates, interfaceObj);
}
if (classElement.isMixin) {
var superClassCandidates = <Name, List<ExecutableElement>>{};
for (var constraint in type.superclassConstraints) {
var interfaceObj = getInterface(constraint);
_addCandidates(superClassCandidates, interfaceObj);
_addCandidates(namedCandidates, interfaceObj);
}
implemented = {};
// `mixin M on S1, S2 {}` can call using `super` any instance member
// from its superclass constraints, whether it is abstract or concrete.
var superClass = <Name, ExecutableElement>{};
_findMostSpecificFromNamedCandidates(superClass, superClassCandidates);
superImplemented.add(superClass);
} else {
if (type.superclass != null) {
superInterface = getInterface(type.superclass);
_addCandidates(namedCandidates, superInterface);
implemented = superInterface.implemented;
superImplemented.add(implemented);
} else {
implemented = {};
}
implementedForMixing = {};
for (var mixin in type.mixins) {
var interfaceObj = getInterface(mixin);
_addCandidates(namedCandidates, interfaceObj);
implemented = <Name, ExecutableElement>{}
..addAll(implemented)
..addAll(interfaceObj._implementedForMixing);
superImplemented.add(implemented);
implementedForMixing.addAll(interfaceObj._implementedForMixing);
}
}
} finally {
_processingClasses.remove(classElement);
}
var thisImplemented = <Name, ExecutableElement>{};
_addImplemented(thisImplemented, type);
if (classElement.isMixin) {
implementedForMixing = thisImplemented;
} else {
implementedForMixing.addAll(thisImplemented);
}
implemented = <Name, ExecutableElement>{}..addAll(implemented);
_addImplemented(implemented, type);
// If a class declaration does not have a member declaration with a
// particular name, but some super-interfaces do have a member with that
// name, it's a compile-time error if there is no signature among the
// super-interfaces that is a valid override of all the other
// super-interface signatures with the same name. That "most specific"
// signature becomes the signature of the class's interface.
Map<Name, ExecutableElement> map = new Map.of(declared);
List<Conflict> conflicts = _findMostSpecificFromNamedCandidates(
map,
namedCandidates,
);
var noSuchMethodForwarders = Set<Name>();
if (classElement.isAbstract) {
if (superInterface != null) {
noSuchMethodForwarders = superInterface._noSuchMethodForwarders;
}
} else {
var noSuchMethod = implemented[_noSuchMethodName];
if (noSuchMethod != null && !_isDeclaredInObject(noSuchMethod)) {
var superForwarders = superInterface?._noSuchMethodForwarders;
for (var name in map.keys) {
if (!implemented.containsKey(name) ||
superForwarders != null && superForwarders.contains(name)) {
implemented[name] = map[name];
noSuchMethodForwarders.add(name);
}
}
}
}
var interface = new Interface._(
map,
declared,
implemented,
noSuchMethodForwarders,
implementedForMixing,
namedCandidates,
superImplemented,
conflicts ?? const [],
);
_interfaces[type] = interface;
return interface;
}
/// Return the member with the given [name].
///
/// If [concrete] is `true`, the the concrete implementation is returned,
/// from the given [type], or its superclass.
///
/// If [forSuper] is `true`, then [concrete] is implied, and only concrete
/// members from the superclass are considered.
///
/// If [forMixinIndex] is specified, only the nominal superclass, and the
/// given number of mixins after it are considered. For example for `1` in
/// `class C extends S with M1, M2, M3`, only `S` and `M1` are considered.
ExecutableElement getMember(
InterfaceType type,
Name name, {
bool concrete: false,
int forMixinIndex: -1,
bool forSuper: false,
}) {
var interface = getInterface(type);
if (forSuper) {
var superImplemented = interface._superImplemented;
if (forMixinIndex >= 0) {
return superImplemented[forMixinIndex][name];
}
return superImplemented.last[name];
}
if (concrete) {
return interface.implemented[name];
}
return interface.map[name];
}
/// Return all members of mixins, superclasses, and interfaces that a member
/// with the given [name], defined in the [type], would override; or `null`
/// if no members would be overridden.
List<ExecutableElement> getOverridden(InterfaceType type, Name name) {
var interface = getInterface(type);
return interface._overridden[name];
}
void _addCandidate(Map<Name, List<ExecutableElement>> namedCandidates,
Name name, ExecutableElement candidate) {
var candidates = namedCandidates[name];
if (candidates == null) {
candidates = <ExecutableElement>[];
namedCandidates[name] = candidates;
}
candidates.add(candidate);
}
void _addCandidates(
Map<Name, List<ExecutableElement>> namedCandidates, Interface interface) {
var map = interface.map;
for (var name in map.keys) {
var candidate = map[name];
_addCandidate(namedCandidates, name, candidate);
}
}
void _addImplemented(
Map<Name, ExecutableElement> implemented, InterfaceType type) {
var libraryUri = type.element.librarySource.uri;
void addMember(ExecutableElement member) {
if (!member.isAbstract && !member.isStatic) {
var name = new Name(libraryUri, member.name);
implemented[name] = member;
}
}
void addMembers(InterfaceType type) {
type.methods.forEach(addMember);
type.accessors.forEach(addMember);
}
addMembers(type);
}
/// Check that all [candidates] for the given [name] have the same kind, all
/// getters, all methods, or all setter. If a conflict found, return the
/// new [Conflict] instance that describes it.
Conflict _checkForGetterMethodConflict(
Name name, List<ExecutableElement> candidates) {
assert(candidates.length > 1);
bool allGetters = true;
bool allMethods = true;
bool allSetters = true;
for (var candidate in candidates) {
var kind = candidate.kind;
if (kind != ElementKind.GETTER) {
allGetters = false;
}
if (kind != ElementKind.METHOD) {
allMethods = false;
}
if (kind != ElementKind.SETTER) {
allSetters = false;
}
}
if (allGetters || allMethods || allSetters) {
return null;
}
ExecutableElement getter;
ExecutableElement method;
for (var candidate in candidates) {
var kind = candidate.kind;
if (kind == ElementKind.GETTER) {
getter ??= candidate;
}
if (kind == ElementKind.METHOD) {
method ??= candidate;
}
}
return new Conflict(name, candidates, getter, method);
}
/// The given [namedCandidates] maps names to candidates from direct
/// superinterfaces. Find the most specific signature, and put it into the
/// [map], if there is no one yet (from the class itself). If there is no
/// such single most specific signature (i.e. no valid override), then add a
/// new conflict description.
List<Conflict> _findMostSpecificFromNamedCandidates(
Map<Name, ExecutableElement> map,
Map<Name, List<ExecutableElement>> namedCandidates) {
List<Conflict> conflicts;
for (var name in namedCandidates.keys) {
if (map.containsKey(name)) {
continue;
}
var candidates = namedCandidates[name];
// If just one candidate, it is always valid.
if (candidates.length == 1) {
map[name] = candidates[0];
continue;
}
// Check for a getter/method conflict.
var conflict = _checkForGetterMethodConflict(name, candidates);
if (conflict != null) {
conflicts ??= <Conflict>[];
conflicts.add(conflict);
}
// Candidates are recorded in forward order, so
// `class X extends S with M1, M2 implements I1, I2 {}` will record
// candidates from [I1, I2, S, M1, M2]. But during method lookup
// candidates should be considered in backward order, i.e. from `M2`,
// then from `M1`, then from `S`.
ExecutableElement validOverride;
for (var i = candidates.length - 1; i >= 0; i--) {
validOverride = candidates[i];
for (var j = 0; j < candidates.length; j++) {
var candidate = candidates[j];
if (!_typeSystem.isOverrideSubtypeOf(
validOverride.type, candidate.type)) {
validOverride = null;
break;
}
}
if (validOverride != null) {
break;
}
}
if (validOverride != null) {
map[name] = validOverride;
} else {
conflicts ??= <Conflict>[];
conflicts.add(new Conflict(name, candidates));
}
}
return conflicts;
}
Map<Name, ExecutableElement> _getTypeMembers(InterfaceType type) {
var declared = <Name, ExecutableElement>{};
var libraryUri = type.element.librarySource.uri;
var methods = type.methods;
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
if (!method.isStatic) {
var name = new Name(libraryUri, method.name);
declared[name] = method;
}
}
var accessors = type.accessors;
for (var i = 0; i < accessors.length; i++) {
var accessor = accessors[i];
if (!accessor.isStatic) {
var name = new Name(libraryUri, accessor.name);
declared[name] = accessor;
}
}
return declared;
}
static bool _isDeclaredInObject(ExecutableElement element) {
var enclosing = element.enclosingElement;
return enclosing is ClassElement &&
enclosing.supertype == null &&
!enclosing.isMixin;
}
}
/// A temporary bridge between the old and the new versions of inheritance
/// managers. Clients may not reference, extend, implement, or mix-in this
/// class. It will be removed in the next major version of analyser, together
/// with "InheritanceManager2".
abstract class InheritanceManagerBase {
InheritanceManager3 get asInheritanceManager3;
}
/// The instance interface of an [InterfaceType].
class Interface {
static final _empty = Interface._(
const {},
const {},
const {},
Set<Name>(),
const {},
const {},
const [{}],
const [],
);
/// The map of names to their signature in the interface.
final Map<Name, ExecutableElement> map;
/// The map of declared names to their signatures.
final Map<Name, ExecutableElement> declared;
/// The map of names to their concrete implementations.
final Map<Name, ExecutableElement> implemented;
/// The set of names that are `noSuchMethod` forwarders in [implemented].
final Set<Name> _noSuchMethodForwarders;
/// The map of names to their concrete implementations that can be mixed
/// when this type is used as a mixin.
final Map<Name, ExecutableElement> _implementedForMixing;
/// The map of names to their signatures from the mixins, superclasses,
/// or interfaces.
final Map<Name, List<ExecutableElement>> _overridden;
/// Each item of this list maps names to their concrete implementations.
/// The first item of the list is the nominal superclass, next the nominal
/// superclass plus the first mixin, etc. So, for the class like
/// `class C extends S with M1, M2`, we get `[S, S&M1, S&M1&M2]`.
final List<Map<Name, ExecutableElement>> _superImplemented;
/// The list of conflicts between superinterfaces - the nominal superclass,
/// mixins, and interfaces. Does not include conflicts with the declared
/// members of the class.
final List<Conflict> conflicts;
/// The map of names to the most specific signatures from the mixins,
/// superclasses, or interfaces.
Map<Name, ExecutableElement> _inheritedMap;
Interface._(
this.map,
this.declared,
this.implemented,
this._noSuchMethodForwarders,
this._implementedForMixing,
this._overridden,
this._superImplemented,
this.conflicts,
);
/// Return `true` if the [name] is implemented in the supertype.
bool isSuperImplemented(Name name) {
return _superImplemented.last.containsKey(name);
}
}
/// A public name, or a private name qualified by a library URI.
class Name {
/// If the name is private, the URI of the defining library.
/// Otherwise, it is `null`.
final Uri libraryUri;
/// The name of this name object.
/// If the name starts with `_`, then the name is private.
/// Names of setters end with `=`.
final String name;
/// Precomputed
final bool isPublic;
/// The cached, pre-computed hash code.
final int hashCode;
factory Name(Uri libraryUri, String name) {
if (name.startsWith('_')) {
var hashCode = JenkinsSmiHash.hash2(libraryUri.hashCode, name.hashCode);
return new Name._internal(libraryUri, name, false, hashCode);
} else {
return new Name._internal(null, name, true, name.hashCode);
}
}
Name._internal(this.libraryUri, this.name, this.isPublic, this.hashCode);
@override
bool operator ==(other) {
return other is Name &&
name == other.name &&
libraryUri == other.libraryUri;
}
bool isAccessibleFor(Uri libraryUri) {
return isPublic || this.libraryUri == libraryUri;
}
@override
String toString() => libraryUri != null ? '$libraryUri::$name' : name;
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/member.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:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/dart/element/type_algebra.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisContext;
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
import 'package:meta/meta.dart';
/**
* A constructor element defined in a parameterized type where the values of the
* type parameters are known.
*/
class ConstructorMember extends ExecutableMember implements ConstructorElement {
/**
* Initialize a newly created element to represent a constructor, based on
* the [baseElement], and applied [substitution].
*/
ConstructorMember(
ConstructorElement baseElement,
MapSubstitution substitution,
) : super(baseElement, substitution);
@override
ConstructorElement get baseElement => super.baseElement as ConstructorElement;
@override
ClassElement get enclosingElement => baseElement.enclosingElement;
@override
bool get isConst => baseElement.isConst;
@override
bool get isConstantEvaluated => baseElement.isConstantEvaluated;
@override
bool get isDefaultConstructor => baseElement.isDefaultConstructor;
@override
bool get isFactory => baseElement.isFactory;
@override
int get nameEnd => baseElement.nameEnd;
@override
int get periodOffset => baseElement.periodOffset;
@override
ConstructorElement get redirectedConstructor {
var definingType = _substitution.substituteType(enclosingElement.thisType);
return from(baseElement.redirectedConstructor, definingType);
}
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitConstructorElement(this);
@deprecated
@override
ConstructorDeclaration computeNode() => baseElement.computeNode();
@override
String toString() {
ConstructorElement baseElement = this.baseElement;
List<ParameterElement> parameters = this.parameters;
FunctionType type = this.type;
StringBuffer buffer = StringBuffer();
if (type != null) {
buffer.write(type.returnType);
buffer.write(' ');
}
buffer.write(baseElement.enclosingElement.displayName);
String name = displayName;
if (name != null && name.isNotEmpty) {
buffer.write('.');
buffer.write(name);
}
buffer.write('(');
int parameterCount = parameters.length;
for (int i = 0; i < parameterCount; i++) {
if (i > 0) {
buffer.write(', ');
}
buffer.write(parameters[i]);
}
buffer.write(')');
return buffer.toString();
}
/**
* If the given [constructor]'s type is different when any type parameters
* from the defining type's declaration are replaced with the actual type
* arguments from the [definingType], create a constructor member representing
* the given constructor. Return the member that was created, or the original
* constructor if no member was created.
*/
static ConstructorElement from(
ConstructorElement constructor, InterfaceType definingType) {
if (constructor == null || definingType.typeArguments.isEmpty) {
return constructor;
}
FunctionType baseType = constructor.type;
if (baseType == null) {
// TODO(brianwilkerson) We need to understand when this can happen.
return constructor;
}
return ConstructorMember(
constructor,
Substitution.fromInterfaceType(definingType),
);
}
}
/**
* An executable element defined in a parameterized type where the values of the
* type parameters are known.
*/
abstract class ExecutableMember extends Member implements ExecutableElement {
FunctionType _type;
/**
* Initialize a newly created element to represent a callable element (like a
* method or function or property), based on the [baseElement], and applied
* [substitution].
*/
ExecutableMember(
ExecutableElement baseElement,
MapSubstitution substitution,
) : super(baseElement, substitution);
@override
ExecutableElement get baseElement => super.baseElement as ExecutableElement;
@override
bool get hasImplicitReturnType => baseElement.hasImplicitReturnType;
@override
bool get isAbstract => baseElement.isAbstract;
@override
bool get isAsynchronous => baseElement.isAsynchronous;
@override
bool get isExternal => baseElement.isExternal;
@override
bool get isGenerator => baseElement.isGenerator;
@override
bool get isOperator => baseElement.isOperator;
@override
bool get isSimplyBounded => baseElement.isSimplyBounded;
@override
bool get isStatic => baseElement.isStatic;
@override
bool get isSynchronous => baseElement.isSynchronous;
@override
List<ParameterElement> get parameters {
return baseElement.parameters.map((p) {
if (p is FieldFormalParameterElement) {
return FieldFormalParameterMember(p, _substitution);
}
return ParameterMember(p, _substitution);
}).toList();
}
@override
DartType get returnType => type.returnType;
@override
FunctionType get type {
if (_type != null) return _type;
return _type = _substitution.substituteType(baseElement.type);
}
@override
List<TypeParameterElement> get typeParameters {
return TypeParameterMember.from2(
baseElement.typeParameters,
_substitution,
);
}
@override
void visitChildren(ElementVisitor visitor) {
// TODO(brianwilkerson) We need to finish implementing the accessors used
// below so that we can safely invoke them.
super.visitChildren(visitor);
safelyVisitChildren(parameters, visitor);
}
static ExecutableElement from2(
ExecutableElement element,
MapSubstitution substitution,
) {
var combined = substitution;
if (element is ExecutableMember) {
ExecutableMember member = element;
element = member.baseElement;
var map = <TypeParameterElement, DartType>{};
map.addAll(member._substitution.map);
map.addAll(substitution.map);
combined = Substitution.fromMap(map);
}
if (combined.map.isEmpty) {
return element;
}
if (element is ConstructorElement) {
return ConstructorMember(element, combined);
} else if (element is MethodElement) {
return MethodMember(element, combined);
} else if (element is PropertyAccessorElement) {
return PropertyAccessorMember(element, combined);
} else {
throw UnimplementedError('(${element.runtimeType}) $element');
}
}
}
/**
* A parameter element defined in a parameterized type where the values of the
* type parameters are known.
*/
class FieldFormalParameterMember extends ParameterMember
implements FieldFormalParameterElement {
/**
* Initialize a newly created element to represent a field formal parameter,
* based on the [baseElement], with applied [substitution].
*/
FieldFormalParameterMember(
FieldFormalParameterElement baseElement,
MapSubstitution substitution,
) : super(baseElement, substitution);
@override
FieldElement get field {
var field = (baseElement as FieldFormalParameterElement).field;
if (field == null) {
return null;
}
return FieldMember(field, _substitution);
}
@override
bool get isCovariant => baseElement.isCovariant;
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitFieldFormalParameterElement(this);
}
/**
* A field element defined in a parameterized type where the values of the type
* parameters are known.
*/
class FieldMember extends VariableMember implements FieldElement {
/**
* Initialize a newly created element to represent a field, based on the
* [baseElement], with applied [substitution].
*/
FieldMember(
FieldElement baseElement,
MapSubstitution substitution,
) : super(baseElement, substitution);
@override
FieldElement get baseElement => super.baseElement as FieldElement;
@override
Element get enclosingElement => baseElement.enclosingElement;
@override
PropertyAccessorElement get getter {
var baseGetter = baseElement.getter;
if (baseGetter == null) {
return null;
}
return PropertyAccessorMember(baseGetter, _substitution);
}
@override
bool get isCovariant => baseElement.isCovariant;
@override
bool get isEnumConstant => baseElement.isEnumConstant;
@deprecated
@override
bool get isVirtual => baseElement.isVirtual;
@deprecated
@override
DartType get propagatedType => null;
@override
PropertyAccessorElement get setter {
var baseSetter = baseElement.setter;
if (baseSetter == null) {
return null;
}
return PropertyAccessorMember(baseSetter, _substitution);
}
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitFieldElement(this);
@deprecated
@override
VariableDeclaration computeNode() => baseElement.computeNode();
@override
String toString() => '$type $displayName';
/**
* If the given [field]'s type is different when any type parameters from the
* defining type's declaration are replaced with the actual type arguments
* from the [definingType], create a field member representing the given
* field. Return the member that was created, or the base field if no member
* was created.
*/
static FieldElement from(FieldElement field, InterfaceType definingType) {
if (field == null || definingType.typeArguments.isEmpty) {
return field;
}
return FieldMember(
field,
Substitution.fromInterfaceType(definingType),
);
}
static FieldElement from2(
FieldElement element,
MapSubstitution substitution,
) {
if (substitution.map.isEmpty) {
return element;
}
return FieldMember(element, substitution);
}
}
/**
* An element defined in a parameterized type where the values of the type
* parameters are known.
*/
abstract class Member implements Element {
/**
* The element on which the parameterized element was created.
*/
final Element _baseElement;
/**
* The substitution for type parameters referenced in the base element.
*/
final MapSubstitution _substitution;
/**
* Initialize a newly created element to represent a member, based on the
* [baseElement], and applied [_substitution].
*/
Member(this._baseElement, this._substitution);
/**
* Return the element on which the parameterized element was created.
*/
Element get baseElement => _baseElement;
@override
AnalysisContext get context => _baseElement.context;
@override
String get displayName => _baseElement.displayName;
@override
String get documentationComment => _baseElement.documentationComment;
@override
bool get hasAlwaysThrows => _baseElement.hasAlwaysThrows;
@override
bool get hasDeprecated => _baseElement.hasDeprecated;
@override
bool get hasFactory => _baseElement.hasFactory;
@override
bool get hasIsTest => _baseElement.hasIsTest;
@override
bool get hasIsTestGroup => _baseElement.hasIsTestGroup;
@override
bool get hasJS => _baseElement.hasJS;
@override
bool get hasLiteral => _baseElement.hasLiteral;
@override
bool get hasMustCallSuper => _baseElement.hasMustCallSuper;
@override
bool get hasOptionalTypeArgs => _baseElement.hasOptionalTypeArgs;
@override
bool get hasOverride => _baseElement.hasOverride;
@override
bool get hasProtected => _baseElement.hasProtected;
@override
bool get hasRequired => _baseElement.hasRequired;
@override
bool get hasSealed => _baseElement.hasSealed;
@override
bool get hasVisibleForTemplate => _baseElement.hasVisibleForTemplate;
@override
bool get hasVisibleForTesting => _baseElement.hasVisibleForTesting;
@override
int get id => _baseElement.id;
@override
bool get isAlwaysThrows => _baseElement.hasAlwaysThrows;
@override
bool get isDeprecated => _baseElement.hasDeprecated;
@override
bool get isFactory => _baseElement.hasFactory;
@override
bool get isJS => _baseElement.hasJS;
@override
bool get isOverride => _baseElement.hasOverride;
@override
bool get isPrivate => _baseElement.isPrivate;
@override
bool get isProtected => _baseElement.hasProtected;
@override
bool get isPublic => _baseElement.isPublic;
@override
bool get isRequired => _baseElement.hasRequired;
@override
bool get isSynthetic => _baseElement.isSynthetic;
@override
bool get isVisibleForTesting => _baseElement.hasVisibleForTesting;
@override
ElementKind get kind => _baseElement.kind;
@override
LibraryElement get library => _baseElement.library;
@override
Source get librarySource => _baseElement.librarySource;
@override
ElementLocation get location => _baseElement.location;
@override
List<ElementAnnotation> get metadata => _baseElement.metadata;
@override
String get name => _baseElement.name;
@override
int get nameLength => _baseElement.nameLength;
@override
int get nameOffset => _baseElement.nameOffset;
@override
AnalysisSession get session => _baseElement.session;
@override
Source get source => _baseElement.source;
/**
* The substitution for type parameters referenced in the base element.
*/
MapSubstitution get substitution => _substitution;
@deprecated
@override
CompilationUnit get unit => _baseElement.unit;
@override
String computeDocumentationComment() => documentationComment;
@deprecated
@override
AstNode computeNode() => _baseElement.computeNode();
@override
E getAncestor<E extends Element>(Predicate<Element> predicate) =>
baseElement.getAncestor(predicate);
@override
String getExtendedDisplayName(String shortName) =>
_baseElement.getExtendedDisplayName(shortName);
@override
bool isAccessibleIn(LibraryElement library) =>
_baseElement.isAccessibleIn(library);
/**
* Use the given [visitor] to visit all of the [children].
*/
void safelyVisitChildren(List<Element> children, ElementVisitor visitor) {
// TODO(brianwilkerson) Make this private
if (children != null) {
for (Element child in children) {
child.accept(visitor);
}
}
}
@override
void visitChildren(ElementVisitor visitor) {
// There are no children to visit
}
}
/**
* A method element defined in a parameterized type where the values of the type
* parameters are known.
*/
class MethodMember extends ExecutableMember implements MethodElement {
/**
* Initialize a newly created element to represent a method, based on the
* [baseElement], with applied [substitution].
*/
MethodMember(
MethodElement baseElement,
MapSubstitution substitution,
) : super(baseElement, substitution);
@override
MethodElement get baseElement => super.baseElement as MethodElement;
@override
Element get enclosingElement => baseElement.enclosingElement;
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitMethodElement(this);
@deprecated
@override
MethodDeclaration computeNode() => baseElement.computeNode();
@override
String toString() {
MethodElement baseElement = this.baseElement;
List<ParameterElement> parameters = this.parameters;
FunctionType type = this.type;
StringBuffer buffer = StringBuffer();
if (type != null) {
buffer.write(type.returnType);
buffer.write(' ');
}
buffer.write(baseElement.enclosingElement.displayName);
buffer.write('.');
buffer.write(baseElement.displayName);
int typeParameterCount = typeParameters.length;
if (typeParameterCount > 0) {
buffer.write('<');
for (int i = 0; i < typeParameterCount; i++) {
if (i > 0) {
buffer.write(', ');
}
// TODO(scheglov) consider always using TypeParameterMember
var typeParameter = typeParameters[i];
if (typeParameter is TypeParameterElementImpl) {
typeParameter.appendTo(buffer);
} else
(typeParameter as TypeParameterMember).appendTo(buffer);
}
buffer.write('>');
}
buffer.write('(');
String closing;
ParameterKind kind = ParameterKind.REQUIRED;
int parameterCount = parameters.length;
for (int i = 0; i < parameterCount; i++) {
if (i > 0) {
buffer.write(', ');
}
ParameterElement parameter = parameters[i];
// ignore: deprecated_member_use_from_same_package
ParameterKind parameterKind = parameter.parameterKind;
if (parameterKind != kind) {
if (closing != null) {
buffer.write(closing);
}
if (parameter.isOptionalPositional) {
buffer.write('[');
closing = ']';
} else if (parameter.isNamed) {
buffer.write('{');
closing = '}';
} else {
closing = null;
}
}
kind = parameterKind;
parameter.appendToWithoutDelimiters(buffer);
}
if (closing != null) {
buffer.write(closing);
}
buffer.write(')');
return buffer.toString();
}
/**
* If the given [method]'s type is different when any type parameters from the
* defining type's declaration are replaced with the actual type arguments
* from the [definingType], create a method member representing the given
* method. Return the member that was created, or the base method if no member
* was created.
*/
static MethodElement from(MethodElement method, InterfaceType definingType) {
if (method == null || definingType.typeArguments.isEmpty) {
return method;
}
return MethodMember(
method,
Substitution.fromInterfaceType(definingType),
);
}
static MethodElement from2(
MethodElement element,
MapSubstitution substitution,
) {
if (substitution.map.isEmpty) {
return element;
}
return MethodMember(element, substitution);
}
}
/**
* A parameter element defined in a parameterized type where the values of the
* type parameters are known.
*/
class ParameterMember extends VariableMember
with ParameterElementMixin
implements ParameterElement {
/**
* Initialize a newly created element to represent a parameter, based on the
* [baseElement], with applied [substitution]. If [type] is passed it will
* represent the already substituted type.
*/
ParameterMember(
ParameterElement baseElement,
MapSubstitution substitution, [
DartType type,
]) : super._(baseElement, substitution, type);
@override
ParameterElement get baseElement => super.baseElement as ParameterElement;
@override
String get defaultValueCode => baseElement.defaultValueCode;
@override
Element get enclosingElement => baseElement.enclosingElement;
@override
int get hashCode => baseElement.hashCode;
@override
bool get isCovariant => baseElement.isCovariant;
@override
bool get isInitializingFormal => baseElement.isInitializingFormal;
@deprecated
@override
ParameterKind get parameterKind => baseElement.parameterKind;
@override
List<ParameterElement> get parameters {
DartType type = this.type;
if (type is FunctionType) {
return type.parameters;
}
return const <ParameterElement>[];
}
@override
List<TypeParameterElement> get typeParameters {
return TypeParameterMember.from2(
baseElement.typeParameters,
_substitution,
);
}
@override
SourceRange get visibleRange => baseElement.visibleRange;
@override
T accept<T>(ElementVisitor<T> visitor) => visitor.visitParameterElement(this);
@deprecated
@override
FormalParameter computeNode() => baseElement.computeNode();
@override
E getAncestor<E extends Element>(Predicate<Element> predicate) {
Element element = baseElement.getAncestor(predicate);
if (element is ExecutableElement) {
return ExecutableMember.from2(element, _substitution) as E;
}
return element as E;
}
@override
String toString() {
ParameterElement baseElement = this.baseElement;
String left = "";
String right = "";
while (true) {
if (baseElement.isNamed) {
left = "{";
right = "}";
} else if (baseElement.isOptionalPositional) {
left = "[";
right = "]";
}
break;
}
return '$left$type ${baseElement.displayName}$right';
}
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
safelyVisitChildren(parameters, visitor);
}
}
/**
* A property accessor element defined in a parameterized type where the values
* of the type parameters are known.
*/
class PropertyAccessorMember extends ExecutableMember
implements PropertyAccessorElement {
/**
* Initialize a newly created element to represent a property, based on the
* [baseElement], with applied [substitution].
*/
PropertyAccessorMember(
PropertyAccessorElement baseElement,
MapSubstitution substitution,
) : super(baseElement, substitution);
@override
PropertyAccessorElement get baseElement =>
super.baseElement as PropertyAccessorElement;
@override
PropertyAccessorElement get correspondingGetter {
return PropertyAccessorMember(
baseElement.correspondingGetter,
_substitution,
);
}
@override
PropertyAccessorElement get correspondingSetter {
return PropertyAccessorMember(
baseElement.correspondingSetter,
_substitution,
);
}
@override
Element get enclosingElement => baseElement.enclosingElement;
@override
bool get isGetter => baseElement.isGetter;
@override
bool get isSetter => baseElement.isSetter;
@override
PropertyInducingElement get variable {
PropertyInducingElement variable = baseElement.variable;
if (variable is FieldElement) {
return FieldMember(variable, _substitution);
}
return variable;
}
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitPropertyAccessorElement(this);
@override
String toString() {
PropertyAccessorElement baseElement = this.baseElement;
List<ParameterElement> parameters = this.parameters;
FunctionType type = this.type;
StringBuffer builder = StringBuffer();
if (type != null) {
builder.write(type.returnType);
builder.write(' ');
}
if (isGetter) {
builder.write('get ');
} else {
builder.write('set ');
}
builder.write(baseElement.enclosingElement.displayName);
builder.write('.');
builder.write(baseElement.displayName);
builder.write('(');
int parameterCount = parameters.length;
for (int i = 0; i < parameterCount; i++) {
if (i > 0) {
builder.write(', ');
}
builder.write(parameters[i]);
}
builder.write(')');
return builder.toString();
}
/**
* If the given [accessor]'s type is different when any type parameters from
* the defining type's declaration are replaced with the actual type
* arguments from the [definingType], create an accessor member representing
* the given accessor. Return the member that was created, or the base
* accessor if no member was created.
*/
static PropertyAccessorElement from(
PropertyAccessorElement accessor, InterfaceType definingType) {
if (accessor == null || definingType.typeArguments.isEmpty) {
return accessor;
}
return PropertyAccessorMember(
accessor,
Substitution.fromInterfaceType(definingType),
);
}
}
/**
* A type parameter defined inside of another parameterized type, where the
* values of the enclosing type parameters are known.
*
* For example:
*
* class C<T> {
* S m<S extends T>(S s);
* }
*
* If we have `C<num>.m` and we ask for the type parameter "S", we should get
* `<S extends num>` instead of `<S extends T>`. This is how the parameter
* and return types work, see: [FunctionType.parameters],
* [FunctionType.returnType], and [ParameterMember].
*/
class TypeParameterMember extends Member implements TypeParameterElement {
DartType _bound;
DartType _type;
TypeParameterMember(TypeParameterElement baseElement,
MapSubstitution substitution, this._bound)
: super(baseElement, substitution) {
_type = TypeParameterTypeImpl(this);
}
@override
TypeParameterElement get baseElement =>
super.baseElement as TypeParameterElement;
@override
DartType get bound => _bound;
@override
Element get enclosingElement => baseElement.enclosingElement;
@override
int get hashCode => baseElement.hashCode;
@override
TypeParameterType get type => _type;
@override
bool operator ==(Object other) =>
other is TypeParameterMember && baseElement == other.baseElement;
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitTypeParameterElement(this);
void appendTo(StringBuffer buffer) {
buffer.write(displayName);
if (bound != null) {
buffer.write(" extends ");
buffer.write(bound);
}
}
@override
TypeParameterType instantiate({
@required NullabilitySuffix nullabilitySuffix,
}) {
return TypeParameterTypeImpl(this, nullabilitySuffix: nullabilitySuffix);
}
@override
String toString() {
var buffer = StringBuffer();
appendTo(buffer);
return buffer.toString();
}
/**
* If the given [parameter]'s type is different when any type parameters from
* the defining type's declaration are replaced with the actual type
* arguments from the [definingType], create a parameter member representing
* the given parameter. Return the member that was created, or the base
* parameter if no member was created.
*/
static List<TypeParameterElement> from(
List<TypeParameterElement> formals, FunctionType definingType) {
var substitution = Substitution.fromPairs(
definingType.typeParameters,
definingType.typeArguments,
);
return from2(formals, substitution);
}
static List<TypeParameterElement> from2(
List<TypeParameterElement> elements,
MapSubstitution substitution,
) {
if (substitution.map.isEmpty) {
return elements;
}
// Create type formals with specialized bounds.
// For example `<U extends T>` where T comes from an outer scope.
var newElements = List<TypeParameterElement>(elements.length);
var newTypes = List<TypeParameterType>(elements.length);
for (int i = 0; i < newElements.length; i++) {
var element = elements[i];
var bound = element?.bound;
if (bound != null) {
bound = substitution.substituteType(bound);
element = TypeParameterMember(element, substitution, bound);
}
newElements[i] = element;
newTypes[i] = newElements[i].instantiate(
nullabilitySuffix: NullabilitySuffix.none,
);
}
// Recursive bounds are allowed too, so make sure these are updated
// to refer to any new TypeParameterMember we just made, rather than
// the original type parameter
var substitution2 = Substitution.fromPairs(elements, newTypes);
for (var newElement in newElements) {
if (newElement is TypeParameterMember) {
// TODO(jmesserly): this is required so substituting for the
// type formal will work. Investigate if there's a better solution.
newElement._bound = substitution2.substituteType(newElement.bound);
}
}
return newElements;
}
}
/**
* A variable element defined in a parameterized type where the values of the
* type parameters are known.
*/
abstract class VariableMember extends Member implements VariableElement {
DartType _type;
/**
* Initialize a newly created element to represent a variable, based on the
* [baseElement], with applied [substitution].
*/
VariableMember(
VariableElement baseElement,
MapSubstitution substitution, [
DartType type,
]) : _type = type,
super(baseElement, substitution);
// TODO(jmesserly): this is temporary to allow the ParameterMember subclass.
// Apparently mixins don't work with optional params.
VariableMember._(VariableElement baseElement, MapSubstitution substitution,
[DartType type])
: this(baseElement, substitution, type);
@override
VariableElement get baseElement => super.baseElement as VariableElement;
@override
DartObject get constantValue => baseElement.constantValue;
@override
bool get hasImplicitType => baseElement.hasImplicitType;
@override
FunctionElement get initializer {
//
// Elements within this element should have type parameters substituted,
// just like this element.
//
throw UnsupportedError('initializer');
// return getBaseElement().getInitializer();
}
@override
bool get isConst => baseElement.isConst;
@override
bool get isConstantEvaluated => baseElement.isConstantEvaluated;
@override
bool get isFinal => baseElement.isFinal;
@override
bool get isLate => baseElement.isLate;
@override
@deprecated
bool get isPotentiallyMutatedInClosure =>
baseElement.isPotentiallyMutatedInClosure;
@override
@deprecated
bool get isPotentiallyMutatedInScope =>
baseElement.isPotentiallyMutatedInScope;
@override
bool get isStatic => baseElement.isStatic;
@override
DartType get type {
if (_type != null) return _type;
return _type = _substitution.substituteType(baseElement.type);
}
@override
DartObject computeConstantValue() => baseElement.computeConstantValue();
@override
void visitChildren(ElementVisitor visitor) {
// TODO(brianwilkerson) We need to finish implementing the accessors used
// below so that we can safely invoke them.
super.visitChildren(visitor);
baseElement.initializer?.accept(visitor);
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/type.dart | // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/dart/element/type_algebra.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisContext, AnalysisEngine;
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/type_system.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
/// Transforms the given [list] by applying [transform] to all its elements.
///
/// If no changes are made (i.e. the return value of [transform] is identical
/// to its parameter each time it is invoked), the original list is returned.
List<T> _transformOrShare<T>(List<T> list, T Function(T) transform) {
var length = list.length;
for (int i = 0; i < length; i++) {
var item = list[i];
var transformed = transform(item);
if (!identical(item, transformed)) {
var newList = list.toList();
newList[i] = transformed;
for (i++; i < length; i++) {
newList[i] = transform(list[i]);
}
return newList;
}
}
return list;
}
/**
* A [Type] that represents the type 'bottom'.
*/
class BottomTypeImpl extends TypeImpl {
/**
* The unique instance of this class, nullable.
*
* This behaves equivalently to the `Null` type, but we distinguish it for two
* reasons: (1) there are circumstances where we need access to this type, but
* we don't have access to the type provider, so using `Never?` is a
* convenient solution. (2) we may decide that the distinction is convenient
* in diagnostic messages (this is TBD).
*/
static final BottomTypeImpl instanceNullable =
new BottomTypeImpl._(NullabilitySuffix.question);
/**
* The unique instance of this class, starred.
*
* This behaves like a version of the Null* type that could be conceivably
* migrated to be of type Never. Therefore, it's the bottom of all legacy
* types, and also assignable to the true bottom. Note that Never? and Never*
* are not the same type, as Never* is a subtype of Never, while Never? is
* not.
*/
static final BottomTypeImpl instanceLegacy =
new BottomTypeImpl._(NullabilitySuffix.star);
/**
* The unique instance of this class, non-nullable.
*/
static final BottomTypeImpl instance =
new BottomTypeImpl._(NullabilitySuffix.none);
@override
final NullabilitySuffix nullabilitySuffix;
/**
* Prevent the creation of instances of this class.
*/
BottomTypeImpl._(this.nullabilitySuffix)
: super(new NeverElementImpl(), "Never");
@override
int get hashCode => 0;
@override
bool get isBottom => true;
@override
bool get isDartCoreNull {
// `Never?` is equivalent to `Null`, so make sure it behaves the same.
return nullabilitySuffix == NullabilitySuffix.question;
}
@override
bool operator ==(Object object) => identical(object, this);
@override
bool isMoreSpecificThan(DartType type,
[bool withDynamic = false, Set<Element> visitedElements]) =>
true;
@override
bool isSubtypeOf(DartType type) => true;
@override
bool isSupertypeOf(DartType type) => false;
@override
TypeImpl pruned(List<FunctionTypeAliasElement> prune) => this;
@override
DartType replaceTopAndBottom(TypeProvider typeProvider,
{bool isCovariant = true}) {
if (isCovariant) {
return this;
} else {
// In theory this should never happen, since we only need to do this
// replacement when checking super-boundedness of explicitly-specified
// types, or types produced by mixin inference or instantiate-to-bounds,
// and bottom can't occur in any of those cases.
assert(false,
'Attempted to check super-boundedness of a type including "bottom"');
// But just in case it does, return `dynamic` since that's similar to what
// we do with Null.
return typeProvider.objectType;
}
}
@override
BottomTypeImpl substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) =>
this;
@override
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) {
switch (nullabilitySuffix) {
case NullabilitySuffix.question:
return instanceNullable;
case NullabilitySuffix.star:
return instanceLegacy;
case NullabilitySuffix.none:
return instance;
}
throw StateError('Unexpected nullabilitySuffix: $nullabilitySuffix');
}
}
/**
* The type created internally if a circular reference is ever detected in a
* function type.
*/
class CircularFunctionTypeImpl extends DynamicTypeImpl
implements _FunctionTypeImplLazy {
CircularFunctionTypeImpl() : super._circular();
@override
List<ParameterElement> get baseParameters => const <ParameterElement>[];
@override
DartType get baseReturnType => DynamicTypeImpl.instance;
@override
List<TypeParameterElement> get boundTypeParameters =>
const <TypeParameterElement>[];
@override
FunctionTypedElement get element => null;
@override
bool get isInstantiated => false;
@override
Map<String, DartType> get namedParameterTypes => <String, DartType>{};
@override
List<FunctionTypeAliasElement> get newPrune =>
const <FunctionTypeAliasElement>[];
@override
List<String> get normalParameterNames => <String>[];
@override
List<DartType> get normalParameterTypes => const <DartType>[];
@override
List<String> get optionalParameterNames => <String>[];
@override
List<DartType> get optionalParameterTypes => const <DartType>[];
@override
List<ParameterElement> get parameters => const <ParameterElement>[];
@override
List<FunctionTypeAliasElement> get prunedTypedefs =>
const <FunctionTypeAliasElement>[];
@override
DartType get returnType => DynamicTypeImpl.instance;
@override
List<DartType> get typeArguments => const <DartType>[];
@override
List<TypeParameterElement> get typeFormals => const <TypeParameterElement>[];
@override
List<TypeParameterElement> get typeParameters =>
const <TypeParameterElement>[];
@override
bool get _isInstantiated => false;
@override
List<ParameterElement> get _parameters => const <ParameterElement>[];
@override
DartType get _returnType => DynamicTypeImpl.instance;
@override
List<DartType> get _typeArguments => const <DartType>[];
@override
void set _typeArguments(List<DartType> arguments) {
throw new UnsupportedError('Cannot have type arguments');
}
@override
List<TypeParameterElement> get _typeParameters =>
const <TypeParameterElement>[];
@override
void set _typeParameters(List<TypeParameterElement> parameters) {
throw new UnsupportedError('Cannot have type parameters');
}
@override
bool operator ==(Object object) => object is CircularFunctionTypeImpl;
@override
void appendTo(StringBuffer buffer, Set<TypeImpl> visitedTypes,
{bool withNullability = false}) {
buffer.write('...');
}
@override
FunctionTypeImpl instantiate(List<DartType> argumentTypes) => this;
@override
FunctionTypeImpl pruned(List<FunctionTypeAliasElement> prune) => this;
@override
FunctionType substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) {
return this;
}
@override
FunctionTypeImpl substitute3(List<DartType> argumentTypes) => this;
@override
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) => this;
@override
void _appendToWithTypeParameters(StringBuffer buffer,
Set<TypeImpl> visitedTypes, bool withNullability, String typeParameters) {
throw StateError('We should never get here.');
}
@override
void _forEachParameterType(
ParameterKind kind, callback(String name, DartType type)) {
// There are no parameters.
}
@override
void _freeVariablesInFunctionType(
FunctionType type, Set<TypeParameterType> free) {
// There are no free variables
}
@override
void _freeVariablesInInterfaceType(
InterfaceType type, Set<TypeParameterType> free) {
// There are no free variables
}
@override
void _freeVariablesInType(DartType type, Set<TypeParameterType> free) {
// There are no free variables
}
}
/**
* Type created internally if a circular reference is ever detected. Behaves
* like `dynamic`, except that when converted to a string it is displayed as
* `...`.
*/
class CircularTypeImpl extends DynamicTypeImpl {
CircularTypeImpl() : super._circular();
@override
bool operator ==(Object object) => object is CircularTypeImpl;
@override
void appendTo(StringBuffer buffer, Set<TypeImpl> visitedTypes,
{bool withNullability = false}) {
buffer.write('...');
}
@override
TypeImpl pruned(List<FunctionTypeAliasElement> prune) => this;
}
/**
* The [Type] representing the type `dynamic`.
*/
class DynamicTypeImpl extends TypeImpl {
/**
* The unique instance of this class.
*/
static final DynamicTypeImpl instance = new DynamicTypeImpl._();
/**
* Prevent the creation of instances of this class.
*/
DynamicTypeImpl._() : super(new DynamicElementImpl(), Keyword.DYNAMIC.lexeme);
/**
* Constructor used by [CircularTypeImpl].
*/
DynamicTypeImpl._circular() : super(instance.element, Keyword.DYNAMIC.lexeme);
@override
int get hashCode => 1;
@override
bool get isDynamic => true;
@override
NullabilitySuffix get nullabilitySuffix => NullabilitySuffix.none;
@override
bool operator ==(Object object) => identical(object, this);
@override
bool isMoreSpecificThan(DartType type,
[bool withDynamic = false, Set<Element> visitedElements]) {
// T is S
if (identical(this, type)) {
return true;
}
// else
return withDynamic;
}
@override
bool isSubtypeOf(DartType type) => true;
@override
bool isSupertypeOf(DartType type) => true;
@override
TypeImpl pruned(List<FunctionTypeAliasElement> prune) => this;
@override
DartType replaceTopAndBottom(TypeProvider typeProvider,
{bool isCovariant = true}) {
if (isCovariant) {
return typeProvider.nullType;
} else {
return this;
}
}
@override
DartType substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) {
int length = parameterTypes.length;
for (int i = 0; i < length; i++) {
if (parameterTypes[i] == this) {
return argumentTypes[i];
}
}
return this;
}
@override
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) {
// The dynamic type is always nullable.
return this;
}
}
/**
* The type of a function, method, constructor, getter, or setter.
*/
abstract class FunctionTypeImpl extends TypeImpl implements FunctionType {
@override
final NullabilitySuffix nullabilitySuffix;
/**
* Initialize a newly created function type to be declared by the given
* [element], and also initialize [typeArguments] to match the
* [typeParameters], which permits later substitution.
*/
factory FunctionTypeImpl(FunctionTypedElement element,
{NullabilitySuffix nullabilitySuffix = NullabilitySuffix.star}) {
if (element is FunctionTypeAliasElement) {
throw new StateError('Use FunctionTypeImpl.forTypedef for typedefs');
}
return new _FunctionTypeImplLazy._(
element, null, null, null, null, null, false,
nullabilitySuffix: nullabilitySuffix);
}
/// Creates a function type that's not associated with any element in the
/// element tree.
factory FunctionTypeImpl.synthetic(DartType returnType,
List<TypeParameterElement> typeFormals, List<ParameterElement> parameters,
{Element element,
List<DartType> typeArguments = const <DartType>[],
NullabilitySuffix nullabilitySuffix = NullabilitySuffix.star}) {
return new _FunctionTypeImplStrict._(returnType, typeFormals, parameters,
element: element,
typeArguments: typeArguments,
nullabilitySuffix: nullabilitySuffix);
}
FunctionTypeImpl._(Element element, String name, this.nullabilitySuffix)
: super(element, name);
@deprecated
@override
List<TypeParameterElement> get boundTypeParameters => typeFormals;
@override
String get displayName {
if (name == null || name.isEmpty) {
// Function types have an empty name when they are defined implicitly by
// either a closure or as part of a parameter declaration.
StringBuffer buffer = new StringBuffer();
appendTo(buffer, new Set.identity());
if (nullabilitySuffix == NullabilitySuffix.question) {
buffer.write('?');
}
return buffer.toString();
}
List<DartType> typeArguments = this.typeArguments;
bool allTypeArgumentsAreDynamic() {
for (DartType type in typeArguments) {
if (type != null && !type.isDynamic) {
return false;
}
}
return true;
}
StringBuffer buffer = new StringBuffer();
buffer.write(name);
// If there is at least one non-dynamic type, then list them out.
if (!allTypeArgumentsAreDynamic()) {
buffer.write("<");
for (int i = 0; i < typeArguments.length; i++) {
if (i != 0) {
buffer.write(", ");
}
DartType typeArg = typeArguments[i];
buffer.write(typeArg.displayName);
}
buffer.write(">");
}
if (nullabilitySuffix == NullabilitySuffix.question) {
buffer.write('?');
}
return buffer.toString();
}
@override
FunctionTypedElement get element => super.element;
@override
int get hashCode {
if (element == null) {
return 0;
}
// Reference the arrays of parameters
List<DartType> normalParameterTypes = this.normalParameterTypes;
List<DartType> optionalParameterTypes = this.optionalParameterTypes;
Iterable<DartType> namedParameterTypes = this.namedParameterTypes.values;
// Generate the hashCode
int code = returnType.hashCode;
for (int i = 0; i < normalParameterTypes.length; i++) {
code = (code << 1) + normalParameterTypes[i].hashCode;
}
for (int i = 0; i < optionalParameterTypes.length; i++) {
code = (code << 1) + optionalParameterTypes[i].hashCode;
}
for (DartType type in namedParameterTypes) {
code = (code << 1) + type.hashCode;
}
return code;
}
/**
* Return `true` if this type is the result of instantiating type parameters.
*/
bool get isInstantiated;
@override
Map<String, DartType> get namedParameterTypes {
// TODO(brianwilkerson) This implementation breaks the contract because the
// parameters will not necessarily be returned in the order in which they
// were declared.
Map<String, DartType> types = <String, DartType>{};
_forEachParameterType(ParameterKind.NAMED, (name, type) {
types[name] = type;
});
_forEachParameterType(ParameterKind.NAMED_REQUIRED, (name, type) {
types[name] = type;
});
return types;
}
/**
* Determine the new set of typedefs which should be pruned when expanding
* this function type.
*/
List<FunctionTypeAliasElement> get newPrune;
@override
List<DartType> get normalParameterTypes {
List<DartType> types = <DartType>[];
_forEachParameterType(ParameterKind.REQUIRED, (name, type) {
types.add(type);
});
return types;
}
@override
List<DartType> get optionalParameterTypes {
List<DartType> types = <DartType>[];
_forEachParameterType(ParameterKind.POSITIONAL, (name, type) {
types.add(type);
});
return types;
}
/**
* The set of typedefs which should not be expanded when exploring this type,
* to avoid creating infinite types in response to self-referential typedefs.
*/
List<FunctionTypeAliasElement> get prunedTypedefs;
@override
bool operator ==(Object object) {
if (object is FunctionTypeImpl) {
if (typeFormals.length != object.typeFormals.length) {
return false;
}
// `<T>T -> T` should be equal to `<U>U -> U`
// To test this, we instantiate both types with the same (unique) type
// variables, and see if the result is equal.
if (typeFormals.isNotEmpty) {
List<DartType> freshVariables = FunctionTypeImpl.relateTypeFormals(
this, object, (t, s, _, __) => t == s);
if (freshVariables == null) {
return false;
}
return instantiate(freshVariables) ==
object.instantiate(freshVariables);
}
return returnType == object.returnType &&
TypeImpl.equalArrays(
normalParameterTypes, object.normalParameterTypes) &&
TypeImpl.equalArrays(
optionalParameterTypes, object.optionalParameterTypes) &&
_equals(namedParameterTypes, object.namedParameterTypes) &&
nullabilitySuffix == object.nullabilitySuffix;
}
return false;
}
@override
void appendTo(StringBuffer buffer, Set<TypeImpl> visitedTypes,
{bool withNullability = false}) {
// TODO(paulberry): eliminate code duplication with
// _ElementWriter.writeType. See issue #35818.
if (visitedTypes.add(this)) {
if (typeFormals.isNotEmpty) {
StringBuffer typeParametersBuffer = StringBuffer();
// To print a type with type variables, first make sure we have unique
// variable names to print.
Set<TypeParameterType> freeVariables = new HashSet<TypeParameterType>();
_freeVariablesInFunctionType(this, freeVariables);
Set<String> namesToAvoid = new HashSet<String>();
for (DartType arg in freeVariables) {
if (arg is TypeParameterType) {
namesToAvoid.add(arg.displayName);
}
}
List<DartType> instantiateTypeArgs = <DartType>[];
List<TypeParameterElement> variables = <TypeParameterElement>[];
typeParametersBuffer.write('<');
for (TypeParameterElement e in typeFormals) {
if (e != typeFormals[0]) {
typeParametersBuffer.write(',');
}
String name = e.name;
int counter = 0;
while (!namesToAvoid.add(name)) {
// Unicode subscript-zero is U+2080, zero is U+0030. Other digits
// are sequential from there. Thus +0x2050 will get us the subscript.
String subscript = new String.fromCharCodes(
counter.toString().codeUnits.map((n) => n + 0x2050));
name = e.name + subscript;
counter++;
}
TypeParameterTypeImpl t = new TypeParameterTypeImpl(
new TypeParameterElementImpl(name, -1),
nullabilitySuffix: NullabilitySuffix.none);
t.appendTo(typeParametersBuffer, visitedTypes,
withNullability: withNullability);
instantiateTypeArgs.add(t);
variables.add(e);
if (e.bound != null) {
typeParametersBuffer.write(' extends ');
TypeImpl renamed =
Substitution.fromPairs(variables, instantiateTypeArgs)
.substituteType(e.bound);
renamed.appendTo(typeParametersBuffer, visitedTypes);
}
}
typeParametersBuffer.write('>');
// Instantiate it and print the resulting type.
this.instantiate(instantiateTypeArgs)._appendToWithTypeParameters(
buffer,
visitedTypes,
withNullability,
typeParametersBuffer.toString());
} else {
_appendToWithTypeParameters(buffer, visitedTypes, withNullability, '');
}
visitedTypes.remove(this);
} else {
buffer.write('<recursive>');
}
}
@override
FunctionTypeImpl instantiate(List<DartType> argumentTypes);
@override
bool isAssignableTo(DartType type) {
// A function type T may be assigned to a function type S, written T <=> S,
// iff T <: S.
return isSubtypeOf(type);
}
@override
bool isMoreSpecificThan(DartType type,
[bool withDynamic = false, Set<Element> visitedElements]) {
// Note: visitedElements is only used for breaking recursion in the type
// hierarchy; we don't use it when recursing into the function type.
return FunctionTypeImpl.relate(
this,
type,
(DartType t, DartType s) =>
(t as TypeImpl).isMoreSpecificThan(s, withDynamic));
}
@override
bool isSubtypeOf(DartType type) {
var typeSystem = new Dart2TypeSystem(null);
return FunctionTypeImpl.relate(
typeSystem.instantiateToBounds(this),
typeSystem.instantiateToBounds(type),
// ignore: deprecated_member_use_from_same_package
(DartType t, DartType s) => t.isAssignableTo(s));
}
@override
DartType replaceTopAndBottom(TypeProvider typeProvider,
{bool isCovariant: true}) {
var returnType = (this.returnType as TypeImpl)
.replaceTopAndBottom(typeProvider, isCovariant: isCovariant);
ParameterElement transformParameter(ParameterElement p) {
TypeImpl type = p.type;
var newType =
type.replaceTopAndBottom(typeProvider, isCovariant: !isCovariant);
if (identical(newType, type)) return p;
return new ParameterElementImpl.synthetic(
p.name,
newType,
// ignore: deprecated_member_use_from_same_package
p.parameterKind);
}
var parameters = _transformOrShare(this.parameters, transformParameter);
if (identical(returnType, this.returnType) &&
identical(parameters, this.parameters)) {
return this;
}
return new _FunctionTypeImplStrict._(returnType, typeFormals, parameters,
nullabilitySuffix: nullabilitySuffix);
}
@override
FunctionType substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]);
@override
FunctionTypeImpl substitute3(List<DartType> argumentTypes) =>
substitute2(argumentTypes, typeArguments);
void _appendToWithTypeParameters(StringBuffer buffer,
Set<TypeImpl> visitedTypes, bool withNullability, String typeParameters) {
List<DartType> normalParameterTypes = this.normalParameterTypes;
List<DartType> optionalParameterTypes = this.optionalParameterTypes;
Map<String, DartType> namedParameterTypes = this.namedParameterTypes;
DartType returnType = this.returnType;
if (returnType == null) {
buffer.write('null');
} else {
(returnType as TypeImpl)
.appendTo(buffer, visitedTypes, withNullability: withNullability);
}
buffer.write(' Function');
buffer.write(typeParameters);
bool needsComma = false;
void writeSeparator() {
if (needsComma) {
buffer.write(', ');
} else {
needsComma = true;
}
}
void startOptionalParameters() {
if (needsComma) {
buffer.write(', ');
needsComma = false;
}
}
buffer.write('(');
if (normalParameterTypes.isNotEmpty) {
for (DartType type in normalParameterTypes) {
writeSeparator();
(type as TypeImpl)
.appendTo(buffer, visitedTypes, withNullability: withNullability);
}
}
if (optionalParameterTypes.isNotEmpty) {
startOptionalParameters();
buffer.write('[');
for (DartType type in optionalParameterTypes) {
writeSeparator();
(type as TypeImpl)
.appendTo(buffer, visitedTypes, withNullability: withNullability);
}
buffer.write(']');
needsComma = true;
}
if (namedParameterTypes.isNotEmpty) {
startOptionalParameters();
buffer.write('{');
namedParameterTypes.forEach((String name, DartType type) {
writeSeparator();
buffer.write(name);
buffer.write(': ');
(type as TypeImpl)
.appendTo(buffer, visitedTypes, withNullability: withNullability);
});
buffer.write('}');
needsComma = true;
}
buffer.write(')');
if (withNullability) {
_appendNullability(buffer);
}
}
/**
* Invokes [callback] for each parameter of [kind] with the parameter's [name]
* and type after any type parameters have been applied.
*/
void _forEachParameterType(
ParameterKind kind, callback(String name, DartType type));
void _freeVariablesInFunctionType(
FunctionType type, Set<TypeParameterType> free) {
// Make some fresh variables to avoid capture.
List<DartType> typeArgs = const <DartType>[];
if (type.typeFormals.isNotEmpty) {
typeArgs = new List<DartType>.from(type.typeFormals.map((e) =>
new TypeParameterTypeImpl(new TypeParameterElementImpl(e.name, -1))));
type = type.instantiate(typeArgs);
}
for (ParameterElement p in type.parameters) {
_freeVariablesInType(p.type, free);
}
_freeVariablesInType(type.returnType, free);
// Remove all of our bound variables.
free.removeAll(typeArgs);
}
void _freeVariablesInInterfaceType(
InterfaceType type, Set<TypeParameterType> free) {
for (DartType typeArg in type.typeArguments) {
_freeVariablesInType(typeArg, free);
}
}
void _freeVariablesInType(DartType type, Set<TypeParameterType> free) {
if (type is TypeParameterType) {
free.add(type);
} else if (type is FunctionType) {
_freeVariablesInFunctionType(type, free);
} else if (type is InterfaceType) {
_freeVariablesInInterfaceType(type, free);
}
}
/**
* Compares two function types [t] and [s] to see if their corresponding
* parameter types match [parameterRelation], return types match
* [returnRelation], and type parameter bounds match [boundsRelation].
*
* Used for the various relations on function types which have the same
* structural rules for handling optional parameters and arity, but use their
* own relation for comparing corresponding parameters or return types.
*
* If [parameterRelation] is omitted, uses [returnRelation] for both. This
* is convenient for Dart 1 type system methods.
*
* If [boundsRelation] is omitted, uses [returnRelation]. This is for
* backwards compatibility, and convenience for Dart 1 type system methods.
*/
static bool relate(FunctionType t, DartType other,
bool returnRelation(DartType t, DartType s),
{bool parameterRelation(ParameterElement t, ParameterElement s),
bool boundsRelation(DartType bound2, DartType bound1,
TypeParameterElement formal2, TypeParameterElement formal1)}) {
parameterRelation ??= (t, s) => returnRelation(t.type, s.type);
boundsRelation ??= (t, s, _, __) => returnRelation(t, s);
// Trivial base cases.
if (other == null) {
return false;
} else if (identical(t, other) ||
other.isDynamic ||
other.isDartCoreFunction ||
other.isObject) {
return true;
} else if (other is! FunctionType) {
return false;
}
// This type cast is safe, because we checked it above.
FunctionType s = other as FunctionType;
if (t.typeFormals.isNotEmpty) {
List<DartType> freshVariables = relateTypeFormals(t, s, boundsRelation);
if (freshVariables == null) {
return false;
}
t = t.instantiate(freshVariables);
s = s.instantiate(freshVariables);
} else if (s.typeFormals.isNotEmpty) {
return false;
}
// Test the return types.
DartType sRetType = s.returnType;
if (!sRetType.isVoid && !returnRelation(t.returnType, sRetType)) {
return false;
}
// Test the parameter types.
return relateParameters(t.parameters, s.parameters, parameterRelation);
}
/**
* Compares parameters [tParams] and [sParams] of two function types, taking
* corresponding parameters from the lists, and see if they match
* [parameterRelation].
*
* Corresponding parameters are defined as a pair `(t, s)` where `t` is a
* parameter from [tParams] and `s` is a parameter from [sParams], and both
* `t` and `s` are at the same position (for positional parameters)
* or have the same name (for named parameters).
*
* Used for the various relations on function types which have the same
* structural rules for handling optional parameters and arity, but use their
* own relation for comparing the parameters.
*/
static bool relateParameters(
List<ParameterElement> tParams,
List<ParameterElement> sParams,
bool parameterRelation(ParameterElement t, ParameterElement s)) {
// TODO(jmesserly): this could be implemented with less allocation if we
// wanted, by taking advantage of the fact that positional arguments must
// appear before named ones.
var tRequired = <ParameterElement>[];
var tOptional = <ParameterElement>[];
var tNamed = <String, ParameterElement>{};
for (var p in tParams) {
if (p.isRequiredPositional) {
tRequired.add(p);
} else if (p.isOptionalPositional) {
tOptional.add(p);
} else {
assert(p.isNamed);
tNamed[p.name] = p;
}
}
var sRequired = <ParameterElement>[];
var sOptional = <ParameterElement>[];
var sNamed = <String, ParameterElement>{};
for (var p in sParams) {
if (p.isRequiredPositional) {
sRequired.add(p);
} else if (p.isOptionalPositional) {
sOptional.add(p);
} else {
assert(p.isNamed);
sNamed[p.name] = p;
}
}
// If one function has positional and the other has named parameters,
// they don't relate.
if (sOptional.isNotEmpty && tNamed.isNotEmpty ||
tOptional.isNotEmpty && sNamed.isNotEmpty) {
return false;
}
// If the passed function includes more named parameters than we do, we
// don't relate.
if (tNamed.length < sNamed.length) {
return false;
}
// For each named parameter in s, make sure we have a corresponding one
// that relates.
for (String key in sNamed.keys) {
var tParam = tNamed[key];
if (tParam == null) {
return false;
}
var sParam = sNamed[key];
if (!parameterRelation(tParam, sParam)) {
return false;
}
}
// Make sure all of the positional parameters (both required and optional)
// relate to each other.
var tPositional = tRequired;
var sPositional = sRequired;
if (tOptional.isNotEmpty) {
tPositional = tPositional.toList()..addAll(tOptional);
}
if (sOptional.isNotEmpty) {
sPositional = sPositional.toList()..addAll(sOptional);
}
// Check that s has enough required parameters.
if (sRequired.length < tRequired.length) {
return false;
}
// Check that s does not include more positional parameters than we do.
if (tPositional.length < sPositional.length) {
return false;
}
for (int i = 0; i < sPositional.length; i++) {
if (!parameterRelation(tPositional[i], sPositional[i])) {
return false;
}
}
return true;
}
/**
* Given two functions [f1] and [f2] where f1 and f2 are known to be
* generic function types (both have type formals), this checks that they
* have the same number of formals, and that those formals have bounds
* (e.g. `<T extends LowerBound>`) that satisfy [relation].
*
* The return value will be a new list of fresh type variables, that can be
* used to instantiate both function types, allowing further comparison.
* For example, given `<T>T -> T` and `<U>U -> U` we can instantiate them with
* `F` to get `F -> F` and `F -> F`, which we can see are equal.
*/
static List<DartType> relateTypeFormals(
FunctionType f1,
FunctionType f2,
bool relation(DartType bound2, DartType bound1,
TypeParameterElement formal2, TypeParameterElement formal1)) {
List<TypeParameterElement> params1 = f1.typeFormals;
List<TypeParameterElement> params2 = f2.typeFormals;
return relateTypeFormals2(params1, params2, relation);
}
static List<DartType> relateTypeFormals2(
List<TypeParameterElement> params1,
List<TypeParameterElement> params2,
bool relation(DartType bound2, DartType bound1,
TypeParameterElement formal2, TypeParameterElement formal1)) {
int count = params1.length;
if (params2.length != count) {
return null;
}
// We build up a substitution matching up the type parameters
// from the two types, {variablesFresh/variables1} and
// {variablesFresh/variables2}
List<TypeParameterElement> variables1 = <TypeParameterElement>[];
List<TypeParameterElement> variables2 = <TypeParameterElement>[];
List<DartType> variablesFresh = <DartType>[];
for (int i = 0; i < count; i++) {
TypeParameterElement p1 = params1[i];
TypeParameterElement p2 = params2[i];
TypeParameterElementImpl pFresh =
new TypeParameterElementImpl.synthetic(p2.name);
DartType variableFresh = new TypeParameterTypeImpl(pFresh);
variables1.add(p1);
variables2.add(p2);
variablesFresh.add(variableFresh);
DartType bound1 = p1.bound ?? DynamicTypeImpl.instance;
DartType bound2 = p2.bound ?? DynamicTypeImpl.instance;
bound1 = Substitution.fromPairs(variables1, variablesFresh)
.substituteType(bound1);
bound2 = Substitution.fromPairs(variables2, variablesFresh)
.substituteType(bound2);
if (!relation(bound2, bound1, p2, p1)) {
return null;
}
if (!bound2.isDynamic) {
pFresh.bound = bound2;
}
}
return variablesFresh;
}
/**
* Return `true` if all of the name/type pairs in the first map ([firstTypes])
* are equal to the corresponding name/type pairs in the second map
* ([secondTypes]). The maps are expected to iterate over their entries in the
* same order in which those entries were added to the map.
*/
static bool _equals(
Map<String, DartType> firstTypes, Map<String, DartType> secondTypes) {
if (secondTypes.length != firstTypes.length) {
return false;
}
Iterator<String> firstKeys = firstTypes.keys.iterator;
Iterator<String> secondKeys = secondTypes.keys.iterator;
while (firstKeys.moveNext() && secondKeys.moveNext()) {
String firstKey = firstKeys.current;
String secondKey = secondKeys.current;
TypeImpl firstType = firstTypes[firstKey];
TypeImpl secondType = secondTypes[secondKey];
if (firstKey != secondKey || firstType != secondType) {
return false;
}
}
return true;
}
}
/**
* A concrete implementation of an [InterfaceType].
*/
class InterfaceTypeImpl extends TypeImpl implements InterfaceType {
@override
final NullabilitySuffix nullabilitySuffix;
/**
* A list containing the actual types of the type arguments.
*/
List<DartType> _typeArguments = const <DartType>[];
/**
* The set of typedefs which should not be expanded when exploring this type,
* to avoid creating infinite types in response to self-referential typedefs.
*/
final List<FunctionTypeAliasElement> prunedTypedefs;
/**
* The version of [element] for which members are cached.
*/
int _versionOfCachedMembers;
/**
* Cached [ConstructorElement]s - members or raw elements.
*/
List<ConstructorElement> _constructors;
/**
* Cached [PropertyAccessorElement]s - members or raw elements.
*/
List<PropertyAccessorElement> _accessors;
/**
* Cached [MethodElement]s - members or raw elements.
*/
List<MethodElement> _methods;
/**
* Initialize a newly created type to be declared by the given [element].
*/
InterfaceTypeImpl(ClassElement element,
{this.prunedTypedefs, this.nullabilitySuffix = NullabilitySuffix.star})
: super(element, element.displayName);
InterfaceTypeImpl.explicit(ClassElement element, List<DartType> typeArguments,
{this.nullabilitySuffix = NullabilitySuffix.star})
: prunedTypedefs = null,
_typeArguments = typeArguments,
super(element, element.displayName);
/**
* Private constructor.
*/
InterfaceTypeImpl._(Element element, String name, this.prunedTypedefs,
{this.nullabilitySuffix = NullabilitySuffix.star})
: super(element, name);
InterfaceTypeImpl._withNullability(InterfaceTypeImpl original,
{this.nullabilitySuffix = NullabilitySuffix.star})
: _typeArguments = original._typeArguments,
prunedTypedefs = original.prunedTypedefs,
super(original.element, original.name);
@override
List<PropertyAccessorElement> get accessors {
_flushCachedMembersIfStale();
if (_accessors == null) {
List<PropertyAccessorElement> accessors = element.accessors;
List<PropertyAccessorElement> members =
new List<PropertyAccessorElement>(accessors.length);
for (int i = 0; i < accessors.length; i++) {
members[i] = PropertyAccessorMember.from(accessors[i], this);
}
_accessors = members;
}
return _accessors;
}
@override
List<ConstructorElement> get constructors {
_flushCachedMembersIfStale();
if (_constructors == null) {
List<ConstructorElement> constructors = element.constructors;
List<ConstructorElement> members =
new List<ConstructorElement>(constructors.length);
for (int i = 0; i < constructors.length; i++) {
members[i] = ConstructorMember.from(constructors[i], this);
}
_constructors = members;
}
return _constructors;
}
@override
String get displayName {
List<DartType> typeArguments = this.typeArguments;
bool allTypeArgumentsAreDynamic() {
for (DartType type in typeArguments) {
if (type != null && !type.isDynamic) {
return false;
}
}
return true;
}
StringBuffer buffer = new StringBuffer();
buffer.write(name);
// If there is at least one non-dynamic type, then list them out.
if (!allTypeArgumentsAreDynamic()) {
buffer.write("<");
for (int i = 0; i < typeArguments.length; i++) {
if (i != 0) {
buffer.write(", ");
}
DartType typeArg = typeArguments[i];
buffer.write(typeArg.displayName);
}
buffer.write(">");
}
if (nullabilitySuffix == NullabilitySuffix.question) {
buffer.write('?');
}
return buffer.toString();
}
@override
ClassElement get element => super.element;
@override
int get hashCode {
ClassElement element = this.element;
if (element == null) {
return 0;
}
return element.hashCode;
}
@override
List<InterfaceType> get interfaces {
return _instantiateSuperTypes(element.interfaces);
}
@override
bool get isDartAsyncFuture {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "Future" && element.library.isDartAsync;
}
@override
bool get isDartAsyncFutureOr {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "FutureOr" && element.library.isDartAsync;
}
@override
bool get isDartCoreBool {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "bool" && element.library.isDartCore;
}
@override
bool get isDartCoreDouble {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "double" && element.library.isDartCore;
}
@override
bool get isDartCoreFunction {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "Function" && element.library.isDartCore;
}
@override
bool get isDartCoreInt {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "int" && element.library.isDartCore;
}
@override
bool get isDartCoreList {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "List" && element.library.isDartCore;
}
@override
bool get isDartCoreMap {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "Map" && element.library.isDartCore;
}
@override
bool get isDartCoreNull {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "Null" && element.library.isDartCore;
}
@override
bool get isDartCoreNum {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "num" && element.library.isDartCore;
}
@override
bool get isDartCoreObject {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "Object" && element.library.isDartCore;
}
@override
bool get isDartCoreSet {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "Set" && element.library.isDartCore;
}
@override
bool get isDartCoreString {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "String" && element.library.isDartCore;
}
@override
bool get isDartCoreSymbol {
ClassElement element = this.element;
if (element == null) {
return false;
}
return element.name == "Symbol" && element.library.isDartCore;
}
@override
bool get isObject => element.supertype == null && !element.isMixin;
@override
List<MethodElement> get methods {
_flushCachedMembersIfStale();
if (_methods == null) {
List<MethodElement> methods = element.methods;
List<MethodElement> members = new List<MethodElement>(methods.length);
for (int i = 0; i < methods.length; i++) {
members[i] = MethodMember.from(methods[i], this);
}
_methods = members;
}
return _methods;
}
@override
List<InterfaceType> get mixins {
List<InterfaceType> mixins = element.mixins;
return _instantiateSuperTypes(mixins);
}
@override
InterfaceType get superclass {
InterfaceType supertype = element.supertype;
if (supertype == null) {
return null;
}
return Substitution.fromInterfaceType(this).substituteType(supertype);
}
@override
List<InterfaceType> get superclassConstraints {
List<InterfaceType> constraints = element.superclassConstraints;
return _instantiateSuperTypes(constraints);
}
@override
List<DartType> get typeArguments {
return _typeArguments;
}
/**
* Set [typeArguments].
*/
void set typeArguments(List<DartType> typeArguments) {
_typeArguments = typeArguments;
}
@override
List<TypeParameterElement> get typeParameters => element.typeParameters;
@override
bool operator ==(Object object) {
if (identical(object, this)) {
return true;
}
if (object is InterfaceTypeImpl) {
return element == object.element &&
TypeImpl.equalArrays(typeArguments, object.typeArguments) &&
nullabilitySuffix == object.nullabilitySuffix;
}
return false;
}
@override
void appendTo(StringBuffer buffer, Set<TypeImpl> visitedTypes,
{bool withNullability = false}) {
if (visitedTypes.add(this)) {
buffer.write(name);
int argumentCount = typeArguments.length;
if (argumentCount > 0) {
buffer.write("<");
for (int i = 0; i < argumentCount; i++) {
if (i > 0) {
buffer.write(", ");
}
(typeArguments[i] as TypeImpl)
.appendTo(buffer, visitedTypes, withNullability: withNullability);
}
buffer.write(">");
}
if (withNullability) {
_appendNullability(buffer);
}
visitedTypes.remove(this);
} else {
buffer.write('<recursive>');
}
}
/**
* Return either this type or a supertype of this type that is defined by the
* [targetElement], or `null` if such a type does not exist. If this type
* inherits from the target element along multiple paths, then the returned type
* is arbitrary.
*
* For example, given the following definitions
* ```
* class A<E> {}
* class B<E> implements A<E> {}
* class C implements A<String> {}
* ```
* Asking the type `B<int>` for the type associated with `A` will return the
* type `A<int>`. Asking the type `C` for the type associated with `A` will
* return the type `A<String>`.
*/
InterfaceType asInstanceOf(ClassElement targetElement) {
return _asInstanceOf(targetElement, new Set<ClassElement>());
}
@override
DartType flattenFutures(TypeSystem typeSystem) {
// Implement the cases:
// - "If T = FutureOr<S> then flatten(T) = S."
// - "If T = Future<S> then flatten(T) = S."
if (isDartAsyncFutureOr || isDartAsyncFuture) {
return typeArguments.isNotEmpty
? typeArguments[0]
: DynamicTypeImpl.instance;
}
// Implement the case: "Otherwise if T <: Future then let S be a type
// such that T << Future<S> and for all R, if T << Future<R> then S << R.
// Then flatten(T) = S."
//
// In other words, given the set of all types R such that T << Future<R>,
// let S be the most specific of those types, if any such S exists.
//
// Since we only care about the most specific type, it is sufficient to
// look at the types appearing as a parameter to Future in the type
// hierarchy of T. We don't need to consider the supertypes of those
// types, since they are by definition less specific.
List<DartType> candidateTypes =
_searchTypeHierarchyForFutureTypeParameters();
DartType flattenResult = findMostSpecificType(candidateTypes, typeSystem);
if (flattenResult != null) {
return flattenResult;
}
// Implement the case: "In any other circumstance, flatten(T) = T."
return this;
}
@override
PropertyAccessorElement getGetter(String getterName) =>
PropertyAccessorMember.from(element.getGetter(getterName), this);
@override
MethodElement getMethod(String methodName) =>
MethodMember.from(element.getMethod(methodName), this);
@override
PropertyAccessorElement getSetter(String setterName) =>
PropertyAccessorMember.from(element.getSetter(setterName), this);
@override
InterfaceTypeImpl instantiate(List<DartType> argumentTypes) =>
substitute2(argumentTypes, typeArguments);
@override
bool isDirectSupertypeOf(InterfaceType type) {
InterfaceType i = this;
InterfaceType j = type;
var substitution = Substitution.fromInterfaceType(j);
ClassElement jElement = j.element;
//
// If J is Object, then it has no direct supertypes.
//
if (j.isObject) {
return false;
}
//
// I is listed in the extends clause of J.
//
InterfaceType supertype = jElement.supertype;
if (supertype != null) {
supertype = substitution.substituteType(supertype);
if (supertype == i) {
return true;
}
}
//
// I is listed in the on clause of J.
//
for (InterfaceType interfaceType in jElement.superclassConstraints) {
interfaceType = substitution.substituteType(interfaceType);
if (interfaceType == i) {
return true;
}
}
//
// I is listed in the implements clause of J.
//
for (InterfaceType interfaceType in jElement.interfaces) {
interfaceType = substitution.substituteType(interfaceType);
if (interfaceType == i) {
return true;
}
}
//
// I is listed in the with clause of J.
//
for (InterfaceType mixinType in jElement.mixins) {
mixinType = substitution.substituteType(mixinType);
if (mixinType == i) {
return true;
}
}
//
// J is a mixin application of the mixin of I.
//
// TODO(brianwilkerson) Determine whether this needs to be implemented or
// whether it is covered by the case above.
return false;
}
@override
bool isMoreSpecificThan(DartType type,
[bool withDynamic = false, Set<Element> visitedElements]) {
//
// T is Null and S is not Bottom.
//
if (isDartCoreNull && !type.isBottom) {
return true;
}
// S is dynamic.
// The test to determine whether S is dynamic is done here because dynamic
// is not an instance of InterfaceType.
//
if (type.isDynamic) {
return true;
}
//
// A type T is more specific than a type S, written T << S,
// if one of the following conditions is met:
//
// Reflexivity: T is S.
//
if (this == type) {
return true;
}
if (type is InterfaceType) {
//
// T is bottom. (This case is handled by the class BottomTypeImpl.)
//
// Direct supertype: S is a direct supertype of T.
//
// ignore: deprecated_member_use_from_same_package
if (type.isDirectSupertypeOf(this)) {
return true;
}
//
// Covariance: T is of the form I<T1, ..., Tn> and S is of the form
// I<S1, ..., Sn> and Ti << Si, 1 <= i <= n.
//
ClassElement tElement = this.element;
ClassElement sElement = type.element;
if (tElement == sElement) {
List<DartType> tArguments = typeArguments;
List<DartType> sArguments = type.typeArguments;
if (tArguments.length != sArguments.length) {
return false;
}
for (int i = 0; i < tArguments.length; i++) {
if (!(tArguments[i] as TypeImpl)
.isMoreSpecificThan(sArguments[i], withDynamic)) {
return false;
}
}
return true;
}
}
//
// Transitivity: T << U and U << S.
//
// First check for infinite loops
if (element == null) {
return false;
}
if (visitedElements == null) {
visitedElements = new HashSet<ClassElement>();
} else if (visitedElements.contains(element)) {
return false;
}
visitedElements.add(element);
try {
// Iterate over all of the types U that are more specific than T because
// they are direct supertypes of T and return true if any of them are more
// specific than S.
InterfaceTypeImpl supertype = superclass;
if (supertype != null &&
supertype.isMoreSpecificThan(type, withDynamic, visitedElements)) {
return true;
}
for (InterfaceType interfaceType in interfaces) {
if ((interfaceType as InterfaceTypeImpl)
.isMoreSpecificThan(type, withDynamic, visitedElements)) {
return true;
}
}
for (InterfaceType mixinType in mixins) {
if ((mixinType as InterfaceTypeImpl)
.isMoreSpecificThan(type, withDynamic, visitedElements)) {
return true;
}
}
if (element.isMixin) {
for (InterfaceType constraint in superclassConstraints) {
if ((constraint as InterfaceTypeImpl)
.isMoreSpecificThan(type, withDynamic, visitedElements)) {
return true;
}
}
}
// If a type I includes an instance method named `call`, and the type of
// `call` is the function type F, then I is considered to be more specific
// than F.
MethodElement callMethod = getMethod('call');
if (callMethod != null && !callMethod.isStatic) {
FunctionTypeImpl callType = callMethod.type;
if (callType.isMoreSpecificThan(type, withDynamic, visitedElements)) {
return true;
}
}
return false;
} finally {
visitedElements.remove(element);
}
}
@override
ConstructorElement lookUpConstructor(
String constructorName, LibraryElement library) {
// prepare base ConstructorElement
ConstructorElement constructorElement;
if (constructorName == null) {
constructorElement = element.unnamedConstructor;
} else {
constructorElement = element.getNamedConstructor(constructorName);
}
// not found or not accessible
if (constructorElement == null ||
!constructorElement.isAccessibleIn(library)) {
return null;
}
// return member
return ConstructorMember.from(constructorElement, this);
}
@override
PropertyAccessorElement lookUpGetter(
String getterName, LibraryElement library) {
PropertyAccessorElement element = getGetter(getterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
return lookUpGetterInSuperclass(getterName, library);
}
@override
PropertyAccessorElement lookUpGetterInSuperclass(
String getterName, LibraryElement library) {
for (InterfaceType mixin in mixins.reversed) {
PropertyAccessorElement element = mixin.getGetter(getterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
for (InterfaceType constraint in superclassConstraints) {
PropertyAccessorElement element = constraint.getGetter(getterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
InterfaceType supertype = superclass;
ClassElement supertypeElement = supertype?.element;
while (supertype != null && !visitedClasses.contains(supertypeElement)) {
visitedClasses.add(supertypeElement);
PropertyAccessorElement element = supertype.getGetter(getterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
for (InterfaceType mixin in supertype.mixins.reversed) {
element = mixin.getGetter(getterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
supertype = supertype.superclass;
supertypeElement = supertype?.element;
}
return null;
}
@override
PropertyAccessorElement lookUpInheritedGetter(String name,
{LibraryElement library, bool thisType: true}) {
PropertyAccessorElement result;
if (thisType) {
result = lookUpGetter(name, library);
} else {
result = lookUpGetterInSuperclass(name, library);
}
if (result != null) {
return result;
}
return _lookUpMemberInInterfaces(this, false, library,
new HashSet<ClassElement>(), (InterfaceType t) => t.getGetter(name));
}
@override
ExecutableElement lookUpInheritedGetterOrMethod(String name,
{LibraryElement library}) {
ExecutableElement result =
lookUpGetter(name, library) ?? lookUpMethod(name, library);
if (result != null) {
return result;
}
return _lookUpMemberInInterfaces(
this,
false,
library,
new HashSet<ClassElement>(),
(InterfaceType t) => t.getGetter(name) ?? t.getMethod(name));
}
ExecutableElement lookUpInheritedMember(String name, LibraryElement library,
{bool concrete: false,
bool forSuperInvocation: false,
int startMixinIndex,
bool setter: false,
bool thisType: false}) {
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
/// TODO(scheglov) Remove [includeSupers]. It is used only to work around
/// the problem with Flutter code base (using old super-mixins).
ExecutableElement lookUpImpl(InterfaceTypeImpl type,
{bool acceptAbstract: false,
bool includeType: true,
bool inMixin: false,
int startMixinIndex}) {
if (type == null || !visitedClasses.add(type.element)) {
return null;
}
if (includeType) {
ExecutableElement result;
if (setter) {
result = type.getSetter(name);
} else {
result = type.getMethod(name);
result ??= type.getGetter(name);
}
if (result != null && result.isAccessibleIn(library)) {
if (!concrete || acceptAbstract || !result.isAbstract) {
return result;
}
}
}
if (!inMixin || acceptAbstract) {
var mixins = type.mixins;
startMixinIndex ??= mixins.length;
for (var i = startMixinIndex - 1; i >= 0; i--) {
var result = lookUpImpl(
mixins[i],
acceptAbstract: acceptAbstract,
inMixin: true,
);
if (result != null) {
return result;
}
}
}
// We were not able to find the concrete dispatch target.
// It is OK to look into interfaces, we need just some resolution now.
if (!concrete) {
for (InterfaceType mixin in type.interfaces) {
var result = lookUpImpl(mixin, acceptAbstract: acceptAbstract);
if (result != null) {
return result;
}
}
}
if (!inMixin || acceptAbstract) {
return lookUpImpl(type.superclass,
acceptAbstract: acceptAbstract, inMixin: inMixin);
}
return null;
}
if (element.isMixin) {
// TODO(scheglov) We should choose the most specific signature.
// Not just the first signature.
for (InterfaceType constraint in superclassConstraints) {
var result = lookUpImpl(constraint, acceptAbstract: true);
if (result != null) {
return result;
}
}
return null;
} else {
return lookUpImpl(
this,
includeType: thisType,
startMixinIndex: startMixinIndex,
);
}
}
@override
MethodElement lookUpInheritedMethod(String name,
{LibraryElement library, bool thisType: true}) {
MethodElement result;
if (thisType) {
result = lookUpMethod(name, library);
} else {
result = lookUpMethodInSuperclass(name, library);
}
if (result != null) {
return result;
}
return _lookUpMemberInInterfaces(this, false, library,
new HashSet<ClassElement>(), (InterfaceType t) => t.getMethod(name));
}
@override
PropertyAccessorElement lookUpInheritedSetter(String name,
{LibraryElement library, bool thisType: true}) {
PropertyAccessorElement result;
if (thisType) {
result = lookUpSetter(name, library);
} else {
result = lookUpSetterInSuperclass(name, library);
}
if (result != null) {
return result;
}
return _lookUpMemberInInterfaces(this, false, library,
new HashSet<ClassElement>(), (t) => t.getSetter(name));
}
@override
MethodElement lookUpMethod(String methodName, LibraryElement library) {
MethodElement element = getMethod(methodName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
return lookUpMethodInSuperclass(methodName, library);
}
@override
MethodElement lookUpMethodInSuperclass(
String methodName, LibraryElement library) {
for (InterfaceType mixin in mixins.reversed) {
MethodElement element = mixin.getMethod(methodName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
for (InterfaceType constraint in superclassConstraints) {
MethodElement element = constraint.getMethod(methodName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
InterfaceType supertype = superclass;
ClassElement supertypeElement = supertype?.element;
while (supertype != null && !visitedClasses.contains(supertypeElement)) {
visitedClasses.add(supertypeElement);
MethodElement element = supertype.getMethod(methodName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
for (InterfaceType mixin in supertype.mixins.reversed) {
element = mixin.getMethod(methodName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
supertype = supertype.superclass;
supertypeElement = supertype?.element;
}
return null;
}
@override
PropertyAccessorElement lookUpSetter(
String setterName, LibraryElement library) {
PropertyAccessorElement element = getSetter(setterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
return lookUpSetterInSuperclass(setterName, library);
}
@override
PropertyAccessorElement lookUpSetterInSuperclass(
String setterName, LibraryElement library) {
for (InterfaceType mixin in mixins.reversed) {
PropertyAccessorElement element = mixin.getSetter(setterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
for (InterfaceType constraint in superclassConstraints) {
PropertyAccessorElement element = constraint.getSetter(setterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
InterfaceType supertype = superclass;
ClassElement supertypeElement = supertype?.element;
while (supertype != null && !visitedClasses.contains(supertypeElement)) {
visitedClasses.add(supertypeElement);
PropertyAccessorElement element = supertype.getSetter(setterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
for (InterfaceType mixin in supertype.mixins.reversed) {
element = mixin.getSetter(setterName);
if (element != null && element.isAccessibleIn(library)) {
return element;
}
}
supertype = supertype.superclass;
supertypeElement = supertype?.element;
}
return null;
}
@override
InterfaceTypeImpl pruned(List<FunctionTypeAliasElement> prune) {
if (prune == null) {
return this;
} else {
// There should never be a reason to prune a type that has already been
// pruned, since pruning is only done when expanding a function type
// alias, and function type aliases are always expanded by starting with
// base types.
assert(this.prunedTypedefs == null);
InterfaceTypeImpl result = new InterfaceTypeImpl._(element, name, prune,
nullabilitySuffix: nullabilitySuffix);
result.typeArguments = typeArguments
.map((DartType t) => (t as TypeImpl).pruned(prune))
.toList();
return result;
}
}
@override
DartType replaceTopAndBottom(TypeProvider typeProvider,
{bool isCovariant: true}) {
// First check if this is actually an instance of Bottom
if (this.isDartCoreNull) {
if (isCovariant) {
return this;
} else {
return typeProvider.objectType;
}
}
// Otherwise, recurse over type arguments.
var typeArguments = _transformOrShare(
this.typeArguments,
(t) => (t as TypeImpl)
.replaceTopAndBottom(typeProvider, isCovariant: isCovariant));
if (identical(typeArguments, this.typeArguments)) {
return this;
} else {
return new InterfaceTypeImpl._(element, name, prunedTypedefs,
nullabilitySuffix: nullabilitySuffix)
..typeArguments = typeArguments;
}
}
@override
InterfaceTypeImpl substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) {
if (argumentTypes.length != parameterTypes.length) {
throw new ArgumentError(
"argumentTypes.length (${argumentTypes.length}) != parameterTypes.length (${parameterTypes.length})");
}
if (argumentTypes.isEmpty || typeArguments.isEmpty) {
return this.pruned(prune);
}
List<DartType> newTypeArguments = TypeImpl.substitute(
typeArguments, argumentTypes, parameterTypes, prune);
InterfaceTypeImpl newType = new InterfaceTypeImpl(element,
prunedTypedefs: prune, nullabilitySuffix: nullabilitySuffix);
newType.typeArguments = newTypeArguments;
return newType;
}
@deprecated
@override
InterfaceTypeImpl substitute4(List<DartType> argumentTypes) =>
instantiate(argumentTypes);
@override
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) {
if (this.nullabilitySuffix == nullabilitySuffix) return this;
return InterfaceTypeImpl._withNullability(this,
nullabilitySuffix: nullabilitySuffix);
}
/**
* Return either this type or a supertype of this type that is defined by the
* [targetElement], or `null` if such a type does not exist. The set of
* [visitedClasses] is used to prevent infinite recursion.
*/
InterfaceType _asInstanceOf(
ClassElement targetElement, Set<ClassElement> visitedClasses) {
ClassElement thisElement = element;
if (thisElement == targetElement) {
return this;
} else if (visitedClasses.add(thisElement)) {
InterfaceType type;
for (InterfaceType mixin in mixins) {
type = (mixin as InterfaceTypeImpl)
._asInstanceOf(targetElement, visitedClasses);
if (type != null) {
return type;
}
}
if (superclass != null) {
type = (superclass as InterfaceTypeImpl)
._asInstanceOf(targetElement, visitedClasses);
if (type != null) {
return type;
}
}
for (InterfaceType interface in interfaces) {
type = (interface as InterfaceTypeImpl)
._asInstanceOf(targetElement, visitedClasses);
if (type != null) {
return type;
}
}
}
return null;
}
/**
* Flush cache members if the version of [element] for which members are
* cached and the current version of the [element].
*/
void _flushCachedMembersIfStale() {
ClassElement element = this.element;
if (element is ClassElementImpl) {
int currentVersion = element.version;
if (_versionOfCachedMembers != currentVersion) {
_constructors = null;
_accessors = null;
_methods = null;
}
_versionOfCachedMembers = currentVersion;
}
}
List<InterfaceType> _instantiateSuperTypes(List<InterfaceType> defined) {
if (defined.isEmpty) return defined;
var typeParameters = element.typeParameters;
if (typeParameters.isEmpty) return defined;
var substitution = Substitution.fromInterfaceType(this);
var result = List<InterfaceType>(defined.length);
for (int i = 0; i < defined.length; i++) {
result[i] = substitution.substituteType(defined[i]);
}
return result;
}
/**
* Starting from this type, search its class hierarchy for types of the form
* Future<R>, and return a list of the resulting R's.
*/
List<DartType> _searchTypeHierarchyForFutureTypeParameters() {
List<DartType> result = <DartType>[];
HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
void recurse(InterfaceTypeImpl type) {
if (type.isDartAsyncFuture && type.typeArguments.isNotEmpty) {
result.add(type.typeArguments[0]);
}
if (visitedClasses.add(type.element)) {
if (type.superclass != null) {
recurse(type.superclass);
}
for (InterfaceType interface in type.interfaces) {
recurse(interface);
}
visitedClasses.remove(type.element);
}
}
recurse(this);
return result;
}
/**
* If there is a single type which is at least as specific as all of the
* types in [types], return it. Otherwise return `null`.
*/
static DartType findMostSpecificType(
List<DartType> types, TypeSystem typeSystem) {
// The << relation ("more specific than") is a partial ordering on types,
// so to find the most specific type of a set, we keep a bucket of the most
// specific types seen so far such that no type in the bucket is more
// specific than any other type in the bucket.
List<DartType> bucket = <DartType>[];
// Then we consider each type in turn.
for (DartType type in types) {
// If any existing type in the bucket is more specific than this type,
// then we can ignore this type.
if (bucket.any((DartType t) => typeSystem.isSubtypeOf(t, type))) {
continue;
}
// Otherwise, we need to add this type to the bucket and remove any types
// that are less specific than it.
bool added = false;
int i = 0;
while (i < bucket.length) {
if (typeSystem.isSubtypeOf(type, bucket[i])) {
if (added) {
if (i < bucket.length - 1) {
bucket[i] = bucket.removeLast();
} else {
bucket.removeLast();
}
} else {
bucket[i] = type;
i++;
added = true;
}
} else {
i++;
}
}
if (!added) {
bucket.add(type);
}
}
// Now that we are finished, if there is exactly one type left in the
// bucket, it is the most specific type.
if (bucket.length == 1) {
return bucket[0];
}
// Otherwise, there is no single type that is more specific than the
// others.
return null;
}
/**
* Returns a "smart" version of the "least upper bound" of the given types.
*
* If these types have the same element and differ only in terms of the type
* arguments, attempts to find a compatible set of type arguments.
*
* Otherwise, calls [DartType.getLeastUpperBound].
*/
static InterfaceType getSmartLeastUpperBound(
InterfaceType first, InterfaceType second) {
// TODO(paulberry): this needs to be deprecated and replaced with a method
// in [TypeSystem], since it relies on the deprecated functionality of
// [DartType.getLeastUpperBound].
if (first.element == second.element) {
return _leastUpperBound(first, second);
}
AnalysisContext context = first.element.context;
return context.typeSystem.getLeastUpperBound(first, second);
}
/**
* Return the "least upper bound" of the given types under the assumption that
* the types have the same element and differ only in terms of the type
* arguments.
*
* The resulting type is composed by comparing the corresponding type
* arguments, keeping those that are the same, and using 'dynamic' for those
* that are different.
*/
static InterfaceType _leastUpperBound(
InterfaceType firstType, InterfaceType secondType) {
ClassElement firstElement = firstType.element;
ClassElement secondElement = secondType.element;
if (firstElement != secondElement) {
throw new ArgumentError('The same elements expected, but '
'$firstElement and $secondElement are given.');
}
if (firstType == secondType) {
return firstType;
}
List<DartType> firstArguments = firstType.typeArguments;
List<DartType> secondArguments = secondType.typeArguments;
int argumentCount = firstArguments.length;
if (argumentCount == 0) {
return firstType;
}
List<DartType> lubArguments = new List<DartType>(argumentCount);
for (int i = 0; i < argumentCount; i++) {
//
// Ideally we would take the least upper bound of the two argument types,
// but this can cause an infinite recursion (such as when finding the
// least upper bound of String and num).
//
if (firstArguments[i] == secondArguments[i]) {
lubArguments[i] = firstArguments[i];
}
if (lubArguments[i] == null) {
lubArguments[i] = DynamicTypeImpl.instance;
}
}
NullabilitySuffix computeNullability() {
NullabilitySuffix first =
(firstType as InterfaceTypeImpl).nullabilitySuffix;
NullabilitySuffix second =
(secondType as InterfaceTypeImpl).nullabilitySuffix;
if (first == NullabilitySuffix.question ||
second == NullabilitySuffix.question) {
return NullabilitySuffix.question;
} else if (first == NullabilitySuffix.star ||
second == NullabilitySuffix.star) {
return NullabilitySuffix.star;
}
return NullabilitySuffix.none;
}
InterfaceTypeImpl lub = new InterfaceTypeImpl(firstElement,
nullabilitySuffix: computeNullability());
lub.typeArguments = lubArguments;
return lub;
}
/**
* Look up the getter with the given [name] in the interfaces
* implemented by the given [targetType], either directly or indirectly.
* Return the element representing the getter that was found, or `null` if
* there is no getter with the given name. The flag [includeTargetType] should
* be `true` if the search should include the target type. The
* [visitedInterfaces] is a set containing all of the interfaces that have
* been examined, used to prevent infinite recursion and to optimize the
* search.
*/
static ExecutableElement _lookUpMemberInInterfaces(
InterfaceType targetType,
bool includeTargetType,
LibraryElement library,
HashSet<ClassElement> visitedInterfaces,
ExecutableElement getMember(InterfaceType type)) {
// TODO(brianwilkerson) This isn't correct. Section 8.1.1 of the
// specification (titled "Inheritance and Overriding" under "Interfaces")
// describes a much more complex scheme for finding the inherited member.
// We need to follow that scheme. The code below should cover the 80% case.
ClassElement targetClass = targetType.element;
if (!visitedInterfaces.add(targetClass)) {
return null;
}
if (includeTargetType) {
ExecutableElement member = getMember(targetType);
if (member != null && member.isAccessibleIn(library)) {
return member;
}
}
for (InterfaceType interfaceType in targetType.interfaces) {
ExecutableElement member = _lookUpMemberInInterfaces(
interfaceType, true, library, visitedInterfaces, getMember);
if (member != null) {
return member;
}
}
for (InterfaceType constraint in targetType.superclassConstraints) {
ExecutableElement member = _lookUpMemberInInterfaces(
constraint, true, library, visitedInterfaces, getMember);
if (member != null) {
return member;
}
}
for (InterfaceType mixinType in targetType.mixins.reversed) {
ExecutableElement member = _lookUpMemberInInterfaces(
mixinType, true, library, visitedInterfaces, getMember);
if (member != null) {
return member;
}
}
InterfaceType superclass = targetType.superclass;
if (superclass == null) {
return null;
}
return _lookUpMemberInInterfaces(
superclass, true, library, visitedInterfaces, getMember);
}
}
/**
* The abstract class `TypeImpl` implements the behavior common to objects
* representing the declared type of elements in the element model.
*/
abstract class TypeImpl implements DartType {
/**
* The element representing the declaration of this type, or `null` if the
* type has not, or cannot, be associated with an element.
*/
final Element _element;
/**
* The name of this type, or `null` if the type does not have a name.
*/
final String name;
/**
* Initialize a newly created type to be declared by the given [element] and
* to have the given [name].
*/
TypeImpl(this._element, this.name);
@override
String get displayName => name;
@override
Element get element => _element;
@override
bool get isBottom => false;
@override
bool get isDartAsyncFuture => false;
@override
bool get isDartAsyncFutureOr => false;
@override
bool get isDartCoreBool => false;
@override
bool get isDartCoreDouble => false;
@override
bool get isDartCoreFunction => false;
@override
bool get isDartCoreInt => false;
@override
bool get isDartCoreList => false;
@override
bool get isDartCoreMap => false;
@override
bool get isDartCoreNull => false;
@override
bool get isDartCoreNum => false;
@override
bool get isDartCoreObject => false;
@override
bool get isDartCoreSet => false;
@override
bool get isDartCoreString => false;
@override
bool get isDartCoreSymbol => false;
@override
bool get isDynamic => false;
@override
bool get isObject => false;
@override
bool get isVoid => false;
/**
* Return the nullability suffix of this type.
*/
NullabilitySuffix get nullabilitySuffix;
/**
* Append a textual representation of this type to the given [buffer]. The set
* of [visitedTypes] is used to prevent infinite recursion.
*/
void appendTo(StringBuffer buffer, Set<TypeImpl> visitedTypes,
{bool withNullability = false}) {
if (visitedTypes.add(this)) {
if (name == null) {
buffer.write("<unnamed type>");
} else {
buffer.write(name);
}
visitedTypes.remove(this);
} else {
buffer.write('<recursive>');
}
if (withNullability) {
_appendNullability(buffer);
}
}
@override
DartType flattenFutures(TypeSystem typeSystem) => this;
/**
* Return `true` if this type is assignable to the given [type] (written in
* the spec as "T <=> S", where T=[this] and S=[type]).
*
* The sets [thisExpansions] and [typeExpansions], if given, are the sets of
* function type aliases that have been expanded so far in the process of
* reaching [this] and [type], respectively. These are used to avoid
* infinite regress when analyzing invalid code; since the language spec
* forbids a typedef from referring to itself directly or indirectly, we can
* use these as sets of function type aliases that don't need to be expanded.
*/
@override
bool isAssignableTo(DartType type) {
// An interface type T may be assigned to a type S, written T <=> S, iff
// either T <: S or S <: T.
return isSubtypeOf(type) || type.isSubtypeOf(this);
}
@override
bool isEquivalentTo(DartType other) => this == other;
/**
* Return `true` if this type is more specific than the given [type] (written
* in the spec as "T << S", where T=[this] and S=[type]).
*
* If [withDynamic] is `true`, then "dynamic" should be considered as a
* subtype of any type (as though "dynamic" had been replaced with bottom).
*
* The set [visitedElements], if given, is the set of classes and type
* parameters that have been visited so far while examining the class
* hierarchy of [this]. This is used to avoid infinite regress when
* analyzing invalid code; since the language spec forbids loops in the class
* hierarchy, we can use this as a set of classes that don't need to be
* examined when walking the class hierarchy.
*/
@override
bool isMoreSpecificThan(DartType type,
[bool withDynamic = false, Set<Element> visitedElements]);
/**
* Return `true` if this type is a subtype of the given [type] (written in
* the spec as "T <: S", where T=[this] and S=[type]).
*
* The sets [thisExpansions] and [typeExpansions], if given, are the sets of
* function type aliases that have been expanded so far in the process of
* reaching [this] and [type], respectively. These are used to avoid
* infinite regress when analyzing invalid code; since the language spec
* forbids a typedef from referring to itself directly or indirectly, we can
* use these as sets of function type aliases that don't need to be expanded.
*/
@override
bool isSubtypeOf(DartType type) {
// For non-function types, T <: S iff [_|_/dynamic]T << S.
return isMoreSpecificThan(type, true);
}
@override
bool isSupertypeOf(DartType type) => type.isSubtypeOf(this);
/**
* Create a new [TypeImpl] that is identical to [this] except that when
* visiting type parameters, function parameter types, and function return
* types, function types listed in [prune] will not be expanded. This is
* used to avoid creating infinite types in the presence of circular
* typedefs.
*
* If [prune] is null, then [this] is returned unchanged.
*
* Only legal to call on a [TypeImpl] that is not already subject to pruning.
*/
TypeImpl pruned(List<FunctionTypeAliasElement> prune);
/// Replaces all covariant occurrences of `dynamic`, `Object`, and `void` with
/// `Null` and all contravariant occurrences of `Null` with `Object`.
///
/// The boolean `isCovariant` indicates whether this type is in covariant or
/// contravariant position.
DartType replaceTopAndBottom(TypeProvider typeProvider,
{bool isCovariant = true});
@override
DartType resolveToBound(DartType objectType) => this;
/**
* Return the type resulting from substituting the given [argumentTypes] for
* the given [parameterTypes] in this type.
*
* In all classes derived from [TypeImpl], a new optional argument
* [prune] is added. If specified, it is a list of function typdefs
* which should not be expanded. This is used to avoid creating infinite
* types in response to self-referential typedefs.
*/
@override
DartType substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]);
@override
String toString({bool withNullability = false}) {
StringBuffer buffer = new StringBuffer();
appendTo(buffer, new Set.identity(), withNullability: withNullability);
return buffer.toString();
}
/**
* Return the same type, but with the given [nullabilitySuffix].
*
* If the nullability of `this` already matches [nullabilitySuffix], `this`
* is returned.
*
* Note: this method just does low-level manipulations of the underlying type,
* so it is what you want if you are constructing a fresh type and want it to
* have the correct nullability suffix, but it is generally *not* what you
* want if you're manipulating existing types. For manipulating existing
* types, please use the methods in [TypeSystem].
*/
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix);
void _appendNullability(StringBuffer buffer) {
if (isDynamic || isVoid) {
// These types don't have nullability variations, so don't append
// anything.
return;
}
switch (nullabilitySuffix) {
case NullabilitySuffix.question:
buffer.write('?');
break;
case NullabilitySuffix.star:
buffer.write('*');
break;
case NullabilitySuffix.none:
break;
}
}
/**
* Return `true` if corresponding elements of the [first] and [second] lists
* of type arguments are all equal.
*/
static bool equalArrays(List<DartType> first, List<DartType> second) {
if (first.length != second.length) {
return false;
}
for (int i = 0; i < first.length; i++) {
if (first[i] == null) {
AnalysisEngine.instance.logger
.logInformation('Found null type argument in TypeImpl.equalArrays');
return second[i] == null;
} else if (second[i] == null) {
AnalysisEngine.instance.logger
.logInformation('Found null type argument in TypeImpl.equalArrays');
return false;
}
if (first[i] != second[i]) {
return false;
}
}
return true;
}
/**
* Return a list containing the results of using the given [argumentTypes] and
* [parameterTypes] to perform a substitution on all of the given [types].
*
* If [prune] is specified, it is a list of function typdefs which should not
* be expanded. This is used to avoid creating infinite types in response to
* self-referential typedefs.
*/
static List<DartType> substitute(List<DartType> types,
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) {
int length = types.length;
if (length == 0) {
return types;
}
List<DartType> newTypes = new List<DartType>(length);
for (int i = 0; i < length; i++) {
newTypes[i] = (types[i] as TypeImpl)
.substitute2(argumentTypes, parameterTypes, prune);
}
return newTypes;
}
}
/**
* A concrete implementation of a [TypeParameterType].
*/
class TypeParameterTypeImpl extends TypeImpl implements TypeParameterType {
@override
final NullabilitySuffix nullabilitySuffix;
/**
* Initialize a newly created type parameter type to be declared by the given
* [element] and to have the given name.
*/
TypeParameterTypeImpl(TypeParameterElement element,
{this.nullabilitySuffix = NullabilitySuffix.star})
: super(element, element.name);
@override
DartType get bound => element.bound ?? DynamicTypeImpl.instance;
@override
ElementLocation get definition => element.location;
@override
TypeParameterElement get element => super.element as TypeParameterElement;
@override
int get hashCode => element.hashCode;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
return other is TypeParameterTypeImpl && other.element == element;
}
@override
bool isMoreSpecificThan(DartType s,
[bool withDynamic = false, Set<Element> visitedElements]) {
//
// A type T is more specific than a type S, written T << S,
// if one of the following conditions is met:
//
// Reflexivity: T is S.
//
if (this == s) {
return true;
}
// S is dynamic.
//
if (s.isDynamic) {
return true;
}
//
// T is a type parameter and S is the upper bound of T.
//
TypeImpl bound = element.bound;
if (s == bound) {
return true;
}
//
// T is a type parameter and S is Object.
//
if (s.isObject) {
return true;
}
// We need upper bound to continue.
if (bound == null) {
return false;
}
//
// Transitivity: T << U and U << S.
//
// First check for infinite loops
if (element == null) {
return false;
}
if (visitedElements == null) {
visitedElements = new HashSet<Element>();
} else if (visitedElements.contains(element)) {
return false;
}
visitedElements.add(element);
try {
return bound.isMoreSpecificThan(s, withDynamic, visitedElements);
} finally {
visitedElements.remove(element);
}
}
@override
bool isSubtypeOf(DartType type) => isMoreSpecificThan(type, true);
@override
TypeImpl pruned(List<FunctionTypeAliasElement> prune) => this;
@override
DartType replaceTopAndBottom(TypeProvider typeProvider,
{bool isCovariant = true}) {
return this;
}
@override
DartType resolveToBound(DartType objectType) {
if (element.bound == null) {
return objectType;
}
NullabilitySuffix newNullabilitySuffix;
if (nullabilitySuffix == NullabilitySuffix.question ||
(element.bound as TypeImpl).nullabilitySuffix ==
NullabilitySuffix.question) {
newNullabilitySuffix = NullabilitySuffix.question;
} else if (nullabilitySuffix == NullabilitySuffix.star ||
(element.bound as TypeImpl).nullabilitySuffix ==
NullabilitySuffix.star) {
newNullabilitySuffix = NullabilitySuffix.star;
} else {
newNullabilitySuffix = NullabilitySuffix.none;
}
return (element.bound.resolveToBound(objectType) as TypeImpl)
.withNullability(newNullabilitySuffix);
}
@override
DartType substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) {
int length = parameterTypes.length;
for (int i = 0; i < length; i++) {
var parameterType = parameterTypes[i];
if (parameterType is TypeParameterTypeImpl && parameterType == this) {
TypeImpl argumentType = argumentTypes[i];
// TODO(scheglov) It should not happen, but sometimes arguments are null.
if (argumentType == null) {
return argumentType;
}
// TODO(scheglov) Proposed substitution rules for nullability.
NullabilitySuffix resultNullability;
NullabilitySuffix parameterNullability =
parameterType.nullabilitySuffix;
NullabilitySuffix argumentNullability = argumentType.nullabilitySuffix;
if (parameterNullability == NullabilitySuffix.none) {
if (argumentNullability == NullabilitySuffix.question ||
nullabilitySuffix == NullabilitySuffix.question) {
resultNullability = NullabilitySuffix.question;
} else if (argumentNullability == NullabilitySuffix.star ||
nullabilitySuffix == NullabilitySuffix.star) {
resultNullability = NullabilitySuffix.star;
} else {
resultNullability = NullabilitySuffix.none;
}
} else if (parameterNullability == NullabilitySuffix.star) {
if (argumentNullability == NullabilitySuffix.question ||
nullabilitySuffix == NullabilitySuffix.question) {
resultNullability = NullabilitySuffix.question;
} else {
resultNullability = argumentNullability;
}
} else {
// We should never be substituting for `T?`.
throw new StateError('Tried to substitute for T?');
}
return argumentType.withNullability(resultNullability);
}
}
return this;
}
@override
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) {
if (this.nullabilitySuffix == nullabilitySuffix) return this;
return TypeParameterTypeImpl(element, nullabilitySuffix: nullabilitySuffix);
}
/**
* Return a list containing the type parameter types defined by the given
* array of type parameter elements ([typeParameters]).
*/
static List<TypeParameterType> getTypes(
List<TypeParameterElement> typeParameters) {
int count = typeParameters.length;
if (count == 0) {
return const <TypeParameterType>[];
}
List<TypeParameterType> types = new List<TypeParameterType>(count);
for (int i = 0; i < count; i++) {
types[i] = typeParameters[i].type;
}
return types;
}
}
/**
* The type `void`.
*/
abstract class VoidType implements DartType {
@override
VoidType substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes);
}
/**
* A concrete implementation of a [VoidType].
*/
class VoidTypeImpl extends TypeImpl implements VoidType {
/**
* The unique instance of this class, with indeterminate nullability.
*/
static final VoidTypeImpl instance = new VoidTypeImpl._();
/**
* Prevent the creation of instances of this class.
*/
VoidTypeImpl._() : super(null, Keyword.VOID.lexeme);
@override
int get hashCode => 2;
@override
bool get isVoid => true;
@override
NullabilitySuffix get nullabilitySuffix => NullabilitySuffix.none;
@override
bool operator ==(Object object) => identical(object, this);
@override
bool isMoreSpecificThan(DartType type,
[bool withDynamic = false, Set<Element> visitedElements]) =>
isSubtypeOf(type);
@override
bool isSubtypeOf(DartType type) {
// The only subtype relations that pertain to void are therefore:
// void <: void (by reflexivity)
// bottom <: void (as bottom is a subtype of all types).
// void <: dynamic (as dynamic is a supertype of all types)
return identical(type, this) || type.isDynamic;
}
@override
TypeImpl pruned(List<FunctionTypeAliasElement> prune) => this;
@override
DartType replaceTopAndBottom(TypeProvider typeProvider,
{bool isCovariant = true}) {
if (isCovariant) {
return typeProvider.nullType;
} else {
return this;
}
}
@override
VoidTypeImpl substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) =>
this;
@override
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) {
// The void type is always nullable.
return this;
}
}
/**
* A [FunctionTypeImpl] that is lazily built from a [FunctionTypedElement] in
* the element model.
*/
class _FunctionTypeImplLazy extends FunctionTypeImpl {
/**
* The list of [typeArguments].
*/
List<DartType> _typeArguments;
/**
* The list of [typeParameters], if it has been computed already. Otherwise
* `null`.
*/
List<TypeParameterElement> _typeParameters;
/**
* The return type of the function, or `null` if the return type should be
* accessed through the element.
*/
final DartType _returnType;
/**
* The parameters to the function, or `null` if the parameters should be
* accessed through the element.
*/
final List<ParameterElement> _parameters;
/**
* True if this type is the result of instantiating type parameters (and thus
* any type parameters bound by the typedef should be considered part of
* [typeParameters] rather than [typeFormals]).
*/
final bool _isInstantiated;
@override
final List<FunctionTypeAliasElement> prunedTypedefs;
/**
* Private constructor.
*/
_FunctionTypeImplLazy._(
FunctionTypedElement element,
String name,
this.prunedTypedefs,
this._typeArguments,
this._returnType,
this._parameters,
this._isInstantiated,
{NullabilitySuffix nullabilitySuffix = NullabilitySuffix.star})
: _typeParameters = null,
super._(element, name, nullabilitySuffix);
/**
* Return the base parameter elements of this function element.
*/
List<ParameterElement> get baseParameters =>
_parameters ?? element.parameters;
/**
* Return the return type defined by this function's element.
*/
DartType get baseReturnType => _returnType ?? element.returnType;
@override
bool get isInstantiated => _isInstantiated;
@override
List<FunctionTypeAliasElement> get newPrune {
Element element = this.element;
if (element is GenericFunctionTypeElement) {
element = (element as GenericFunctionTypeElement).enclosingElement;
}
if (element is FunctionTypeAliasElement && !element.isSynthetic) {
// This typedef should be pruned, along with anything that was previously
// pruned.
if (prunedTypedefs == null) {
return <FunctionTypeAliasElement>[element];
} else {
return new List<FunctionTypeAliasElement>.from(prunedTypedefs)
..add(element);
}
} else {
// This is not a typedef, so nothing additional needs to be pruned.
return prunedTypedefs;
}
}
@override
List<String> get normalParameterNames {
return baseParameters
.where((parameter) => parameter.isRequiredPositional)
.map((parameter) => parameter.name)
.toList();
}
@override
List<String> get optionalParameterNames {
return baseParameters
.where((parameter) => parameter.isOptionalPositional)
.map((parameter) => parameter.name)
.toList();
}
@override
List<ParameterElement> get parameters {
var substitution = Substitution.fromPairs(typeParameters, typeArguments);
List<ParameterElement> baseParameters = this.baseParameters;
// no parameters, quick return
int parameterCount = baseParameters.length;
if (parameterCount == 0) {
return baseParameters;
}
// create specialized parameters
var specializedParams = new List<ParameterElement>(parameterCount);
var parameterTypes = TypeParameterTypeImpl.getTypes(typeParameters);
for (int i = 0; i < parameterCount; i++) {
var parameter = baseParameters[i];
if (parameter?.type == null) {
specializedParams[i] = parameter;
continue;
}
// Check if parameter type depends on defining type type arguments, or
// if it needs to be pruned.
if (parameter is FieldFormalParameterElement) {
// TODO(jmesserly): this seems like it won't handle pruning correctly.
specializedParams[i] =
new FieldFormalParameterMember(parameter, substitution);
continue;
}
var baseType = parameter.type as TypeImpl;
TypeImpl type;
if (typeArguments.isEmpty ||
typeArguments.length != typeParameters.length) {
type = baseType.pruned(newPrune);
} else {
type = baseType.substitute2(typeArguments, parameterTypes, newPrune);
}
specializedParams[i] = identical(type, baseType)
? parameter
: new ParameterMember(parameter, substitution, type);
}
return specializedParams;
}
@override
DartType get returnType {
DartType baseReturnType = this.baseReturnType;
if (baseReturnType == null) {
// TODO(brianwilkerson) This is a patch. The return type should never be
// null and we need to understand why it is and fix it.
return DynamicTypeImpl.instance;
}
// If there are no arguments to substitute, or if the arguments size doesn't
// match the parameter size, return the base return type.
if (typeArguments.isEmpty ||
typeArguments.length != typeParameters.length) {
return (baseReturnType as TypeImpl).pruned(newPrune);
}
return (baseReturnType as TypeImpl).substitute2(typeArguments,
TypeParameterTypeImpl.getTypes(typeParameters), newPrune);
}
/**
* A list containing the actual types of the type arguments.
*/
List<DartType> get typeArguments {
if (_typeArguments == null) {
// TODO(jmesserly): reuse TypeParameterTypeImpl.getTypes once we can
// make it generic, which will allow it to return List<DartType> instead
// of List<TypeParameterType>.
if (typeParameters.isEmpty) {
_typeArguments = const <DartType>[];
} else {
_typeArguments = new List<DartType>.from(
typeParameters.map((t) => t.type),
growable: false);
}
}
return _typeArguments;
}
@override
List<TypeParameterElement> get typeFormals {
if (_isInstantiated || element == null) {
return const <TypeParameterElement>[];
}
List<TypeParameterElement> baseTypeFormals = element.typeParameters;
int formalCount = baseTypeFormals.length;
if (formalCount == 0) {
return const <TypeParameterElement>[];
}
// Create type formals with specialized bounds.
// For example `<U extends T>` where T comes from an outer scope.
return TypeParameterMember.from(baseTypeFormals, this);
}
@override
List<TypeParameterElement> get typeParameters {
if (_typeParameters == null) {
// Combine the generic type variables from all enclosing contexts, except
// for this generic function's type variables. Those variables are
// tracked in [boundTypeParameters].
_typeParameters = <TypeParameterElement>[];
Element e = element;
while (e != null) {
// If a static method, skip the enclosing class type parameters.
if (e is MethodElement && e.isStatic) {
e = e.enclosingElement;
}
e = e.enclosingElement;
if (e is TypeParameterizedElement) {
_typeParameters.addAll(e.typeParameters);
}
}
if (_isInstantiated) {
// Once the type has been instantiated, type parameters defined at the
// site of the declaration of the method are no longer considered part
// [boundTypeParameters]; they are part of [typeParameters].
List<TypeParameterElement> parametersToAdd = element?.typeParameters;
if (parametersToAdd != null) {
_typeParameters.addAll(parametersToAdd);
}
}
}
return _typeParameters;
}
@override
FunctionTypeImpl instantiate(List<DartType> argumentTypes) {
if (argumentTypes.length != typeFormals.length) {
throw new ArgumentError(
"argumentTypes.length (${argumentTypes.length}) != "
"typeFormals.length (${typeFormals.length})");
}
if (argumentTypes.isEmpty) {
return this;
}
// Given:
// {U/T} <S> T -> S
// Where {U/T} represents the typeArguments (U) and typeParameters (T) list,
// and <S> represents the typeFormals.
//
// Now instantiate([V]), and the result should be:
// {U/T, V/S} T -> S.
List<DartType> newTypeArgs = <DartType>[];
newTypeArgs.addAll(typeArguments);
newTypeArgs.addAll(argumentTypes);
return new _FunctionTypeImplLazy._(element, name, prunedTypedefs,
newTypeArgs, _returnType, _parameters, true,
nullabilitySuffix: nullabilitySuffix);
}
@override
FunctionTypeImpl pruned(List<FunctionTypeAliasElement> prune) {
if (prune == null) {
return this;
} else if (prune.contains(element) ||
prune.contains(element.enclosingElement)) {
// Circularity found. Prune the type declaration.
return new CircularFunctionTypeImpl();
} else {
// There should never be a reason to prune a type that has already been
// pruned, since pruning is only done when expanding a function type
// alias, and function type aliases are always expanded by starting with
// base types.
assert(this.prunedTypedefs == null);
List<DartType> typeArgs = typeArguments
.map((DartType t) => (t as TypeImpl).pruned(prune))
.toList(growable: false);
return new _FunctionTypeImplLazy._(element, name, prune, typeArgs,
_returnType, _parameters, _isInstantiated,
nullabilitySuffix: nullabilitySuffix);
}
}
@override
FunctionType substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) {
if (argumentTypes.length != parameterTypes.length) {
throw new ArgumentError(
"argumentTypes.length (${argumentTypes.length}) != parameterTypes.length (${parameterTypes.length})");
}
Element element = this.element;
Element forCircularity = this.element;
if (element is GenericFunctionTypeElement &&
element.enclosingElement is FunctionTypeAliasElement) {
forCircularity = element.enclosingElement;
}
if (prune != null && prune.contains(forCircularity)) {
// Circularity found. Prune the type declaration.
return new CircularFunctionTypeImpl();
}
if (argumentTypes.isEmpty) {
return this.pruned(prune);
}
List<DartType> typeArgs =
TypeImpl.substitute(typeArguments, argumentTypes, parameterTypes);
return new _FunctionTypeImplLazy._(element, name, prune, typeArgs,
_returnType, _parameters, _isInstantiated,
nullabilitySuffix: nullabilitySuffix);
}
@override
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) {
if (this.nullabilitySuffix == nullabilitySuffix) return this;
return _FunctionTypeImplLazy._(element, name, prunedTypedefs,
_typeArguments, _returnType, _parameters, _isInstantiated,
nullabilitySuffix: nullabilitySuffix);
}
@override
void _forEachParameterType(
ParameterKind kind, callback(String name, DartType type)) {
List<ParameterElement> parameters = baseParameters;
if (parameters.isEmpty) {
return;
}
List<DartType> typeParameters =
TypeParameterTypeImpl.getTypes(this.typeParameters);
int length = parameters.length;
for (int i = 0; i < length; i++) {
ParameterElement parameter = parameters[i];
// ignore: deprecated_member_use_from_same_package
if (parameter.parameterKind == kind) {
TypeImpl type = parameter.type ?? DynamicTypeImpl.instance;
if (typeArguments.isNotEmpty &&
typeArguments.length == typeParameters.length) {
type = type.substitute2(typeArguments, typeParameters, newPrune);
} else {
type = type.pruned(newPrune);
}
callback(parameter.name, type);
}
}
}
}
/// A [FunctionTypeImpl] that is not associated with any element in the element
/// model.
///
/// In contrast to [_FunctionTypeImplLazy], all of the properties of a
/// [_FunctionTypeImplStrict] are known at construction time.
class _FunctionTypeImplStrict extends FunctionTypeImpl {
@override
final DartType returnType;
@override
final List<TypeParameterElement> typeFormals;
@override
final List<ParameterElement> parameters;
@override
final List<DartType> typeArguments;
_FunctionTypeImplStrict._(this.returnType, this.typeFormals, this.parameters,
{Element element,
List<DartType> typeArguments,
NullabilitySuffix nullabilitySuffix = NullabilitySuffix.star})
: typeArguments = typeArguments ?? const <DartType>[],
super._(element, null, nullabilitySuffix);
@override
List<TypeParameterElement> get boundTypeParameters => typeFormals;
@override
FunctionTypedElement get element {
var element = super.element;
if (element is GenericTypeAliasElement) {
return element.function;
}
return element;
}
@override
bool get isInstantiated => throw new UnimplementedError('TODO(paulberry)');
@override
List<FunctionTypeAliasElement> get newPrune => const [];
@override
List<String> get normalParameterNames => parameters
.where((p) => p.isRequiredPositional)
.map((p) => p.name)
.toList();
@override
List<String> get optionalParameterNames => parameters
.where((p) => p.isOptionalPositional)
.map((p) => p.name)
.toList();
@override
List<FunctionTypeAliasElement> get prunedTypedefs => const [];
@override
List<TypeParameterElement> get typeParameters => const [] /*TODO(paulberry)*/;
@override
FunctionTypeImpl instantiate(List<DartType> argumentTypes) {
if (argumentTypes.length != typeFormals.length) {
throw new ArgumentError(
"argumentTypes.length (${argumentTypes.length}) != "
"typeFormals.length (${typeFormals.length})");
}
if (argumentTypes.isEmpty) {
return this;
}
var substitution = Substitution.fromPairs(typeFormals, argumentTypes);
ParameterElement transformParameter(ParameterElement p) {
var type = p.type;
var newType = substitution.substituteType(type);
if (identical(newType, type)) return p;
return new ParameterElementImpl.synthetic(
p.name,
newType,
// ignore: deprecated_member_use_from_same_package
p.parameterKind)
..isExplicitlyCovariant = p.isCovariant;
}
return new _FunctionTypeImplStrict._(
substitution.substituteType(returnType),
const [],
_transformOrShare(parameters, transformParameter),
nullabilitySuffix: nullabilitySuffix);
}
@override
TypeImpl pruned(List<FunctionTypeAliasElement> prune) => this;
@override
FunctionType substitute2(
List<DartType> argumentTypes, List<DartType> parameterTypes,
[List<FunctionTypeAliasElement> prune]) {
if (argumentTypes.length != parameterTypes.length) {
throw new ArgumentError(
"argumentTypes.length (${argumentTypes.length}) != "
"parameterTypes.length (${parameterTypes.length})");
}
var substitution = Substitution.fromPairs(
parameterTypes.map<TypeParameterElement>((t) => t.element).toList(),
argumentTypes,
);
return substitution.substituteType(this);
}
@override
TypeImpl withNullability(NullabilitySuffix nullabilitySuffix) {
if (this.nullabilitySuffix == nullabilitySuffix) return this;
return _FunctionTypeImplStrict._(returnType, typeFormals, parameters,
element: element,
typeArguments: typeArguments,
nullabilitySuffix: nullabilitySuffix);
}
@override
void _forEachParameterType(
ParameterKind kind, Function(String name, DartType type) callback) {
for (var parameter in parameters) {
// ignore: deprecated_member_use_from_same_package
if (parameter.parameterKind == kind) {
callback(parameter.name, parameter.type);
}
}
}
}
| 0 |
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart | mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/analyzer/src/dart/element/handle.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:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
import 'package:meta/meta.dart';
/**
* A handle to a [ClassElement].
*/
class ClassElementHandle extends ElementHandle implements ClassElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
ClassElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
List<PropertyAccessorElement> get accessors => actualElement.accessors;
@override
ClassElement get actualElement => super.actualElement as ClassElement;
@override
List<InterfaceType> get allSupertypes => actualElement.allSupertypes;
@override
List<ConstructorElement> get constructors => actualElement.constructors;
@override
List<FieldElement> get fields => actualElement.fields;
@override
bool get hasJS => actualElement.hasJS;
@override
bool get hasLiteral => actualElement.hasLiteral;
@override
bool get hasNonFinalField => actualElement.hasNonFinalField;
@override
bool get hasReferenceToSuper => actualElement.hasReferenceToSuper;
@override
bool get hasRequired => actualElement.hasRequired;
@override
bool get hasSealed => actualElement.hasSealed;
@override
bool get hasStaticMember => actualElement.hasStaticMember;
@override
List<InterfaceType> get interfaces => actualElement.interfaces;
@override
bool get isAbstract => actualElement.isAbstract;
@override
bool get isDartCoreObject => actualElement.isDartCoreObject;
@override
bool get isEnum => actualElement.isEnum;
@override
bool get isJS => actualElement.hasJS;
@override
bool get isMixin => actualElement.isMixin;
@override
bool get isMixinApplication => actualElement.isMixinApplication;
@override
bool get isOrInheritsProxy => actualElement.isOrInheritsProxy;
@override
bool get isProxy => actualElement.isProxy;
@override
bool get isRequired => actualElement.hasRequired;
@override
bool get isSimplyBounded => actualElement.isSimplyBounded;
@override
bool get isValidMixin => actualElement.isValidMixin;
@override
ElementKind get kind => ElementKind.CLASS;
@override
List<MethodElement> get methods => actualElement.methods;
@override
List<InterfaceType> get mixins => actualElement.mixins;
@override
List<InterfaceType> get superclassConstraints =>
actualElement.superclassConstraints;
@override
InterfaceType get supertype => actualElement.supertype;
@override
InterfaceType get thisType => actualElement.thisType;
@override
InterfaceType get type => actualElement.type;
@override
List<TypeParameterElement> get typeParameters => actualElement.typeParameters;
@override
ConstructorElement get unnamedConstructor => actualElement.unnamedConstructor;
@deprecated
@override
NamedCompilationUnitMember computeNode() => super.computeNode();
@override
FieldElement getField(String fieldName) => actualElement.getField(fieldName);
@override
PropertyAccessorElement getGetter(String getterName) =>
actualElement.getGetter(getterName);
@override
MethodElement getMethod(String methodName) =>
actualElement.getMethod(methodName);
@override
ConstructorElement getNamedConstructor(String name) =>
actualElement.getNamedConstructor(name);
@override
PropertyAccessorElement getSetter(String setterName) =>
actualElement.getSetter(setterName);
@override
InterfaceType instantiate({
@required List<DartType> typeArguments,
@required NullabilitySuffix nullabilitySuffix,
}) {
return actualElement.instantiate(
typeArguments: typeArguments,
nullabilitySuffix: nullabilitySuffix,
);
}
@override
MethodElement lookUpConcreteMethod(
String methodName, LibraryElement library) =>
actualElement.lookUpConcreteMethod(methodName, library);
@override
PropertyAccessorElement lookUpGetter(
String getterName, LibraryElement library) =>
actualElement.lookUpGetter(getterName, library);
@override
PropertyAccessorElement lookUpInheritedConcreteGetter(
String methodName, LibraryElement library) =>
actualElement.lookUpInheritedConcreteGetter(methodName, library);
@override
MethodElement lookUpInheritedConcreteMethod(
String methodName, LibraryElement library) =>
actualElement.lookUpInheritedConcreteMethod(methodName, library);
@override
PropertyAccessorElement lookUpInheritedConcreteSetter(
String methodName, LibraryElement library) =>
actualElement.lookUpInheritedConcreteSetter(methodName, library);
@override
MethodElement lookUpInheritedMethod(
String methodName, LibraryElement library) {
return actualElement.lookUpInheritedMethod(methodName, library);
}
@override
MethodElement lookUpMethod(String methodName, LibraryElement library) =>
actualElement.lookUpMethod(methodName, library);
@override
PropertyAccessorElement lookUpSetter(
String setterName, LibraryElement library) =>
actualElement.lookUpSetter(setterName, library);
}
/**
* A handle to a [CompilationUnitElement].
*/
class CompilationUnitElementHandle extends ElementHandle
implements CompilationUnitElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
CompilationUnitElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
List<PropertyAccessorElement> get accessors => actualElement.accessors;
@override
CompilationUnitElement get actualElement =>
super.actualElement as CompilationUnitElement;
@override
LibraryElement get enclosingElement =>
super.enclosingElement as LibraryElement;
@override
List<ClassElement> get enums => actualElement.enums;
@override
List<ExtensionElement> get extensions => actualElement.extensions;
@override
List<FunctionElement> get functions => actualElement.functions;
@override
List<FunctionTypeAliasElement> get functionTypeAliases =>
actualElement.functionTypeAliases;
@override
bool get hasLoadLibraryFunction => actualElement.hasLoadLibraryFunction;
@override
ElementKind get kind => ElementKind.COMPILATION_UNIT;
@override
LineInfo get lineInfo => actualElement.lineInfo;
@override
List<ClassElement> get mixins => actualElement.mixins;
@override
Source get source => actualElement.source;
@override
List<TopLevelVariableElement> get topLevelVariables =>
actualElement.topLevelVariables;
@override
List<ClassElement> get types => actualElement.types;
@override
String get uri => actualElement.uri;
@override
int get uriEnd => actualElement.uriEnd;
@override
int get uriOffset => actualElement.uriOffset;
@deprecated
@override
CompilationUnit computeNode() => actualElement.computeNode();
@override
ClassElement getEnum(String enumName) => actualElement.getEnum(enumName);
@override
ClassElement getType(String className) => actualElement.getType(className);
}
/**
* A handle to a [ConstructorElement].
*/
class ConstructorElementHandle extends ExecutableElementHandle
implements ConstructorElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
ConstructorElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
ConstructorElement get actualElement =>
super.actualElement as ConstructorElement;
@override
ClassElement get enclosingElement => actualElement.enclosingElement;
@override
bool get isConst => actualElement.isConst;
@override
bool get isConstantEvaluated => actualElement.isConstantEvaluated;
@override
bool get isDefaultConstructor => actualElement.isDefaultConstructor;
@override
bool get isFactory => actualElement.isFactory;
@override
ElementKind get kind => ElementKind.CONSTRUCTOR;
@override
int get nameEnd => actualElement.nameEnd;
@override
int get periodOffset => actualElement.periodOffset;
@override
ConstructorElement get redirectedConstructor =>
actualElement.redirectedConstructor;
@deprecated
@override
ConstructorDeclaration computeNode() => actualElement.computeNode();
}
/**
* A handle to an [Element].
*/
abstract class ElementHandle implements Element {
/**
* The unique integer identifier of this element.
*/
final int id = 0;
/**
* The [ElementResynthesizer] which will be used to resynthesize elements on
* demand.
*/
final ElementResynthesizer _resynthesizer;
/**
* The location of this element, used to reconstitute the element if it has
* not yet been resynthesized.
*/
final ElementLocation _location;
/**
* A reference to the element being referenced by this handle, or `null` if
* the element has not yet been resynthesized.
*/
Element _elementReference;
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
ElementHandle(this._resynthesizer, this._location);
/**
* Return the element being represented by this handle, reconstituting the
* element if the reference has been set to `null`.
*/
Element get actualElement {
if (_elementReference == null) {
_elementReference = _resynthesizer.getElement(_location);
}
return _elementReference;
}
@override
AnalysisContext get context => _resynthesizer.context;
@override
String get displayName => actualElement.displayName;
@override
String get documentationComment => actualElement.documentationComment;
@override
Element get enclosingElement => actualElement.enclosingElement;
@override
bool get hasAlwaysThrows => actualElement.hasAlwaysThrows;
@override
bool get hasDeprecated => actualElement.hasDeprecated;
@override
bool get hasFactory => actualElement.hasFactory;
@override
int get hashCode => _location.hashCode;
@override
bool get hasIsTest => actualElement.hasIsTest;
@override
bool get hasIsTestGroup => actualElement.hasIsTestGroup;
@override
bool get hasJS => actualElement.hasJS;
@override
bool get hasLiteral => actualElement.hasLiteral;
@override
bool get hasMustCallSuper => actualElement.hasMustCallSuper;
@override
bool get hasOptionalTypeArgs => actualElement.hasOptionalTypeArgs;
@override
bool get hasOverride => actualElement.hasOverride;
@override
bool get hasProtected => actualElement.hasProtected;
@override
bool get hasRequired => actualElement.hasRequired;
@override
bool get hasSealed => actualElement.hasSealed;
@override
bool get hasVisibleForTemplate => actualElement.hasVisibleForTemplate;
@override
bool get hasVisibleForTesting => actualElement.hasVisibleForTesting;
@override
bool get isAlwaysThrows => actualElement.hasAlwaysThrows;
@override
bool get isDeprecated => actualElement.hasDeprecated;
@override
bool get isFactory => actualElement.hasFactory;
@override
bool get isJS => actualElement.hasJS;
@override
bool get isOverride => actualElement.hasOverride;
@override
bool get isPrivate => actualElement.isPrivate;
@override
bool get isProtected => actualElement.hasProtected;
@override
bool get isPublic => actualElement.isPublic;
@override
bool get isRequired => actualElement.hasRequired;
@override
bool get isSynthetic => actualElement.isSynthetic;
@override
bool get isVisibleForTesting => actualElement.hasVisibleForTesting;
@override
LibraryElement get library =>
getAncestor((element) => element is LibraryElement);
@override
Source get librarySource => actualElement.librarySource;
@override
ElementLocation get location => _location;
@override
List<ElementAnnotation> get metadata => actualElement.metadata;
@override
String get name => actualElement.name;
@override
int get nameLength => actualElement.nameLength;
@override
int get nameOffset => actualElement.nameOffset;
@override
AnalysisSession get session => _resynthesizer.session;
@override
Source get source => actualElement.source;
@deprecated
@override
CompilationUnit get unit => actualElement.unit;
@override
bool operator ==(Object object) =>
object is Element && object.location == _location;
@override
T accept<T>(ElementVisitor<T> visitor) => actualElement.accept(visitor);
@override
String computeDocumentationComment() => documentationComment;
@deprecated
@override
AstNode computeNode() => actualElement.computeNode();
@override
E getAncestor<E extends Element>(Predicate<Element> predicate) =>
actualElement.getAncestor(predicate);
@override
String getExtendedDisplayName(String shortName) =>
actualElement.getExtendedDisplayName(shortName);
@override
bool isAccessibleIn(LibraryElement library) =>
actualElement.isAccessibleIn(library);
@override
String toString() => actualElement.toString();
@override
void visitChildren(ElementVisitor visitor) {
actualElement.visitChildren(visitor);
}
}
/**
* Interface which allows an [Element] handle to be resynthesized based on an
* [ElementLocation]. The concrete classes implementing element handles use
* this interface to retrieve the underlying elements when queried.
*/
abstract class ElementResynthesizer {
/**
* The context that owns the element to be resynthesized.
*/
final AnalysisContext context;
/**
* The session that owns the element to be resynthesized.
*
* Note that this will be `null` if the task model is being used.
*/
final AnalysisSession session;
/**
* Initialize a newly created resynthesizer to resynthesize elements in the
* given [context].
*/
ElementResynthesizer(this.context, this.session);
/**
* Return the element referenced by the given [location].
*/
Element getElement(ElementLocation location);
}
/**
* A handle to an [ExecutableElement].
*/
abstract class ExecutableElementHandle extends ElementHandle
implements ExecutableElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
ExecutableElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
ExecutableElement get actualElement =>
super.actualElement as ExecutableElement;
@override
bool get hasImplicitReturnType => actualElement.hasImplicitReturnType;
@override
bool get isAbstract => actualElement.isAbstract;
@override
bool get isAsynchronous => actualElement.isAsynchronous;
@override
bool get isExternal => actualElement.isExternal;
@override
bool get isGenerator => actualElement.isGenerator;
@override
bool get isOperator => actualElement.isOperator;
@override
bool get isSimplyBounded => actualElement.isSimplyBounded;
@override
bool get isStatic => actualElement.isStatic;
@override
bool get isSynchronous => actualElement.isSynchronous;
@override
List<ParameterElement> get parameters => actualElement.parameters;
@override
DartType get returnType => actualElement.returnType;
@override
FunctionType get type => actualElement.type;
@override
List<TypeParameterElement> get typeParameters => actualElement.typeParameters;
}
/**
* A handle to an [ExportElement].
*/
class ExportElementHandle extends ElementHandle implements ExportElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
ExportElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
ExportElement get actualElement => super.actualElement as ExportElement;
@override
List<NamespaceCombinator> get combinators => actualElement.combinators;
@override
LibraryElement get exportedLibrary => actualElement.exportedLibrary;
@override
ElementKind get kind => ElementKind.EXPORT;
@override
String get uri => actualElement.uri;
@override
int get uriEnd => actualElement.uriEnd;
@override
int get uriOffset => actualElement.uriOffset;
}
/**
* A handle to a [FieldElement].
*/
class FieldElementHandle extends PropertyInducingElementHandle
implements FieldElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
FieldElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
FieldElement get actualElement => super.actualElement as FieldElement;
@override
ClassElement get enclosingElement => actualElement.enclosingElement;
@override
bool get isCovariant => actualElement.isCovariant;
@override
bool get isEnumConstant => actualElement.isEnumConstant;
@deprecated
@override
bool get isVirtual => actualElement.isVirtual;
@override
ElementKind get kind => ElementKind.FIELD;
@deprecated
@override
VariableDeclaration computeNode() => actualElement.computeNode();
}
/**
* A handle to a [FunctionElement].
*/
class FunctionElementHandle extends ExecutableElementHandle
implements FunctionElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
FunctionElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
FunctionElement get actualElement => super.actualElement as FunctionElement;
@override
bool get isEntryPoint => actualElement.isEntryPoint;
@override
ElementKind get kind => ElementKind.FUNCTION;
@override
SourceRange get visibleRange => actualElement.visibleRange;
@deprecated
@override
FunctionDeclaration computeNode() => actualElement.computeNode();
}
/**
* A handle to a [FunctionTypeAliasElement].
*/
class FunctionTypeAliasElementHandle extends ElementHandle
implements FunctionTypeAliasElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
FunctionTypeAliasElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
FunctionTypeAliasElement get actualElement =>
super.actualElement as FunctionTypeAliasElement;
@override
CompilationUnitElement get enclosingElement =>
super.enclosingElement as CompilationUnitElement;
@override
GenericFunctionTypeElement get function => actualElement.function;
@override
bool get isSimplyBounded => actualElement.isSimplyBounded;
@override
ElementKind get kind => ElementKind.FUNCTION_TYPE_ALIAS;
@override
List<ParameterElement> get parameters => actualElement.parameters;
@override
DartType get returnType => actualElement.returnType;
@override
FunctionType get type => actualElement.type;
@override
List<TypeParameterElement> get typeParameters => actualElement.typeParameters;
@deprecated
@override
FunctionTypeAlias computeNode() => actualElement.computeNode();
@override
FunctionType instantiate(List<DartType> argumentTypes) =>
actualElement.instantiate(argumentTypes);
@override
FunctionType instantiate2({
@required List<DartType> typeArguments,
@required NullabilitySuffix nullabilitySuffix,
}) {
return actualElement.instantiate2(
typeArguments: typeArguments,
nullabilitySuffix: nullabilitySuffix,
);
}
}
/**
* A handle to a [GenericTypeAliasElement].
*/
class GenericTypeAliasElementHandle extends ElementHandle
implements GenericTypeAliasElement {
GenericTypeAliasElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
GenericTypeAliasElement get actualElement =>
super.actualElement as GenericTypeAliasElement;
@override
CompilationUnitElement get enclosingElement =>
super.enclosingElement as CompilationUnitElement;
@override
GenericFunctionTypeElement get function => actualElement.function;
@override
bool get isSimplyBounded => actualElement.isSimplyBounded;
@override
ElementKind get kind => ElementKind.FUNCTION_TYPE_ALIAS;
@override
List<ParameterElement> get parameters => actualElement.parameters;
@override
DartType get returnType => actualElement.returnType;
@override
FunctionType get type => actualElement.type;
@override
List<TypeParameterElement> get typeParameters => actualElement.typeParameters;
@deprecated
@override
FunctionTypeAlias computeNode() => actualElement.computeNode();
@override
FunctionType instantiate(List<DartType> argumentTypes) =>
actualElement.instantiate(argumentTypes);
@override
FunctionType instantiate2({
@required List<DartType> typeArguments,
@required NullabilitySuffix nullabilitySuffix,
}) {
return actualElement.instantiate2(
typeArguments: typeArguments,
nullabilitySuffix: nullabilitySuffix,
);
}
}
/**
* A handle to an [ImportElement].
*/
class ImportElementHandle extends ElementHandle implements ImportElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
ImportElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
ImportElement get actualElement => super.actualElement as ImportElement;
@override
List<NamespaceCombinator> get combinators => actualElement.combinators;
@override
LibraryElement get importedLibrary => actualElement.importedLibrary;
@override
bool get isDeferred => actualElement.isDeferred;
@override
ElementKind get kind => ElementKind.IMPORT;
@override
Namespace get namespace => actualElement.namespace;
@override
PrefixElement get prefix => actualElement.prefix;
@override
int get prefixOffset => actualElement.prefixOffset;
@override
String get uri => actualElement.uri;
@override
int get uriEnd => actualElement.uriEnd;
@override
int get uriOffset => actualElement.uriOffset;
}
/**
* A handle to a [LabelElement].
*/
class LabelElementHandle extends ElementHandle implements LabelElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
LabelElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
ExecutableElement get enclosingElement =>
super.enclosingElement as ExecutableElement;
@override
ElementKind get kind => ElementKind.LABEL;
}
/**
* A handle to a [LibraryElement].
*/
class LibraryElementHandle extends ElementHandle implements LibraryElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
LibraryElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
LibraryElement get actualElement => super.actualElement as LibraryElement;
@override
CompilationUnitElement get definingCompilationUnit =>
actualElement.definingCompilationUnit;
@override
FunctionElement get entryPoint => actualElement.entryPoint;
@override
List<LibraryElement> get exportedLibraries => actualElement.exportedLibraries;
@override
Namespace get exportNamespace => actualElement.exportNamespace;
@override
List<ExportElement> get exports => actualElement.exports;
@override
bool get hasExtUri => actualElement.hasExtUri;
@override
bool get hasLoadLibraryFunction => actualElement.hasLoadLibraryFunction;
@override
String get identifier => location.components.last;
@override
List<LibraryElement> get importedLibraries => actualElement.importedLibraries;
@override
List<ImportElement> get imports => actualElement.imports;
@override
bool get isBrowserApplication => actualElement.isBrowserApplication;
@override
bool get isDartAsync => actualElement.isDartAsync;
@override
bool get isDartCore => actualElement.isDartCore;
@override
bool get isInSdk => actualElement.isInSdk;
@override
bool get isNonNullableByDefault => actualElement.isNonNullableByDefault;
@override
ElementKind get kind => ElementKind.LIBRARY;
@override
List<LibraryElement> get libraryCycle => actualElement.libraryCycle;
@override
FunctionElement get loadLibraryFunction => actualElement.loadLibraryFunction;
@override
List<CompilationUnitElement> get parts => actualElement.parts;
@override
List<PrefixElement> get prefixes => actualElement.prefixes;
@override
Namespace get publicNamespace => actualElement.publicNamespace;
@override
Iterable<Element> get topLevelElements => actualElement.topLevelElements;
@override
List<CompilationUnitElement> get units => actualElement.units;
@override
List<ImportElement> getImportsWithPrefix(PrefixElement prefixElement) =>
actualElement.getImportsWithPrefix(prefixElement);
@override
ClassElement getType(String className) => actualElement.getType(className);
}
/**
* A handle to a [LocalVariableElement].
*/
class LocalVariableElementHandle extends VariableElementHandle
implements LocalVariableElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
LocalVariableElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
LocalVariableElement get actualElement =>
super.actualElement as LocalVariableElement;
@override
ElementKind get kind => ElementKind.LOCAL_VARIABLE;
@override
SourceRange get visibleRange => actualElement.visibleRange;
@deprecated
@override
VariableDeclaration computeNode() => actualElement.computeNode();
}
/**
* A handle to a [MethodElement].
*/
class MethodElementHandle extends ExecutableElementHandle
implements MethodElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
MethodElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
MethodElement get actualElement => super.actualElement as MethodElement;
@override
ClassElement get enclosingElement => super.enclosingElement as ClassElement;
@override
bool get isStatic => actualElement.isStatic;
@override
ElementKind get kind => ElementKind.METHOD;
@deprecated
@override
MethodDeclaration computeNode() => actualElement.computeNode();
}
/**
* A handle to a [ParameterElement].
*/
class ParameterElementHandle extends VariableElementHandle
with ParameterElementMixin
implements ParameterElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
ParameterElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
ParameterElement get actualElement => super.actualElement as ParameterElement;
@override
String get defaultValueCode => actualElement.defaultValueCode;
@override
bool get isCovariant => actualElement.isCovariant;
@override
bool get isInitializingFormal => actualElement.isInitializingFormal;
@override
ElementKind get kind => ElementKind.PARAMETER;
@deprecated
@override
ParameterKind get parameterKind => actualElement.parameterKind;
@override
List<ParameterElement> get parameters => actualElement.parameters;
@override
List<TypeParameterElement> get typeParameters => actualElement.typeParameters;
@override
SourceRange get visibleRange => actualElement.visibleRange;
@deprecated
@override
FormalParameter computeNode() => super.computeNode();
}
/**
* A handle to a [PrefixElement].
*/
class PrefixElementHandle extends ElementHandle implements PrefixElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
PrefixElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
PrefixElement get actualElement => super.actualElement as PrefixElement;
@override
LibraryElement get enclosingElement =>
super.enclosingElement as LibraryElement;
@override
List<LibraryElement> get importedLibraries => const <LibraryElement>[];
@override
ElementKind get kind => ElementKind.PREFIX;
}
/**
* A handle to a [PropertyAccessorElement].
*/
class PropertyAccessorElementHandle extends ExecutableElementHandle
implements PropertyAccessorElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
PropertyAccessorElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
PropertyAccessorElement get actualElement =>
super.actualElement as PropertyAccessorElement;
@override
PropertyAccessorElement get correspondingGetter =>
actualElement.correspondingGetter;
@override
PropertyAccessorElement get correspondingSetter =>
actualElement.correspondingSetter;
@override
bool get isGetter => !isSetter;
@override
bool get isSetter => location.components.last.endsWith('=');
@override
ElementKind get kind {
if (isGetter) {
return ElementKind.GETTER;
} else {
return ElementKind.SETTER;
}
}
@override
PropertyInducingElement get variable => actualElement.variable;
}
/**
* A handle to an [PropertyInducingElement].
*/
abstract class PropertyInducingElementHandle extends VariableElementHandle
implements PropertyInducingElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
PropertyInducingElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
PropertyInducingElement get actualElement =>
super.actualElement as PropertyInducingElement;
@override
PropertyAccessorElement get getter => actualElement.getter;
@override
bool get isConstantEvaluated => actualElement.isConstantEvaluated;
@deprecated
@override
DartType get propagatedType => null;
@override
PropertyAccessorElement get setter => actualElement.setter;
}
/**
* A handle to a [TopLevelVariableElement].
*/
class TopLevelVariableElementHandle extends PropertyInducingElementHandle
implements TopLevelVariableElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
TopLevelVariableElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
ElementKind get kind => ElementKind.TOP_LEVEL_VARIABLE;
@deprecated
@override
VariableDeclaration computeNode() => super.computeNode();
}
/**
* A handle to a [TypeParameterElement].
*/
class TypeParameterElementHandle extends ElementHandle
implements TypeParameterElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
TypeParameterElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
TypeParameterElement get actualElement =>
super.actualElement as TypeParameterElement;
@override
DartType get bound => actualElement.bound;
@override
ElementKind get kind => ElementKind.TYPE_PARAMETER;
@override
TypeParameterType get type => actualElement.type;
@override
TypeParameterType instantiate({
@required NullabilitySuffix nullabilitySuffix,
}) {
return actualElement.instantiate(nullabilitySuffix: nullabilitySuffix);
}
}
/**
* A handle to an [VariableElement].
*/
abstract class VariableElementHandle extends ElementHandle
implements VariableElement {
/**
* Initialize a newly created element handle to represent the element at the
* given [_location]. The [_resynthesizer] will be used to resynthesize the
* element when needed.
*/
VariableElementHandle(
ElementResynthesizer resynthesizer, ElementLocation location)
: super(resynthesizer, location);
@override
VariableElement get actualElement => super.actualElement as VariableElement;
@override
DartObject get constantValue => actualElement.constantValue;
@override
bool get hasImplicitType => actualElement.hasImplicitType;
@override
FunctionElement get initializer => actualElement.initializer;
@override
bool get isConst => actualElement.isConst;
@override
bool get isConstantEvaluated => actualElement.isConstantEvaluated;
@override
bool get isFinal => actualElement.isFinal;
@override
bool get isLate => actualElement.isLate;
@deprecated
@override
bool get isPotentiallyMutatedInClosure =>
actualElement.isPotentiallyMutatedInClosure;
@deprecated
@override
bool get isPotentiallyMutatedInScope =>
actualElement.isPotentiallyMutatedInScope;
@override
bool get isStatic => actualElement.isStatic;
@override
DartType get type => actualElement.type;
@override
DartObject computeConstantValue() => actualElement.computeConstantValue();
}
| 0 |
Subsets and Splits