diff --git a/pkg/analyzer/lib/src/dart/analysis/byte_store.dart b/pkg/analyzer/lib/src/dart/analysis/byte_store.dart index b73493e4c277..fbb5afbd6303 100644 --- a/pkg/analyzer/lib/src/dart/analysis/byte_store.dart +++ b/pkg/analyzer/lib/src/dart/analysis/byte_store.dart @@ -4,34 +4,26 @@ 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. - */ +/// 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. - */ + /// Return the bytes associated with the given [key]. + /// Return `null` if the association does not exist. List get(String key); - /** - * Associate the given [bytes] with the [key]. - */ + /// Associate the given [bytes] with the [key]. void put(String key, List bytes); } -/** - * [ByteStore] which stores data only in memory. - */ +/// [ByteStore] which stores data only in memory. class MemoryByteStore implements ByteStore { final Map> _map = {}; @@ -46,9 +38,7 @@ class MemoryByteStore implements ByteStore { } } -/** - * A wrapper around [ByteStore] which adds an in-memory LRU cache to it. - */ +/// A wrapper around [ByteStore] which adds an in-memory LRU cache to it. class MemoryCachingByteStore implements ByteStore { final ByteStore _store; final Cache> _cache; @@ -68,9 +58,7 @@ class MemoryCachingByteStore implements ByteStore { } } -/** - * [ByteStore] which does not store any data. - */ +/// [ByteStore] which does not store any data. class NullByteStore implements ByteStore { @override List get(String key) => null; diff --git a/pkg/analyzer/lib/src/dart/analysis/cache.dart b/pkg/analyzer/lib/src/dart/analysis/cache.dart index 1a6d8e491beb..d7fe7533d1ce 100644 --- a/pkg/analyzer/lib/src/dart/analysis/cache.dart +++ b/pkg/analyzer/lib/src/dart/analysis/cache.dart @@ -2,9 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -/** - * LRU cache of objects. - */ +/// LRU cache of objects. class Cache { final int _maxSizeBytes; final int Function(V) _meter; diff --git a/pkg/analyzer/lib/src/dart/analysis/context_builder.dart b/pkg/analyzer/lib/src/dart/analysis/context_builder.dart index ee087db2a93c..7de4d8e9f5f9 100644 --- a/pkg/analyzer/lib/src/dart/analysis/context_builder.dart +++ b/pkg/analyzer/lib/src/dart/analysis/context_builder.dart @@ -25,28 +25,20 @@ 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. - */ +/// An implementation of a context builder. class ContextBuilderImpl implements ContextBuilder { - /** - * The resource provider used to access the file system. - */ + /// 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. - */ + /// 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. - */ + /// 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; @@ -113,10 +105,8 @@ class ContextBuilderImpl implements ContextBuilder { return context; } - /** - * Convert the [declaredVariables] into a map for use with the old context - * builder. - */ + /// Convert the [declaredVariables] into a map for use with the old context + /// builder. Map _toMap(DeclaredVariables declaredVariables) { Map map = {}; for (String name in declaredVariables.variableNames) { diff --git a/pkg/analyzer/lib/src/dart/analysis/context_locator.dart b/pkg/analyzer/lib/src/dart/analysis/context_locator.dart index 7bfa83fcdc33..0ad9d8eb09e9 100644 --- a/pkg/analyzer/lib/src/dart/analysis/context_locator.dart +++ b/pkg/analyzer/lib/src/dart/analysis/context_locator.dart @@ -32,37 +32,25 @@ import 'package:meta/meta.dart'; import 'package:path/path.dart'; import 'package:yaml/yaml.dart'; -/** - * An implementation of a context locator. - */ +/// An implementation of a context locator. class ContextLocatorImpl implements ContextLocator { - /** - * The name of the analysis options file. - */ + /// The name of the analysis options file. static const String ANALYSIS_OPTIONS_NAME = 'analysis_options.yaml'; - /** - * The name of the packages file. - */ + /// The name of the packages file. static const String PACKAGES_FILE_NAME = '.packages'; - /** - * The resource provider used to access the file system. - */ + /// 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. - */ + /// 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. - */ + /// Return the path to the default location of the SDK. String get _defaultSdkPath => FolderBasedDartSdk.defaultSdkDirectory(resourceProvider).path; @@ -189,26 +177,23 @@ class ContextLocatorImpl implements ContextLocator { return roots; } - /** - * Return `true` if the given [resource] is contained in one or more of the - * given [folders]. - */ + /// Return `true` if the given [resource] is contained in one or more of the + /// given [folders]. bool _containedInAny(Iterable 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. - */ + /// 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 roots, Folder folder, @@ -253,14 +238,13 @@ class ContextLocatorImpl implements ContextLocator { 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. - */ + /// 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 roots, Folder folder, @@ -303,11 +287,9 @@ class ContextLocatorImpl implements ContextLocator { } } - /** - * 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. - */ + /// 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); @@ -319,11 +301,9 @@ class ContextLocatorImpl implements ContextLocator { 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. - */ + /// 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); @@ -375,10 +355,8 @@ class ContextLocatorImpl implements ContextLocator { return patterns; } - /** - * If the given [directory] contains a file with the given [name], then return - * the file. Otherwise, return `null`. - */ + /// 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) { @@ -387,24 +365,18 @@ class ContextLocatorImpl implements ContextLocator { return null; } - /** - * Return the analysis options file in the given [folder], or `null` if the - * folder does not contain an analysis options file. - */ + /// 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); - /** - * Return the packages file in the given [folder], or `null` if the folder - * does not contain a packages file. - */ + /// 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. - */ + /// 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 paths, List folders, List files) { for (String path in _uniqueSortedPaths(paths)) { @@ -421,10 +393,8 @@ class ContextLocatorImpl implements ContextLocator { } } - /** - * 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. - */ + /// 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 _uniqueSortedPaths(List paths) { Set uniquePaths = HashSet.from(paths); List sortedPaths = uniquePaths.toList(); diff --git a/pkg/analyzer/lib/src/dart/analysis/context_root.dart b/pkg/analyzer/lib/src/dart/analysis/context_root.dart index 88d085a4529c..e65271003b0b 100644 --- a/pkg/analyzer/lib/src/dart/analysis/context_root.dart +++ b/pkg/analyzer/lib/src/dart/analysis/context_root.dart @@ -6,9 +6,7 @@ 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. - */ +/// An implementation of a context root. class ContextRootImpl implements ContextRoot { @override final ResourceProvider resourceProvider; @@ -28,9 +26,7 @@ class ContextRootImpl implements ContextRoot { @override File packagesFile; - /** - * Initialize a newly created context root. - */ + /// Initialize a newly created context root. ContextRootImpl(this.resourceProvider, this.root); @override @@ -71,10 +67,8 @@ class ContextRootImpl implements ContextRoot { return _isIncluded(path) && !_isExcluded(path); } - /** - * Return the absolute paths of all of the files that are included in the - * given [folder]. - */ + /// Return the absolute paths of all of the files that are included in the + /// given [folder]. Iterable _includedFilesInFolder(Folder folder) sync* { for (Resource resource in folder.getChildren()) { String path = resource.path; @@ -91,10 +85,8 @@ class ContextRootImpl implements ContextRoot { } } - /** - * Return `true` if the given [path] is either the same as or inside of one of - * the [excludedPaths]. - */ + /// 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); @@ -120,10 +112,8 @@ class ContextRootImpl implements ContextRoot { return false; } - /** - * Return `true` if the given [path] is either the same as or inside of one of - * the [includedPaths]. - */ + /// 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) { diff --git a/pkg/analyzer/lib/src/dart/analysis/crc32.dart b/pkg/analyzer/lib/src/dart/analysis/crc32.dart index 2f2d504980d5..374097cb4ca9 100644 --- a/pkg/analyzer/lib/src/dart/analysis/crc32.dart +++ b/pkg/analyzer/lib/src/dart/analysis/crc32.dart @@ -261,10 +261,8 @@ const List _CRC32_TABLE = [ 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. - */ +/// 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 array, [int crc = 0]) { int len = array.length; crc = crc ^ 0xffffffff; diff --git a/pkg/analyzer/lib/src/dart/analysis/defined_names.dart b/pkg/analyzer/lib/src/dart/analysis/defined_names.dart index d76631a890e8..ed3cfb787d76 100644 --- a/pkg/analyzer/lib/src/dart/analysis/defined_names.dart +++ b/pkg/analyzer/lib/src/dart/analysis/defined_names.dart @@ -4,9 +4,7 @@ import 'package:analyzer/dart/ast/ast.dart'; -/** - * Compute the [DefinedNames] for the given [unit]. - */ +/// Compute the [DefinedNames] for the given [unit]. DefinedNames computeDefinedNames(CompilationUnit unit) { DefinedNames names = DefinedNames(); @@ -47,9 +45,7 @@ DefinedNames computeDefinedNames(CompilationUnit unit) { return names; } -/** - * Defined top-level and class member names. - */ +/// Defined top-level and class member names. class DefinedNames { final Set topLevelNames = {}; final Set classMemberNames = {}; diff --git a/pkg/analyzer/lib/src/dart/analysis/driver_based_analysis_context.dart b/pkg/analyzer/lib/src/dart/analysis/driver_based_analysis_context.dart index 1ca44d2d7b26..582a366ed290 100644 --- a/pkg/analyzer/lib/src/dart/analysis/driver_based_analysis_context.dart +++ b/pkg/analyzer/lib/src/dart/analysis/driver_based_analysis_context.dart @@ -11,32 +11,23 @@ import 'package:analyzer/src/dart/analysis/driver.dart' show AnalysisDriver; import 'package:analyzer/src/generated/engine.dart' show AnalysisOptions; import 'package:analyzer/src/workspace/workspace.dart'; -/** - * An analysis context whose implementation is based on an analysis driver. - */ +/// An analysis context whose implementation is based on an analysis driver. class DriverBasedAnalysisContext implements AnalysisContext { - /** - * The resource provider used to access the file system. - */ + /// The resource provider used to access the file system. final ResourceProvider resourceProvider; @override final ContextRoot contextRoot; - /** - * The driver on which this context is based. - */ + /// The driver on which this context is based. final AnalysisDriver driver; - /** - * The [Workspace] for this context, `null` if not yet created. - */ + /// The [Workspace] for this context, `null` if not yet created. Workspace _workspace; - /** - * Initialize a newly created context that uses the given [resourceProvider] - * to access the file system and that is based on the given analysis [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; diff --git a/pkg/analyzer/lib/src/dart/analysis/file_byte_store.dart b/pkg/analyzer/lib/src/dart/analysis/file_byte_store.dart index a5652ecf5e9c..b93a6c894fa5 100644 --- a/pkg/analyzer/lib/src/dart/analysis/file_byte_store.dart +++ b/pkg/analyzer/lib/src/dart/analysis/file_byte_store.dart @@ -12,9 +12,7 @@ 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. - */ +/// The request that is sent from the main isolate to the clean-up isolate. class CacheCleanUpRequest { final String cachePath; final int maxSizeBytes; @@ -23,13 +21,11 @@ class CacheCleanUpRequest { 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. - */ +/// [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; @@ -59,9 +55,7 @@ class EvictingFileByteStore implements ByteStore { } } - /** - * If the cache clean up process has not been requested yet, request it. - */ + /// If the cache clean up process has not been requested yet, request it. Future _requestCacheCleanUp() async { if (_cleanUpSendPortShouldBePrepared) { _cleanUpSendPortShouldBePrepared = false; @@ -88,10 +82,8 @@ class EvictingFileByteStore implements ByteStore { } } - /** - * This function is started in a new isolate, receives cache folder clean up - * requests and evicts older files from the folder. - */ + /// 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 = ReceivePort(); @@ -149,9 +141,7 @@ class EvictingFileByteStore implements ByteStore { } } -/** - * [ByteStore] that stores values as files. - */ +/// [ByteStore] that stores values as files. class FileByteStore implements ByteStore { static final FileByteStoreValidator _validator = FileByteStoreValidator(); static final _dotCodeUnit = '.'.codeUnitAt(0); @@ -161,10 +151,8 @@ class FileByteStore implements ByteStore { final Map> _writeInProgress = {}; final FuturePool _pool = 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. - */ + /// 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'}'; @@ -229,21 +217,17 @@ class FileByteStore implements ByteStore { } } -/** - * 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. - */ +/// 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 _VERSION = [0x01, 0x00]; - /** - * If the [rawBytes] have the valid version and checksum, extract and - * return the data from it. Otherwise return `null`. - */ + /// If the [rawBytes] have the valid version and checksum, extract and + /// return the data from it. Otherwise return `null`. List getData(List rawBytes) { // There must be at least the version and the checksum in the raw bytes. if (rawBytes.length < 4) { @@ -268,10 +252,8 @@ class FileByteStoreValidator { return data; } - /** - * Return bytes that include the given [data] plus the current version and - * the checksum of the [data]. - */ + /// Return bytes that include the given [data] plus the current version and + /// the checksum of the [data]. List wrapData(List data) { int len = data.length; var bytes = Uint8List(len + 4); diff --git a/pkg/analyzer/lib/src/dart/analysis/file_state.dart b/pkg/analyzer/lib/src/dart/analysis/file_state.dart index 0e00b63e1858..e58f61b0c4aa 100644 --- a/pkg/analyzer/lib/src/dart/analysis/file_state.dart +++ b/pkg/analyzer/lib/src/dart/analysis/file_state.dart @@ -47,30 +47,22 @@ var counterFileStateRefresh = 0; var counterUnlinkedLinkedBytes = 0; var timerFileStateRefresh = Stopwatch(); -/** - * [FileContentOverlay] is used to temporary override content of files. - */ +/// [FileContentOverlay] is used to temporary override content of files. class FileContentOverlay { final _map = {}; - /** - * Return the paths currently being overridden. - */ + /// Return the paths currently being overridden. Iterable 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. - */ + /// 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. - */ + /// 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); @@ -80,56 +72,42 @@ class FileContentOverlay { } } -/** - * 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. - */ +/// 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. - */ + /// The absolute path of the file. final String path; - /** - * The absolute URI of the file. - */ + /// The absolute URI of the file. final Uri uri; - /** - * The [Source] of the file with the [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. - */ + /// 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; - /** - * The [FeatureSet] for all files in the analysis context. - * - * Usually it is the feature set of the latest language version, plus - * possibly additional enabled experiments (from the analysis options file, - * or from SDK allowed experiments). - * - * This feature set is then restricted, with the [_packageLanguageVersion], - * or with a `@dart` language override token in the file header. - */ + /// The [FeatureSet] for all files in the analysis context. + /// + /// Usually it is the feature set of the latest language version, plus + /// possibly additional enabled experiments (from the analysis options file, + /// or from SDK allowed experiments). + /// + /// This feature set is then restricted, with the [_packageLanguageVersion], + /// or with a `@dart` language override token in the file header. final FeatureSet _contextFeatureSet; - /** - * The language version for the package that contains this file. - */ + /// The language version for the package that contains this file. final Version _packageLanguageVersion; bool _exists; @@ -157,10 +135,8 @@ class FileState { 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. - */ + /// 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._( @@ -183,81 +159,58 @@ class FileState { _libraryCycle = LibraryCycle.external(); } - /** - * The unlinked API signature of the file. - */ + /// The unlinked API signature of the file. List get apiSignature => _apiSignature; - /** - * The content of the file. - */ + /// The content of the file. String get content => _content; - /** - * The MD5 hash of the [content]. - */ + /// The MD5 hash of the [content]. String get contentHash => _contentHash; - /** - * The class member names defined by the file. - */ + /// The class member names defined by the file. Set get definedClassMemberNames { return _definedClassMemberNames ??= _driverUnlinkedUnit.definedClassMemberNames.toSet(); } - /** - * The top-level names defined by the file. - */ + /// The top-level names defined by the file. Set get definedTopLevelNames { return _definedTopLevelNames ??= _driverUnlinkedUnit.definedTopLevelNames.toSet(); } - /** - * Return the set of all directly referenced files - imported, exported or - * parted. - */ + /// Return the set of all directly referenced files - imported, exported or + /// parted. Set get directReferencedFiles => _directReferencedFiles; - /** - * Return the set of all directly referenced libraries - imported or exported. - */ + /// Return the set of all directly referenced libraries - imported or + /// exported. Set get directReferencedLibraries => _directReferencedLibraries; - /** - * Return `true` if the file exists. - */ + /// Return `true` if the file exists. bool get exists => _exists; - /** - * The list of files this file exports. - */ + /// The list of files this file exports. List get exportedFiles => _exportedFiles; @override int get hashCode => uri.hashCode; - /** - * The list of files this file imports. - */ + /// The list of files this file imports. List 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. - */ + /// 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. - */ + /// 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)) { @@ -266,17 +219,13 @@ class FileState { return !_unlinked2.hasLibraryDirective && _unlinked2.hasPartOfDirective; } - /** - * Return `true` if the file is the "unresolved" file, which does not have - * neither a valid URI, nor a path. - */ + /// 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. - */ + /// 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 libraries = _fsState._partToLibraries[this]; if (libraries == null || libraries.isEmpty) { @@ -303,25 +252,17 @@ class FileState { return _libraryCycle; } - /** - * The list of files files that this library consists of, i.e. this library - * file itself and its [partedFiles]. - */ + /// The list of files files that this library consists of, i.e. this library + /// file itself and its [partedFiles]. List get libraryFiles => _libraryFiles; - /** - * Return information about line in the file. - */ + /// Return information about line in the file. LineInfo get lineInfo => _lineInfo; - /** - * The list of files this library file references as parts. - */ + /// The list of files this library file references as parts. List get partedFiles => _partedFiles; - /** - * The external names referenced by the file. - */ + /// The external names referenced by the file. Set get referencedNames { return _referencedNames ??= _driverUnlinkedUnit.referencedNames.toSet(); } @@ -329,10 +270,8 @@ class FileState { @visibleForTesting FileStateTestView get test => FileStateTestView(this); - /** - * Return the set of transitive files - the file itself and all of the - * directly or indirectly referenced files. - */ + /// Return the set of transitive files - the file itself and all of the + /// directly or indirectly referenced files. Set get transitiveFiles { var transitiveFiles = {}; @@ -346,30 +285,22 @@ class FileState { return transitiveFiles; } - /** - * Return the signature of the file, based on API signatures of the - * transitive closure of imported / exported files. - */ + /// 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. - */ + /// The value `transitiveSignature.linked` is used often, so we cache it. String get transitiveSignatureLinked { return _transitiveSignatureLinked ??= '$transitiveSignature.linked'; } - /** - * The [UnlinkedUnit2] of the file. - */ + /// The [UnlinkedUnit2] of the file. UnlinkedUnit2 get unlinked2 => _unlinked2; - /** - * Return the [uri] string. - */ + /// Return the [uri] string. String get uriStr => uri.toString(); @override @@ -388,11 +319,9 @@ class FileState { } } - /** - * Return a new parsed unresolved [CompilationUnit]. - * - * If an exception happens during parsing, an empty unit is returned. - */ + /// 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 { @@ -404,16 +333,14 @@ class FileState { } } - /** - * 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. - */ + /// 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++; @@ -579,10 +506,8 @@ class FileState { return unit; } - /** - * Return the [FileState] for the given [relativeUri], maybe "unresolved" - * file if the URI cannot be parsed, cannot correspond any file, etc. - */ + /// 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; @@ -598,10 +523,8 @@ class FileState { 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. - */ + /// 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; @@ -759,9 +682,7 @@ $content ); } - /** - * Return `true` if the given byte lists are equal. - */ + /// Return `true` if the given byte lists are equal. static bool _equalByteLists(List a, List b) { if (a == null) { return b == null; @@ -805,9 +726,7 @@ class FileStateTestView { String get unlinkedKey => file._unlinkedKey; } -/** - * Information about known file system state. - */ +/// Information about known file system state. class FileSystemState { final PerformanceLog _logger; final ResourceProvider _resourceProvider; @@ -822,71 +741,47 @@ class FileSystemState { final FeatureSetProvider featureSetProvider; - /** - * 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. - */ + /// 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]. - */ + /// Mapping from a URI to the corresponding [FileState]. final Map _uriToFile = {}; - /** - * All known file paths. - */ + /// All known file paths. final Set knownFilePaths = {}; - /** - * All known files. - */ + /// All known files. final List knownFiles = []; - /** - * Mapping from a path to the flag whether there is a URI for the path. - */ + /// Mapping from a path to the flag whether there is a URI for the path. final Map _hasUriForPath = {}; - /** - * Mapping from a path to the corresponding [FileState]s, canonical or not. - */ + /// Mapping from a path to the corresponding [FileState]s, canonical or not. final Map> _pathToFiles = {}; - /** - * Mapping from a path to the corresponding canonical [FileState]. - */ + /// Mapping from a path to the corresponding canonical [FileState]. final Map _pathToCanonicalFile = {}; - /** - * Mapping from a part to the libraries it is a part of. - */ + /// Mapping from a part to the libraries it is a part of. final Map> _partToLibraries = {}; - /** - * The map of subtyped names to files where these names are subtyped. - */ + /// The map of subtyped names to files where these names are subtyped. final Map> _subtypedNameToFiles = {}; - /** - * The value of this field is incremented when the set of files is updated. - */ + /// 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. - */ + /// 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. - */ + /// 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; @@ -915,9 +810,7 @@ class FileSystemState { @visibleForTesting FileSystemStateTestView get test => _testView; - /** - * Return the [FileState] instance that correspond to an unresolved URI. - */ + /// Return the [FileState] instance that correspond to an unresolved URI. FileState get unresolvedFile { if (_unresolvedFile == null) { var featureSet = FeatureSet.fromEnableFlags([]); @@ -928,13 +821,11 @@ class FileSystemState { 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. - */ + /// 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) { @@ -963,12 +854,10 @@ class FileSystemState { 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. - */ + /// 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) { @@ -1007,10 +896,8 @@ class FileSystemState { 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. - */ + /// 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 getFilesForPath(String path) { FileState canonicalFile = getFileForPath(path); List allFiles = _pathToFiles[path].toList(); @@ -1022,21 +909,17 @@ class FileSystemState { ..insert(0, canonicalFile); } - /** - * Return files where the given [name] is subtyped, i.e. used in `extends`, - * `with` or `implements` clauses. - */ + /// Return files where the given [name] is subtyped, i.e. used in `extends`, + /// `with` or `implements` clauses. Set 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. - */ + /// 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) { @@ -1050,27 +933,21 @@ class FileSystemState { return flag; } - /** - * The file with the given [path] might have changed, so ensure that it is - * read the next time it is refreshed. - */ + /// 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]. - */ + /// 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. - */ + /// 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(); @@ -1114,9 +991,7 @@ class FileSystemStateTestView { } } -/** - * Information about the content of a file. - */ +/// Information about the content of a file. class _FileContent { final String path; final bool exists; @@ -1126,23 +1001,17 @@ class _FileContent { _FileContent(this.path, this.exists, this.content, this.contentHash); } -/** - * The cache of information about content of files. - */ +/// 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]. - */ + /// Weak map of cache instances. + /// + /// Outer key is a [FileContentOverlay]. + /// Inner key is a [ResourceProvider]. static final _instances = Expando>(); - /** - * Weak map of cache instances. - * - * Key is a [ResourceProvider]. - */ + /// Weak map of cache instances. + /// + /// Key is a [ResourceProvider]. static final _instances2 = Expando<_FileContentCache>(); final ResourceProvider _resourceProvider; @@ -1155,12 +1024,10 @@ class _FileContentCache { _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. - */ + /// 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) { @@ -1188,9 +1055,7 @@ class _FileContentCache { return file; } - /** - * Remove the file with the given [path] from the cache. - */ + /// Remove the file with the given [path] from the cache. void remove(String path) { _pathToFile.remove(path); } diff --git a/pkg/analyzer/lib/src/dart/analysis/file_tracker.dart b/pkg/analyzer/lib/src/dart/analysis/file_tracker.dart index 57eaa06021fc..abd28a5a91a3 100644 --- a/pkg/analyzer/lib/src/dart/analysis/file_tracker.dart +++ b/pkg/analyzer/lib/src/dart/analysis/file_tracker.dart @@ -11,76 +11,54 @@ import 'package:analyzer/src/dart/analysis/performance_logger.dart'; /// `null` if multiple files were added, changed, or removed. typedef FileTrackerChangeHook = void Function(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. - */ +/// 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. - */ + /// 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. - */ + /// The logger to write performed operations and performance to. final PerformanceLog _logger; - /** - * The current file system state. - */ + /// The current file system state. final FileSystemState _fsState; - /** - * The set of added files. - */ + /// The set of added files. final addedFiles = {}; - /** - * The set of files were reported as changed through [changeFile] and not - * checked for actual changes yet. - */ + /// The set of files were reported as changed through [changeFile] and not + /// checked for actual changes yet. final _changedFiles = {}; - /** - * The set of files that are currently scheduled for analysis, which were - * reported as changed through [changeFile]. - */ + /// The set of files that are currently scheduled for analysis, which were + /// reported as changed through [changeFile]. var _pendingChangedFiles = {}; - /** - * The set of files that are currently scheduled for analysis, which directly - * import a changed file. - */ + /// The set of files that are currently scheduled for analysis, which directly + /// import a changed file. var _pendingImportFiles = {}; - /** - * 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. - */ + /// 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 = {}; - /** - * The set of files that are currently scheduled for analysis, and don't - * have any special relation with changed files. - */ + /// The set of files that are currently scheduled for analysis, and don't + /// have any special relation with changed files. var _pendingFiles = {}; FileTracker(this._logger, this._fsState, this._changeHook); - /** - * Returns the path to exactly one that needs analysis. Throws a [StateError] - * if no files need analysis. - */ + /// 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; @@ -94,27 +72,19 @@ class FileTracker { 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. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// Returns a boolean indicating whether there are any files that need + /// analysis. bool get hasPendingFiles { return hasPendingChangedFiles || hasPendingImportFiles || @@ -122,15 +92,11 @@ class FileTracker { _pendingFiles.isNotEmpty; } - /** - * Return `true` if there are files that directly import a changed file that - * need analysis. - */ + /// 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. - */ + /// Returns a count of how many files need analysis. int get numberOfPendingFiles { return _pendingChangedFiles.length + _pendingImportFiles.length + @@ -138,9 +104,7 @@ class FileTracker { _pendingFiles.length; } - /** - * Adds the given [path] to the set of "added files". - */ + /// Adds the given [path] to the set of "added files". void addFile(String path) { _fsState.markFileForReading(path); addedFiles.add(path); @@ -148,18 +112,14 @@ class FileTracker { _changeHook(path); } - /** - * Adds the given [paths] to the set of "added files". - */ + /// Adds the given [paths] to the set of "added files". void addFiles(Iterable paths) { addedFiles.addAll(paths); _pendingFiles.addAll(paths); _changeHook(null); } - /** - * Adds the given [path] to the set of "changed files". - */ + /// Adds the given [path] to the set of "changed files". void changeFile(String path) { _changedFiles.add(path); if (addedFiles.contains(path)) { @@ -169,11 +129,9 @@ class FileTracker { _changeHook(path); } - /** - * Removes the given [path] from the set of "pending files". - * - * Should be called after the client has analyzed a file. - */ + /// 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); @@ -181,10 +139,8 @@ class FileTracker { _pendingFiles.remove(path); } - /** - * Returns a boolean indicating whether the given [path] points to a file that - * requires analysis. - */ + /// 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) || @@ -192,9 +148,7 @@ class FileTracker { _pendingFiles.contains(path); } - /** - * Removes the given [path] from the set of "added files". - */ + /// Removes the given [path] from the set of "added files". void removeFile(String path) { addedFiles.remove(path); _pendingChangedFiles.remove(path); @@ -208,17 +162,13 @@ class FileTracker { _changeHook(path); } - /** - * Schedule all added files for analysis. - */ + /// 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. - */ + /// 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}'); @@ -286,12 +236,10 @@ class FileTracker { }); } - /** - * 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`. - */ + /// 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) { diff --git a/pkg/analyzer/lib/src/dart/analysis/index.dart b/pkg/analyzer/lib/src/dart/analysis/index.dart index 816685dbb225..e13fb579b84d 100644 --- a/pkg/analyzer/lib/src/dart/analysis/index.dart +++ b/pkg/analyzer/lib/src/dart/analysis/index.dart @@ -57,10 +57,8 @@ Element declaredParameterElement( return element; } -/** - * Return the [CompilationUnitElement] that should be used for [element]. - * Throw [StateError] if the [element] is not linked into a unit. - */ +/// 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) { @@ -73,9 +71,7 @@ CompilationUnitElement getUnitElement(Element element) { throw StateError('Element not contained in compilation unit: $element'); } -/** - * Index the [unit] into a new [AnalysisDriverUnitIndexBuilder]. - */ +/// Index the [unit] into a new [AnalysisDriverUnitIndexBuilder]. AnalysisDriverUnitIndexBuilder indexUnit(CompilationUnit unit) { return _IndexAssembler().assemble(unit); } @@ -123,11 +119,10 @@ class ElementNameComponents { }); } -/** - * 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]. - */ +/// 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; @@ -189,51 +184,35 @@ class IndexElementInfo { IndexElementInfo._(this.element, this.kind); } -/** - * Information about an element referenced in index. - */ +/// Information about an element referenced in index. class _ElementInfo { - /** - * The identifier of the [CompilationUnitElement] containing this element. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ +/// Information about a single relation in a single compilation unit. class _ElementRelationInfo { final _ElementInfo elementInfo; final IndexRelationKind kind; @@ -245,73 +224,51 @@ class _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. - */ +/// 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. - */ + /// The string to use in place of the `null` string. static const NULL_STRING = '--nullString--'; - /** - * Map associating referenced elements with their [_ElementInfo]s. - */ + /// Map associating referenced elements with their [_ElementInfo]s. final Map elementMap = {}; - /** - * Map associating [CompilationUnitElement]s with their identifiers, which - * are indices into [unitLibraryUris] and [unitUnitUris]. - */ + /// Map associating [CompilationUnitElement]s with their identifiers, which + /// are indices into [unitLibraryUris] and [unitUnitUris]. final Map unitMap = {}; - /** - * The fields [unitLibraryUris] and [unitUnitUris] are used together to - * describe each unique [CompilationUnitElement]. - * - * This field contains the library URI of a unit. - */ + /// 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. - */ + /// 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. - */ + /// Map associating strings with their [_StringInfo]s. final Map stringMap = {}; - /** - * All element relations. - */ + /// All element relations. final List<_ElementRelationInfo> elementRelations = []; - /** - * All unresolved name relations. - */ + /// All unresolved name relations. final List<_NameRelationInfo> nameRelations = []; - /** - * All subtypes declared in the unit. - */ + /// All subtypes declared in the unit. final List<_SubtypeInfo> subtypes = []; - /** - * The [_StringInfo] to use for `null` strings. - */ + /// The [_StringInfo] to use for `null` strings. _StringInfo nullString; _IndexAssembler() { @@ -343,9 +300,7 @@ class _IndexAssembler { } } - /** - * Index the [unit] and assemble a new [AnalysisDriverUnitIndexBuilder]. - */ + /// Index the [unit] and assemble a new [AnalysisDriverUnitIndexBuilder]. AnalysisDriverUnitIndexBuilder assemble(CompilationUnit unit) { unit.accept(_IndexContributor(this)); @@ -422,10 +377,8 @@ class _IndexAssembler { }).toList()); } - /** - * Return the unique [_ElementInfo] corresponding the [element]. The field - * [_ElementInfo.id] is filled by [assemble] during final sorting. - */ + /// Return the unique [_ElementInfo] corresponding the [element]. The field + /// [_ElementInfo.id] is filled by [assemble] during final sorting. _ElementInfo _getElementInfo(Element element) { element = element.declaration; return elementMap.putIfAbsent(element, () { @@ -435,10 +388,8 @@ class _IndexAssembler { }); } - /** - * Return the unique [_StringInfo] corresponding the given [string]. The - * field [_StringInfo.id] is filled by [assemble] during final sorting. - */ + /// Return the unique [_StringInfo] corresponding the given [string]. The + /// field [_StringInfo.id] is filled by [assemble] during final sorting. _StringInfo _getStringInfo(String string) { if (string == null) { return nullString; @@ -449,11 +400,9 @@ class _IndexAssembler { }); } - /** - * Add information about [unitElement] to [unitUnitUris] and - * [unitLibraryUris] if necessary, and return the location in those - * arrays representing [unitElement]. - */ + /// 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); @@ -464,19 +413,15 @@ class _IndexAssembler { }); } - /** - * Return the unique [_StringInfo] corresponding [uri]. The field - * [_StringInfo.id] is filled by [assemble] during final sorting. - */ + /// 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. - */ + /// 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 = IndexElementInfo(element); element = info.element; @@ -492,9 +437,7 @@ class _IndexAssembler { } } -/** - * Visits a resolved AST and adds relationships into the [assembler]. - */ +/// Visits a resolved AST and adds relationships into the [assembler]. class _IndexContributor extends GeneralizingAstVisitor { final _IndexAssembler assembler; @@ -504,9 +447,7 @@ class _IndexContributor extends GeneralizingAstVisitor { _recordIsAncestorOf(descendant, descendant, false, []); } - /** - * Record that the name [node] has a relation of the given [kind]. - */ + /// Record that the name [node] has a relation of the given [kind]. void recordNameRelation( SimpleIdentifier node, IndexRelationKind kind, bool isQualified) { if (node != null) { @@ -514,19 +455,15 @@ class _IndexContributor extends GeneralizingAstVisitor { } } - /** - * Record reference to the given operator [Element]. - */ + /// 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. - */ + /// 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) { @@ -535,12 +472,10 @@ class _IndexContributor extends GeneralizingAstVisitor { } } - /** - * 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. - */ + /// 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. @@ -582,10 +517,8 @@ class _IndexContributor extends GeneralizingAstVisitor { assembler.addElementRelation(element, kind, offset, length, isQualified); } - /** - * Record that [element] has a relation of the given [kind] at the location - * of the given [token]. - */ + /// 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) { @@ -593,9 +526,7 @@ class _IndexContributor extends GeneralizingAstVisitor { } } - /** - * Record a relation between a super [typeName] and its [Element]. - */ + /// Record a relation between a super [typeName] and its [Element]. void recordSuperType(TypeName typeName, IndexRelationKind kind) { Identifier name = typeName?.name; if (name != null) { @@ -877,9 +808,7 @@ class _IndexContributor extends GeneralizingAstVisitor { } } - /** - * Record the given class as a subclass of its direct superclasses. - */ + /// Record the given class as a subclass of its direct superclasses. void _addSubtype(String name, {TypeName superclass, WithClause withClause, @@ -935,9 +864,7 @@ class _IndexContributor extends GeneralizingAstVisitor { assembler.addSubtype(name, members, supertypes); } - /** - * Record the given class as a subclass of its direct superclasses. - */ + /// Record the given class as a subclass of its direct superclasses. void _addSubtypeForClassDeclaration(ClassDeclaration node) { _addSubtype(node.name.name, superclass: node.extendsClause?.superclass, @@ -946,9 +873,7 @@ class _IndexContributor extends GeneralizingAstVisitor { memberNodes: node.members); } - /** - * Record the given class as a subclass of its direct superclasses. - */ + /// Record the given class as a subclass of its direct superclasses. void _addSubtypeForClassTypeAlis(ClassTypeAlias node) { _addSubtype(node.name.name, superclass: node.superclass, @@ -957,9 +882,7 @@ class _IndexContributor extends GeneralizingAstVisitor { memberNodes: const []); } - /** - * Record the given mixin as a subclass of its direct superclasses. - */ + /// Record the given mixin as a subclass of its direct superclasses. void _addSubtypeForMixinDeclaration(MixinDeclaration node) { _addSubtype(node.name.name, onClause: node.onClause, @@ -967,11 +890,9 @@ class _IndexContributor extends GeneralizingAstVisitor { 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. - */ + /// 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 seenConstructors = {}; @@ -987,10 +908,8 @@ class _IndexContributor extends GeneralizingAstVisitor { return constructor; } - /** - * Return `true` if [node] has an explicit or implicit qualifier, so that it - * cannot be shadowed by a local declaration. - */ + /// 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; @@ -1034,9 +953,7 @@ class _IndexContributor extends GeneralizingAstVisitor { } } -/** - * Information about a single name relation in single compilation unit. - */ +/// Information about a single name relation in single compilation unit. class _NameRelationInfo { final _StringInfo nameInfo; final IndexRelationKind kind; @@ -1046,41 +963,27 @@ class _NameRelationInfo { _NameRelationInfo(this.nameInfo, this.kind, this.offset, this.isQualified); } -/** - * Information about a string referenced in the index. - */ +/// Information about a string referenced in the index. class _StringInfo { - /** - * The value of the string. - */ + /// 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. - */ + /// 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. - */ +/// Information about a subtype in the index. class _SubtypeInfo { - /** - * The identifier of a direct supertype. - */ + /// The identifier of a direct supertype. final _StringInfo supertype; - /** - * The name of the class. - */ + /// The name of the class. final _StringInfo name; - /** - * The names of defined instance members. - */ + /// The names of defined instance members. final List<_StringInfo> members; _SubtypeInfo(this.supertype, this.name, this.members); diff --git a/pkg/analyzer/lib/src/dart/analysis/library_analyzer.dart b/pkg/analyzer/lib/src/dart/analysis/library_analyzer.dart index 4361edfebb95..14f05c923193 100644 --- a/pkg/analyzer/lib/src/dart/analysis/library_analyzer.dart +++ b/pkg/analyzer/lib/src/dart/analysis/library_analyzer.dart @@ -58,9 +58,7 @@ var timerLibraryAnalyzerResolve = Stopwatch(); var timerLibraryAnalyzerSplicer = Stopwatch(); var timerLibraryAnalyzerVerify = Stopwatch(); -/** - * Analyzer of a single library. - */ +/// Analyzer of a single library. class LibraryAnalyzer { /// A marker object used to prevent the initialization of /// [_versionConstraintFromPubspec] when the previous initialization attempt @@ -108,18 +106,14 @@ class LibraryAnalyzer { TypeSystemImpl get _typeSystem => _libraryElement.typeSystem; - /** - * Compute analysis results for all units of the library. - */ + /// Compute analysis results for all units of the library. Map analyze() { return PerformanceStatistics.analysis.makeCurrentWhile(() { return analyzeSync(); }); } - /** - * Compute analysis results for all units of the library. - */ + /// Compute analysis results for all units of the library. Map analyzeSync() { timerLibraryAnalyzer.start(); Map units = {}; @@ -215,9 +209,7 @@ class LibraryAnalyzer { unit.accept(constantVerifier); } - /** - * Compute [_constants] in all units. - */ + /// Compute [_constants] in all units. void _computeConstants() { computeConstants(_typeProvider, _typeSystem, _declaredVariables, _constants.toList(), _analysisOptions.experimentStatus); @@ -390,10 +382,8 @@ class LibraryAnalyzer { unit.accept(FfiVerifier(_typeSystem, errorReporter)); } - /** - * Return a subset of the given [errors] that are not marked as ignored in - * the [file]. - */ + /// Return a subset of the given [errors] that are not marked as ignored in + /// the [file]. List _filterIgnoredErrors( FileState file, List errors) { if (errors.isEmpty) { @@ -504,10 +494,8 @@ class LibraryAnalyzer { return workspace?.findPackageFor(libraryPath); } - /** - * 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. - */ + /// 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 directivesToResolve) { for (Directive directive in partUnit.directives) { @@ -539,16 +527,12 @@ class LibraryAnalyzer { return source == _library.source; } - /** - * Return `true` if the given [source] is a library. - */ + /// Return `true` if the given [source] is a library. bool _isLibrarySource(Source source) { return _isLibraryUri(source.uri); } - /** - * Return a new parsed unresolved [CompilationUnit]. - */ + /// Return a new parsed unresolved [CompilationUnit]. CompilationUnit _parse(FileState file) { AnalysisErrorListener errorListener = _getErrorListener(file); String content = file.content; @@ -734,10 +718,8 @@ class LibraryAnalyzer { featureSet: unit.featureSet, flowAnalysisHelper: flowAnalysisHelper)); } - /** - * Return the result of resolve the given [uriContent], reporting errors - * against the [uriLiteral]. - */ + /// 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 = @@ -811,10 +793,8 @@ class LibraryAnalyzer { } } - /** - * Check the given [directive] to see if the referenced source exists and - * report an error if it does not. - */ + /// 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) { String uriContent; @@ -846,10 +826,8 @@ class LibraryAnalyzer { .reportErrorForNode(errorCode, uriLiteral, [uriContent]); } - /** - * Check each directive in the given [unit] to see if the referenced source - * exists and report an error if it does not. - */ + /// 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) { @@ -858,10 +836,8 @@ class LibraryAnalyzer { } } - /** - * Return `true` if the given [source] refers to a file that is assumed to be - * generated. - */ + /// 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; @@ -885,9 +861,7 @@ class LibraryAnalyzer { } } -/** - * Analysis result for single file. - */ +/// Analysis result for single file. class UnitAnalysisResult { final FileState file; final CompilationUnit unit; @@ -896,9 +870,7 @@ class UnitAnalysisResult { UnitAnalysisResult(this.file, this.unit, this.errors); } -/** - * Either the name or the source associated with a part-of directive. - */ +/// Either the name or the source associated with a part-of directive. class _NameOrSource { final String name; final Source source; diff --git a/pkg/analyzer/lib/src/dart/analysis/library_context.dart b/pkg/analyzer/lib/src/dart/analysis/library_context.dart index 86fdc7f9ae6f..1e9dfc9d9242 100644 --- a/pkg/analyzer/lib/src/dart/analysis/library_context.dart +++ b/pkg/analyzer/lib/src/dart/analysis/library_context.dart @@ -31,12 +31,10 @@ 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]. - */ +/// 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; @@ -76,9 +74,7 @@ class LibraryContext { load2(targetLibrary); } - /** - * Computes a [CompilationUnitElement] for the given library/unit pair. - */ + /// Computes a [CompilationUnitElement] for the given library/unit pair. CompilationUnitElement computeUnitElement(FileState library, FileState unit) { var reference = elementFactory.rootReference .getChild(library.uriStr) @@ -87,16 +83,12 @@ class LibraryContext { return elementFactory.elementOfReference(reference); } - /** - * Get the [LibraryElement] for the given library. - */ + /// 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. - */ + /// Return `true` if the given [uri] is known to be a library. bool isLibraryUri(Uri uri) { String uriStr = uri.toString(); return elementFactory.isLibraryUri(uriStr); diff --git a/pkg/analyzer/lib/src/dart/analysis/performance_logger.dart b/pkg/analyzer/lib/src/dart/analysis/performance_logger.dart index 6e3caaa30622..4f25fe111bbc 100644 --- a/pkg/analyzer/lib/src/dart/analysis/performance_logger.dart +++ b/pkg/analyzer/lib/src/dart/analysis/performance_logger.dart @@ -66,12 +66,10 @@ class PerformanceLog { } } -/** - * 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]. - */ +/// 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; @@ -79,9 +77,7 @@ class PerformanceLogSection { PerformanceLogSection(this._logger, this._msg); - /** - * Stop the timer, log the time. - */ + /// Stop the timer, log the time. void exit() { _timer.stop(); _logger._level--; diff --git a/pkg/analyzer/lib/src/dart/analysis/referenced_names.dart b/pkg/analyzer/lib/src/dart/analysis/referenced_names.dart index 9f5f250727a6..82e5383e6927 100644 --- a/pkg/analyzer/lib/src/dart/analysis/referenced_names.dart +++ b/pkg/analyzer/lib/src/dart/analysis/referenced_names.dart @@ -5,19 +5,15 @@ import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; -/** - * Compute the set of external names referenced in the [unit]. - */ +/// Compute the set of external names referenced in the [unit]. Set computeReferencedNames(CompilationUnit unit) { _ReferencedNamesComputer computer = _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. - */ +/// 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 computeSubtypedNames(CompilationUnit unit) { Set subtypedNames = {}; @@ -54,9 +50,7 @@ Set computeSubtypedNames(CompilationUnit unit) { return subtypedNames; } -/** - * Chained set of local names, that hide corresponding external names. - */ +/// Chained set of local names, that hide corresponding external names. class _LocalNameScope { final _LocalNameScope enclosing; Set names; diff --git a/pkg/analyzer/lib/src/dart/analysis/search.dart b/pkg/analyzer/lib/src/dart/analysis/search.dart index 2f263d9c4790..2dba6d4b987e 100644 --- a/pkg/analyzer/lib/src/dart/analysis/search.dart +++ b/pkg/analyzer/lib/src/dart/analysis/search.dart @@ -26,17 +26,13 @@ Element _getEnclosingElement(CompilationUnitElement unitElement, int offset) { return element; } -/** - * Search support for an [AnalysisDriver]. - */ +/// Search support for an [AnalysisDriver]. class Search { final AnalysisDriver _driver; Search(this._driver); - /** - * Returns class or mixin members with the given [name]. - */ + /// Returns class or mixin members with the given [name]. Future> classMembers(String name) async { List elements = []; @@ -63,9 +59,7 @@ class Search { return elements; } - /** - * Returns references to the [element]. - */ + /// Returns references to the [element]. Future> references( Element element, SearchedFiles searchedFiles) async { if (element == null) { @@ -110,13 +104,11 @@ class Search { return const []; } - /** - * 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. - */ + /// 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> subTypes( ClassElement type, SearchedFiles searchedFiles) async { if (type == null) { @@ -131,9 +123,7 @@ class Search { return results; } - /** - * Return direct [SubtypeResult]s for either the [type] or [subtype]. - */ + /// Return direct [SubtypeResult]s for either the [type] or [subtype]. Future> subtypes(SearchedFiles searchedFiles, {ClassElement type, SubtypeResult subtype}) async { String name; @@ -168,9 +158,7 @@ class Search { return results; } - /** - * Returns top-level elements with names matching the given [regExp]. - */ + /// Returns top-level elements with names matching the given [regExp]. Future> topLevelElements(RegExp regExp) async { List elements = []; @@ -198,9 +186,7 @@ class Search { return elements; } - /** - * Returns unresolved references to the given [name]. - */ + /// Returns unresolved references to the given [name]. Future> unresolvedMemberReferences( String name, SearchedFiles searchedFiles) async { if (name == null) { @@ -274,9 +260,7 @@ class Search { } } - /** - * Add results for [element] usage in the given [file]. - */ + /// Add results for [element] usage in the given [file]. Future _addResultsInFile( List results, Element element, @@ -497,9 +481,7 @@ class Search { } } -/** - * Container that keeps track of file owners. - */ +/// Container that keeps track of file owners. class SearchedFiles { final Map pathOwners = {}; final Map uriOwners = {}; @@ -523,38 +505,24 @@ class SearchedFiles { } } -/** - * A single search result. - */ +/// A single search result. class SearchResult { - /** - * The deep most element that contains this result. - */ + /// The deep most element that contains this result. final Element enclosingElement; - /** - * The kind of the [element] usage. - */ + /// The kind of the [element] usage. final SearchResultKind kind; - /** - * The offset relative to the beginning of the containing file. - */ + /// The offset relative to the beginning of the containing file. final int offset; - /** - * The length of the usage in the containing file context. - */ + /// 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. - */ + /// 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]. - */ + /// Is `true` if the result is a resolved reference to [element]. final bool isQualified; SearchResult._(this.enclosingElement, this.kind, this.offset, this.length, @@ -581,33 +549,21 @@ class SearchResult { } } -/** - * The kind of reference in a [SearchResult]. - */ +/// The kind of reference in a [SearchResult]. enum SearchResultKind { READ, READ_WRITE, WRITE, INVOCATION, REFERENCE } -/** - * A single subtype of a type. - */ +/// A single subtype of a type. class SubtypeResult { - /** - * The URI of the library. - */ + /// The URI of the library. final String libraryUri; - /** - * The identifier of the subtype. - */ + /// The identifier of the subtype. final String id; - /** - * The name of the subtype. - */ + /// The name of the subtype. final String name; - /** - * The names of instance members declared in the class. - */ + /// The names of instance members declared in the class. final List members; SubtypeResult(this.libraryUri, this.id, this.name, this.members); @@ -616,9 +572,7 @@ class SubtypeResult { String toString() => id; } -/** - * A visitor that finds the deep-most [Element] that contains the [offset]. - */ +/// A visitor that finds the deep-most [Element] that contains the [offset]. class _ContainingElementFinder extends GeneralizingElementVisitor { final int offset; Element containingElement; @@ -638,9 +592,7 @@ class _ContainingElementFinder extends GeneralizingElementVisitor { } } -/** - * Visitor that adds [SearchResult]s for references to the [importElement]. - */ +/// Visitor that adds [SearchResult]s for references to the [importElement]. class _ImportElementReferencesVisitor extends RecursiveAstVisitor { final List results = []; @@ -734,10 +686,8 @@ class _IndexRequest { } } - /** - * Return the [element]'s identifier in the [index] or `-1` if the - * [element] is not referenced in the [index]. - */ + /// 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 = IndexElementInfo(element); element = info.element; @@ -781,14 +731,12 @@ class _IndexRequest { return -1; } - /** - * 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. - */ + /// 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> getRelations( int elementId, Map relationToResultKind, @@ -825,10 +773,8 @@ class _IndexRequest { return results; } - /** - * Return the identifier of [str] in the [index] or `-1` if [str] is not - * used in the [index]. - */ + /// Return the identifier of [str] in the [index] or `-1` if [str] is not + /// used in the [index]. int getStringId(String str) { if (str == null) { return index.nullStringId; @@ -837,10 +783,8 @@ class _IndexRequest { return binarySearch(index.strings, str); } - /** - * Return the identifier of the [CompilationUnitElement] containing the - * [element] in the [index] or `-1` if not found. - */ + /// 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); @@ -860,10 +804,8 @@ class _IndexRequest { return -1; } - /** - * Return a list of results where a class members with the given [name] is - * referenced with a qualifier, but is not resolved. - */ + /// Return a list of results where a class members with the given [name] is + /// referenced with a qualifier, but is not resolved. Future> getUnresolvedMemberReferences( String name, Map relationToResultKind, @@ -901,19 +843,15 @@ class _IndexRequest { return results; } - /** - * Return the identifier of the [uri] in the [index] or `-1` if the [uri] is - * not used in the [index]. - */ + /// 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. - */ + /// 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 sortedList, int value) { // Find an occurrence. int i = binarySearch(sortedList, value); @@ -928,11 +866,9 @@ class _IndexRequest { } } -/** - * 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. - */ +/// 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 results = []; diff --git a/pkg/analyzer/lib/src/dart/analysis/status.dart b/pkg/analyzer/lib/src/dart/analysis/status.dart index c6fd7a718298..af6c6b8ff842 100644 --- a/pkg/analyzer/lib/src/dart/analysis/status.dart +++ b/pkg/analyzer/lib/src/dart/analysis/status.dart @@ -4,9 +4,7 @@ import 'dart:async'; -/** - * The status of analysis. - */ +/// The status of analysis. class AnalysisStatus { static const IDLE = AnalysisStatus._(false); static const ANALYZING = AnalysisStatus._(true); @@ -15,42 +13,32 @@ class AnalysisStatus { const AnalysisStatus._(this._analyzing); - /** - * Return `true` if the scheduler is analyzing. - */ + /// Return `true` if the scheduler is analyzing. bool get isAnalyzing => _analyzing; - /** - * Return `true` if the scheduler is idle. - */ + /// 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. - */ +/// [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 _completer = Completer(); - /** - * Return a [Future] that completes when [notify] is called at least once. - */ + /// Return a [Future] that completes when [notify] is called at least once. Future get signal async { await _completer.future; _completer = Completer(); } - /** - * 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. - */ + /// 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); @@ -58,50 +46,35 @@ class Monitor { } } -/** - * Helper for managing transitioning [AnalysisStatus]. - */ +/// Helper for managing transitioning [AnalysisStatus]. class StatusSupport { - /** - * The controller for the [stream]. - */ + /// The controller for the [stream]. final _statusController = StreamController(); - /** - * The last status sent to the [stream]. - */ + /// 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. - */ + /// If non-null, a completer which should be completed on the next transition + /// to idle. Completer _idleCompleter; - /** - * Return the last status sent to the [stream]. - */ + /// Return the last status sent to the [stream]. AnalysisStatus get currentStatus => _currentStatus; - /** - * Return the stream that produces [AnalysisStatus] events. - */ + /// Return the stream that produces [AnalysisStatus] events. Stream 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]. - */ + /// 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 ??= Completer(); } - /** - * Send a notification to the [stream] that the scheduler started analyzing. - */ + /// Send a notification to the [stream] that the scheduler started analyzing. void transitionToAnalyzing() { if (_currentStatus != AnalysisStatus.ANALYZING) { preTransitionToAnalyzing(); @@ -110,9 +83,7 @@ class StatusSupport { } } - /** - * Send a notification to the [stream] stream that the scheduler is idle. - */ + /// Send a notification to the [stream] stream that the scheduler is idle. void transitionToIdle() { if (_currentStatus != AnalysisStatus.IDLE) { _currentStatus = AnalysisStatus.IDLE; @@ -122,12 +93,10 @@ class StatusSupport { _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. - */ + /// 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 waitForIdle() { return _idleCompleter?.future ?? Future.value(); } diff --git a/pkg/analyzer/lib/src/dart/analysis/uri_converter.dart b/pkg/analyzer/lib/src/dart/analysis/uri_converter.dart index 04e200bf1a28..da5f7e4e0850 100644 --- a/pkg/analyzer/lib/src/dart/analysis/uri_converter.dart +++ b/pkg/analyzer/lib/src/dart/analysis/uri_converter.dart @@ -8,19 +8,13 @@ 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. - */ +/// 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. - */ + /// 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. - */ + /// Initialize a newly created URI converter to use the given [driver] to = + /// perform the conversions. DriverBasedUriConverter(this.driver); @override diff --git a/pkg/analyzer/lib/src/dart/ast/ast_factory.dart b/pkg/analyzer/lib/src/dart/ast/ast_factory.dart index 90ee4ecc964b..f60676cd9481 100644 --- a/pkg/analyzer/lib/src/dart/ast/ast_factory.dart +++ b/pkg/analyzer/lib/src/dart/ast/ast_factory.dart @@ -10,10 +10,8 @@ import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:analyzer/src/generated/utilities_dart.dart'; import 'package:meta/meta.dart'; -/** - * Concrete implementation of [AstFactory] based on the standard AST - * implementation. - */ +/// Concrete implementation of [AstFactory] based on the standard AST +/// implementation. class AstFactoryImpl extends AstFactory { @override AdjacentStrings adjacentStrings(List strings) => diff --git a/pkg/analyzer/lib/src/dart/ast/constant_evaluator.dart b/pkg/analyzer/lib/src/dart/ast/constant_evaluator.dart index 897d7952e929..b1da5dee266d 100644 --- a/pkg/analyzer/lib/src/dart/ast/constant_evaluator.dart +++ b/pkg/analyzer/lib/src/dart/ast/constant_evaluator.dart @@ -9,95 +9,92 @@ 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. - * > * - * > An expression of the form identical(e1, e2) - * > where e1 and e2 are constant - * > expressions and identical() is statically bound to the predefined - * > dart function identical() discussed above. - * > - * > * - * > An expression of one of the forms e1 == e2 - * > or e1 != e2 where e1 and - * > e2 are constant expressions that evaluate to a - * > numeric, string or boolean value. - * > - * > * - * > An expression of one of the forms !e, e1 && - * > e2 or e1 || e2, where - * > e, e1 and e2 are constant - * > expressions that evaluate to a boolean value. - * > - * > * - * > An expression of one of the forms ~e, e1 ^ - * > e2, e1 & e2, - * > e1 | e2, e1 >> - * > e2 or e1 << e2, where - * > e, e1 and e2 are constant - * > expressions that evaluate to an integer value or to null. - * > - * > * - * > An expression of one of the forms -e, e1 - * > -e2, e1 * e2, - * > e1 / e2, e1 ~/ - * > e2, e1 > e2, - * > e1 < e2, e1 >= - * > e2, e1 <= e2 or - * > e1 % e2, where e, - * > e1 and e2 are constant expressions - * > that evaluate to a numeric value or to null. - * > - * > * - * > An expression of one the form e1 + e2, - * > e1 -e2 where e1 and - * > e2 are constant expressions that evaluate to a numeric or - * > string value or to null. - * > - * > * - * > An expression of the form e1 ? e2 : - * > e3 where e1, e2 and - * > e3 are constant expressions, and e1 - * > evaluates to a boolean value. - * > - * - * 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. - */ +/// 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. +/// > * +/// > An expression of the form identical(e1, e2) +/// > where e1 and e2 are constant +/// > expressions and identical() is statically bound to the predefined +/// > dart function identical() discussed above. +/// > +/// > * +/// > An expression of one of the forms e1 == e2 +/// > or e1 != e2 where e1 and +/// > e2 are constant expressions that evaluate to a +/// > numeric, string or boolean value. +/// > +/// > * +/// > An expression of one of the forms !e, e1 && +/// > e2 or e1 || e2, where +/// > e, e1 and e2 are constant +/// > expressions that evaluate to a boolean value. +/// > +/// > * +/// > An expression of one of the forms ~e, e1 ^ +/// > e2, e1 & e2, +/// > e1 | e2, e1 >> +/// > e2 or e1 << e2, where +/// > e, e1 and e2 are constant +/// > expressions that evaluate to an integer value or to null. +/// > +/// > * +/// > An expression of one of the forms -e, e1 +/// > -e2, e1 * e2, +/// > e1 / e2, e1 ~/ +/// > e2, e1 > e2, +/// > e1 < e2, e1 >= +/// > e2, e1 <= e2 or +/// > e1 % e2, where e, +/// > e1 and e2 are constant expressions +/// > that evaluate to a numeric value or to null. +/// > +/// > * +/// > An expression of one the form e1 + e2, +/// > e1 -e2 where e1 and +/// > e2 are constant expressions that evaluate to a numeric or +/// > string value or to null. +/// > +/// > * +/// > An expression of the form e1 ? e2 : +/// > e3 where e1, e2 and +/// > e3 are constant expressions, and e1 +/// > evaluates to a boolean value. +/// > +/// +/// 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 { - /** - * The value returned for expressions (or non-expression nodes) that are not - * compile-time constant expressions. - */ + /// The value returned for expressions (or non-expression nodes) that are not + /// compile-time constant expressions. static Object NOT_A_CONSTANT = Object(); @override @@ -383,10 +380,8 @@ class ConstantEvaluator extends GeneralizingAstVisitor { return buffer.toString(); } - /** - * Return the constant value of the static constant represented by the given - * [element]. - */ + /// 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) { diff --git a/pkg/analyzer/lib/src/dart/ast/to_source_visitor.dart b/pkg/analyzer/lib/src/dart/ast/to_source_visitor.dart index 81188ae75cbe..adf8d2b98db3 100644 --- a/pkg/analyzer/lib/src/dart/ast/to_source_visitor.dart +++ b/pkg/analyzer/lib/src/dart/ast/to_source_visitor.dart @@ -7,27 +7,19 @@ import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/src/dart/ast/ast.dart'; import 'package:meta/meta.dart'; -/** - * A visitor used to write a source representation of a visited AST node (and - * all of it's children) to a sink. - */ +/// A visitor used to write a source representation of a visited AST node (and +/// all of it's children) to a sink. class ToSourceVisitor implements AstVisitor { - /** - * The sink to which the source is to be written. - */ + /// 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]. - */ + /// Initialize a newly created visitor to write source code representing the + /// visited nodes to the given [sink]. ToSourceVisitor(this.sink); - /** - * Visit the given function [body], printing the [prefix] before if the body - * is not empty. - */ + /// 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) { @@ -36,9 +28,7 @@ class ToSourceVisitor implements AstVisitor { safelyVisitNode(body); } - /** - * Safely visit the given [node]. - */ + /// Safely visit the given [node]. @protected void safelyVisitNode(AstNode node) { if (node != null) { @@ -46,17 +36,13 @@ class ToSourceVisitor implements AstVisitor { } } - /** - * Print a list of [nodes] without any separation. - */ + /// Print a list of [nodes] without any separation. @protected void safelyVisitNodeList(NodeList nodes) { safelyVisitNodeListWithSeparator(nodes, ""); } - /** - * Print a list of [nodes], separated by the given [separator]. - */ + /// Print a list of [nodes], separated by the given [separator]. @protected void safelyVisitNodeListWithSeparator( NodeList nodes, String separator) { @@ -76,10 +62,8 @@ class ToSourceVisitor implements AstVisitor { } } - /** - * Print a list of [nodes], prefixed by the given [prefix] if the list is not - * empty, and separated by the given [separator]. - */ + /// 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 nodes, String separator) { @@ -97,10 +81,8 @@ class ToSourceVisitor implements AstVisitor { } } - /** - * Print a list of [nodes], separated by the given [separator], followed by - * the given [suffix] if the list is not empty. - */ + /// 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 nodes, String separator, String suffix) { @@ -118,10 +100,8 @@ class ToSourceVisitor implements AstVisitor { } } - /** - * Safely visit the given [node], printing the [prefix] before the node if it - * is non-`null`. - */ + /// 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) { @@ -130,10 +110,8 @@ class ToSourceVisitor implements AstVisitor { } } - /** - * Safely visit the given [node], printing the [suffix] after the node if it - * is non-`null`. - */ + /// 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) { @@ -142,9 +120,7 @@ class ToSourceVisitor implements AstVisitor { } } - /** - * Safely visit the given [token]. - */ + /// Safely visit the given [token]. @protected void safelyVisitToken(Token token) { if (token != null) { @@ -152,10 +128,8 @@ class ToSourceVisitor implements AstVisitor { } } - /** - * Safely visit the given [token], printing the [suffix] after the token if it - * is non-`null`. - */ + /// 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) { diff --git a/pkg/analyzer/lib/src/dart/ast/token.dart b/pkg/analyzer/lib/src/dart/ast/token.dart index 0833eb518755..d1753398020f 100644 --- a/pkg/analyzer/lib/src/dart/ast/token.dart +++ b/pkg/analyzer/lib/src/dart/ast/token.dart @@ -18,11 +18,9 @@ export 'package:_fe_analyzer_shared/src/scanner/token.dart' 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. - */ +/// 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; diff --git a/pkg/analyzer/lib/src/dart/ast/utilities.dart b/pkg/analyzer/lib/src/dart/ast/utilities.dart index 27b83c18dfc7..250c38e716a8 100644 --- a/pkg/analyzer/lib/src/dart/ast/utilities.dart +++ b/pkg/analyzer/lib/src/dart/ast/utilities.dart @@ -22,49 +22,33 @@ export 'package:analyzer/src/dart/ast/constant_evaluator.dart'; typedef ExceptionInDelegateHandler = void Function( 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. - */ +/// 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 { - /** - * A flag indicating whether tokens should be cloned while cloning an AST - * structure. - */ + /// A flag indicating whether tokens should be cloned while cloning an AST + /// structure. final bool cloneTokens; - /** - * Mapping from original tokes to cloned. - */ + /// Mapping from original tokes to cloned. final Map _clonedTokens = Map.identity(); - /** - * The next original token to clone. - */ + /// The next original token to clone. Token _nextToClone; - /** - * The last cloned token. - */ + /// The last cloned token. Token _lastCloned; - /** - * The offset of the last cloned token. - */ + /// 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. - */ + /// 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]. - */ + /// Return a clone of the given [node]. E cloneNode(E node) { if (node == null) { return null; @@ -72,10 +56,8 @@ class AstCloner implements AstVisitor { return node.accept(this) as E; } - /** - * Return a list containing cloned versions of the nodes in the given list of - * [nodes]. - */ + /// Return a list containing cloned versions of the nodes in the given list of + /// [nodes]. List cloneNodeList(List nodes) { int count = nodes.length; List clonedNodes = []; @@ -85,9 +67,7 @@ class AstCloner implements AstVisitor { return clonedNodes; } - /** - * Clone the given [token] if tokens are supposed to be cloned. - */ + /// Clone the given [token] if tokens are supposed to be cloned. Token cloneToken(Token token) { if (cloneTokens) { if (token == null) { @@ -104,9 +84,7 @@ class AstCloner implements AstVisitor { } } - /** - * Clone the given [tokens] if tokens are supposed to be cloned. - */ + /// Clone the given [tokens] if tokens are supposed to be cloned. List cloneTokenList(List tokens) { if (cloneTokens) { return tokens.map(cloneToken).toList(); @@ -1076,15 +1054,13 @@ class AstCloner implements AstVisitor { 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. - */ + /// 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; @@ -1121,73 +1097,55 @@ class AstCloner implements AstVisitor { } } - /** - * Return a clone of the given [node]. - */ + /// Return a clone of the given [node]. static AstNode clone(AstNode node) { return node.accept(AstCloner()); } } -/** - * An AstVisitor that compares the structure of two AstNodes to see whether they - * are equal. - */ +/// An AstVisitor that compares the structure of two AstNodes to see whether +/// they are equal. class AstComparator implements AstVisitor { - /** - * 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). - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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); @@ -1200,13 +1158,11 @@ class AstComparator implements AstVisitor { 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. - */ + /// 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); @@ -1218,10 +1174,8 @@ class AstComparator implements AstVisitor { 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`. - */ + /// 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 && @@ -2344,10 +2298,8 @@ class AstComparator implements AstVisitor { 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. - */ + /// 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); @@ -2366,10 +2318,8 @@ class AstComparator implements AstVisitor { return true; } - /** - * Return `true` if the [first] and [second] lists of tokens have the same - * length and corresponding elements are equal. - */ + /// Return `true` if the [first] and [second] lists of tokens have the same + /// length and corresponding elements are equal. bool _isEqualTokenLists(List first, List second) { int length = first.length; if (second.length != length) { @@ -2383,33 +2333,25 @@ class AstComparator implements AstVisitor { return true; } - /** - * Return `true` if the [first] and [second] nodes are equal. - */ + /// Return `true` if the [first] and [second] nodes are equal. static bool equalNodes(AstNode first, AstNode second) { AstComparator comparator = 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]. - */ +/// 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 { - /** - * A flag indicating whether an identifier from a deferred library has been - * found. - */ + /// 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. - */ + /// Return `true` if the visitor found a [PrefixedIdentifier] that returned + /// `true` to the [PrefixedIdentifier.isDeferred] query. bool get result => _result; @override @@ -2422,24 +2364,18 @@ class DeferredLibraryReferenceDetector extends RecursiveAstVisitor { } } -/** - * 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. - */ +/// 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 extends DelegatingAstVisitor { - /** - * The function that will be executed for each exception that is thrown by one - * of the visit methods on the delegate. - */ + /// 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. - */ + /// Initialize a newly created visitor to use each of the given delegate + /// visitors to visit the nodes of an AST structure. ExceptionHandlingDelegatingAstVisitor( Iterable> delegates, this.handler) : super(delegates) { @@ -2461,10 +2397,8 @@ class ExceptionHandlingDelegatingAstVisitor extends DelegatingAstVisitor { 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. - */ + /// 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 = StringBuffer(); @@ -2486,49 +2420,35 @@ class ExceptionHandlingDelegatingAstVisitor extends DelegatingAstVisitor { } } -/** - * 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. - */ +/// 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 { - /** - * The start offset of the range used to identify the node. - */ + /// The start offset of the range used to identify the node. final int _startOffset; - /** - * The end offset of the range used to identify the node. - */ + /// The end offset of the range used to identify the node. final int _endOffset; - /** - * The element that was found that corresponds to the given source range, or - * `null` if there is no such element. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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; @@ -2593,11 +2513,9 @@ class NodeLocator extends UnifyingAstVisitor { } } -/** - * 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. - */ +/// 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 { /// The inclusive start offset of the range used to identify the node. final int _startOffset; @@ -2605,26 +2523,20 @@ class NodeLocator2 extends UnifyingAstVisitor { /// The inclusive end offset of the range used to identify the node. final int _endOffset; - /** - * The found node or `null` if there is no such node. - */ + /// 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]. - */ + /// 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. - */ + /// 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; @@ -2633,9 +2545,10 @@ class NodeLocator2 extends UnifyingAstVisitor { node.accept(this); } catch (exception, stackTrace) { // TODO(39284): should this exception be silent? - AnalysisEngine.instance.instrumentationService.logException( - SilentException( - "Unable to locate element at offset ($_startOffset - $_endOffset)", + AnalysisEngine.instance.instrumentationService + .logException(SilentException( + 'Unable to locate element at offset ' + '($_startOffset - $_endOffset)', exception, stackTrace)); return null; @@ -2689,24 +2602,16 @@ class NodeLocator2 extends UnifyingAstVisitor { } } -/** - * An object that will replace one child node in an AST node with another node. - */ +/// An object that will replace one child node in an AST node with another node. class NodeReplacer implements AstVisitor { - /** - * The node being replaced. - */ + /// The node being replaced. final AstNode _oldNode; - /** - * The node that is replacing the old node. - */ + /// The node that is replacing the old node. final AstNode _newNode; - /** - * Initialize a newly created node locator to replace the [_oldNode] with the - * [_newNode]. - */ + /// Initialize a newly created node locator to replace the [_oldNode] with the + /// [_newNode]. NodeReplacer(this._oldNode, this._newNode); @override @@ -4044,13 +3949,11 @@ class NodeReplacer implements AstVisitor { 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. - */ + /// 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 ArgumentError("The old and new nodes must be non-null"); @@ -4066,17 +3969,13 @@ class NodeReplacer implements AstVisitor { } } -/** - * 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. - */ +/// 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 { - /** - * 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). - */ + /// 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 @@ -5488,9 +5387,7 @@ class ResolutionCopier implements AstVisitor { _isEqualTokens(node.semicolon, toNode.semicolon)); } - /** - * Return `true` if all of the parameters are `true`. - */ + /// Return `true` if all of the parameters are `true`. bool _and(bool b1, bool b2, [bool b3 = true, bool b4 = true, @@ -5519,10 +5416,8 @@ class ResolutionCopier implements AstVisitor { b13; } - /** - * Return `true` if the [first] and [second] lists of AST nodes have the same - * size and corresponding elements are equal. - */ + /// 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; @@ -5542,11 +5437,9 @@ class ResolutionCopier implements AstVisitor { 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. - */ + /// 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; @@ -5575,10 +5468,8 @@ class ResolutionCopier implements AstVisitor { return false; } - /** - * Return `true` if the [first] and [second] arrays of tokens have the same - * length and corresponding elements are equal. - */ + /// Return `true` if the [first] and [second] arrays of tokens have the same + /// length and corresponding elements are equal. bool _isEqualTokenLists(List first, List second) { int length = first.length; if (second.length != length) { @@ -5592,9 +5483,7 @@ class ResolutionCopier implements AstVisitor { return true; } - /** - * Return `true` if the [first] and [second] tokens have the same structure. - */ + /// Return `true` if the [first] and [second] tokens have the same structure. bool _isEqualTokens(Token first, Token second) { if (first == null) { return second == null; @@ -5604,24 +5493,20 @@ class ResolutionCopier implements AstVisitor { return first.lexeme == second.lexeme; } - /** - * Copy resolution data from the [fromNode] to the [toNode]. - */ + /// Copy resolution data from the [fromNode] to the [toNode]. static void copyResolutionData(AstNode fromNode, AstNode toNode) { ResolutionCopier copier = 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. - */ +/// 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 { Declaration _declarationNode; @@ -5757,10 +5642,9 @@ class ScopedNameFinder extends GeneralizingAstVisitor { } } - /** - * 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. - */ + /// 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 statements) { for (Statement statement in statements) { if (identical(statement, _immediateChild)) { @@ -5785,10 +5669,8 @@ class ScopedNameFinder extends GeneralizingAstVisitor { } } -/** - * A visitor used to write a source representation of a visited AST node (and - * all of it's children) to a sink. - */ +/// A visitor used to write a source representation of a visited AST node (and +/// all of it's children) to a sink. @Deprecated('Use ToSourceVisitor') class ToSourceVisitor2 extends ToSourceVisitor { ToSourceVisitor2(StringSink sink) : super(sink); diff --git a/pkg/analyzer/lib/src/dart/element/greatest_lower_bound.dart b/pkg/analyzer/lib/src/dart/element/greatest_lower_bound.dart index 96dab6b2ef5e..e46904e9d360 100644 --- a/pkg/analyzer/lib/src/dart/element/greatest_lower_bound.dart +++ b/pkg/analyzer/lib/src/dart/element/greatest_lower_bound.dart @@ -257,12 +257,10 @@ class GreatestLowerBoundHelper { return NeverTypeImpl.instance; } - /** - * Compute the greatest lower bound of function types [f] and [g]. - * - * https://github.com/dart-lang/language - * See `resources/type-system/upper-lower-bounds.md` - */ + /// Compute the greatest lower bound of function types [f] and [g]. + /// + /// https://github.com/dart-lang/language + /// See `resources/type-system/upper-lower-bounds.md` DartType _functionType(FunctionType f, FunctionType g) { var fTypeFormals = f.typeFormals; var gTypeFormals = g.typeFormals; diff --git a/pkg/analyzer/lib/src/dart/element/least_upper_bound.dart b/pkg/analyzer/lib/src/dart/element/least_upper_bound.dart index 173c8c4cc6de..8ad806846075 100644 --- a/pkg/analyzer/lib/src/dart/element/least_upper_bound.dart +++ b/pkg/analyzer/lib/src/dart/element/least_upper_bound.dart @@ -254,10 +254,8 @@ class InterfaceLeastUpperBoundHelper { return _computeTypeAtMaxUniqueDepth(s); } - /** - * Return the length of the longest inheritance path from the [element] to - * Object. - */ + /// Return the length of the longest inheritance path from the [element] to + /// Object. @visibleForTesting static int computeLongestInheritancePathToObject(ClassElement element) { return _computeLongestInheritancePathToObject( @@ -407,10 +405,8 @@ class InterfaceLeastUpperBoundHelper { return null; } - /** - * Return the intersection of the [first] and [second] sets of types, where - * intersection is based on the equality of the types themselves. - */ + /// Return the intersection of the [first] and [second] sets of types, where + /// intersection is based on the equality of the types themselves. static List _intersection( Set first, Set second, @@ -435,12 +431,10 @@ class LeastUpperBoundHelper { InterfaceType get _objectType => _typeSystem.typeProvider.objectType; - /** - * Compute the least upper bound of two types. - * - * https://github.com/dart-lang/language - * See `resources/type-system/upper-lower-bounds.md` - */ + /// Compute the least upper bound of two types. + /// + /// https://github.com/dart-lang/language + /// See `resources/type-system/upper-lower-bounds.md` DartType getLeastUpperBound(DartType T1, DartType T2) { // UP(T, T) = T if (identical(T1, T2)) { @@ -678,12 +672,10 @@ class LeastUpperBoundHelper { return helper.compute(T1, T2); } - /** - * Compute the least upper bound of function types [f] and [g]. - * - * https://github.com/dart-lang/language - * See `resources/type-system/upper-lower-bounds.md` - */ + /// Compute the least upper bound of function types [f] and [g]. + /// + /// https://github.com/dart-lang/language + /// See `resources/type-system/upper-lower-bounds.md` DartType _functionType(FunctionType f, FunctionType g) { var fTypeFormals = f.typeFormals; var gTypeFormals = g.typeFormals; diff --git a/pkg/analyzer/lib/src/dart/element/member.dart b/pkg/analyzer/lib/src/dart/element/member.dart index c4ceea2339c3..7fccac1927ea 100644 --- a/pkg/analyzer/lib/src/dart/element/member.dart +++ b/pkg/analyzer/lib/src/dart/element/member.dart @@ -17,15 +17,11 @@ 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. - */ +/// 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 [declaration], and applied [substitution]. - */ + /// Initialize a newly created element to represent a constructor, based on + /// the [declaration], and applied [substitution]. ConstructorMember( ConstructorElement declaration, MapSubstitution substitution, @@ -96,13 +92,11 @@ class ConstructorMember extends ExecutableMember implements ConstructorElement { builder.writeConstructorElement(this); } - /** - * 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. - */ + /// 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) { @@ -129,25 +123,21 @@ class ConstructorMember extends ExecutableMember implements ConstructorElement { } } -/** - * An executable element defined in a parameterized type where the values of the - * type parameters are known. - */ +/// An executable element defined in a parameterized type where the values of +/// the type parameters are known. abstract class ExecutableMember extends Member implements ExecutableElement { @override final List typeParameters; FunctionType _type; - /** - * Initialize a newly created element to represent a callable element (like a - * method or function or property), based on the [declaration], and applied - * [substitution]. - * - * The [typeParameters] are fresh, and [substitution] is already applied to - * their bounds. The [substitution] includes replacing [declaration] type - * parameters with the provided fresh [typeParameters]. - */ + /// Initialize a newly created element to represent a callable element (like a + /// method or function or property), based on the [declaration], and applied + /// [substitution]. + /// + /// The [typeParameters] are fresh, and [substitution] is already applied to + /// their bounds. The [substitution] includes replacing [declaration] type + /// parameters with the provided fresh [typeParameters]. ExecutableMember( ExecutableElement declaration, MapSubstitution substitution, @@ -264,10 +254,8 @@ abstract class ExecutableMember extends Member implements ExecutableElement { } } -/** - * A parameter element defined in a parameterized type where the values of the - * type parameters are known. - */ +/// A parameter element defined in a parameterized type where the values of the +/// type parameters are known. class FieldFormalParameterMember extends ParameterMember implements FieldFormalParameterElement { factory FieldFormalParameterMember( @@ -312,15 +300,11 @@ class FieldFormalParameterMember extends ParameterMember visitor.visitFieldFormalParameterElement(this); } -/** - * A field element defined in a parameterized type where the values of the type - * parameters are known. - */ +/// 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 - * [declaration], with applied [substitution]. - */ + /// Initialize a newly created element to represent a field, based on the + /// [declaration], with applied [substitution]. FieldMember( FieldElement declaration, MapSubstitution substitution, @@ -364,13 +348,11 @@ class FieldMember extends VariableMember implements FieldElement { @override T accept(ElementVisitor visitor) => visitor.visitFieldElement(this); - /** - * 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. - */ + /// 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; @@ -414,39 +396,27 @@ class FunctionMember extends ExecutableMember implements FunctionElement { } } -/** - * An element defined in a parameterized type where the values of the type - * parameters are known. - */ +/// 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. - */ + /// The element on which the parameterized element was created. final Element _declaration; - /** - * The substitution for type parameters referenced in the base element. - */ + /// The substitution for type parameters referenced in the base element. final MapSubstitution _substitution; - /** - * If `true`, then this is a legacy view on a NNBD element. - */ + /// If `true`, then this is a legacy view on a NNBD element. final bool isLegacy; - /** - * Initialize a newly created element to represent a member, based on the - * [declaration], and applied [_substitution]. - */ + /// Initialize a newly created element to represent a member, based on the + /// [declaration], and applied [_substitution]. Member(this._declaration, this._substitution, this.isLegacy) { if (_declaration is Member) { throw StateError('Members must be created from a declarations.'); } } - /** - * Return the element on which the parameterized element was created. - */ + /// Return the element on which the parameterized element was created. @Deprecated('Use Element.declaration instead') Element get baseElement => _declaration; @@ -555,9 +525,7 @@ abstract class Member implements Element { @override Source get source => _declaration.source; - /** - * The substitution for type parameters referenced in the base element. - */ + /// The substitution for type parameters referenced in the base element. MapSubstitution get substitution => _substitution; /// Append a textual representation of this element to the given [builder]. @@ -586,9 +554,7 @@ abstract class Member implements Element { bool isAccessibleIn(LibraryElement library) => _declaration.isAccessibleIn(library); - /** - * Use the given [visitor] to visit all of the [children]. - */ + /// Use the given [visitor] to visit all of the [children]. void safelyVisitChildren(List children, ElementVisitor visitor) { // TODO(brianwilkerson) Make this private if (children != null) { @@ -683,10 +649,8 @@ abstract class Member implements Element { } } -/** - * A method element defined in a parameterized type where the values of the type - * parameters are known. - */ +/// A method element defined in a parameterized type where the values of the +/// type parameters are known. class MethodMember extends ExecutableMember implements MethodElement { factory MethodMember( MethodElement declaration, @@ -725,13 +689,11 @@ class MethodMember extends ExecutableMember implements MethodElement { @override T accept(ElementVisitor visitor) => visitor.visitMethodElement(this); - /** - * 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. - */ + /// 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; @@ -755,10 +717,8 @@ class MethodMember extends ExecutableMember implements MethodElement { } } -/** - * A parameter element defined in a parameterized type where the values of the - * type parameters are known. - */ +/// 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 { @@ -782,10 +742,8 @@ class ParameterMember extends VariableMember ); } - /** - * Initialize a newly created element to represent a parameter, based on the - * [declaration], with applied [substitution]. - */ + /// Initialize a newly created element to represent a parameter, based on the + /// [declaration], with applied [substitution]. ParameterMember._( ParameterElement declaration, MapSubstitution substitution, @@ -861,10 +819,8 @@ class ParameterMember extends VariableMember } } -/** - * A property accessor element defined in a parameterized type where the values - * of the type parameters are known. - */ +/// A property accessor element defined in a parameterized type where the values +/// of the type parameters are known. class PropertyAccessorMember extends ExecutableMember implements PropertyAccessorElement { factory PropertyAccessorMember( @@ -950,13 +906,11 @@ class PropertyAccessorMember extends ExecutableMember ); } - /** - * 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. - */ + /// 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) { @@ -1006,17 +960,13 @@ class TopLevelVariableMember extends VariableMember } } -/** - * A variable element defined in a parameterized type where the values of the - * type parameters are known. - */ +/// 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 - * [declaration], with applied [substitution]. - */ + /// Initialize a newly created element to represent a variable, based on the + /// [declaration], with applied [substitution]. VariableMember( VariableElement declaration, MapSubstitution substitution, diff --git a/pkg/analyzer/lib/src/dart/element/top_merge.dart b/pkg/analyzer/lib/src/dart/element/top_merge.dart index e89ffb1d70f3..7b2b5a56c646 100644 --- a/pkg/analyzer/lib/src/dart/element/top_merge.dart +++ b/pkg/analyzer/lib/src/dart/element/top_merge.dart @@ -17,14 +17,12 @@ class TopMergeHelper { TopMergeHelper(this.typeSystem); - /** - * Merges two types into a single type. - * Compute the canonical representation of [T]. - * - * https://github.com/dart-lang/language/ - * See `accepted/future-releases/nnbd/feature-specification.md` - * See `#classes-defined-in-opted-in-libraries` - */ + /// Merges two types into a single type. + /// Compute the canonical representation of [T]. + /// + /// https://github.com/dart-lang/language/ + /// See `accepted/future-releases/nnbd/feature-specification.md` + /// See `#classes-defined-in-opted-in-libraries` DartType topMerge(DartType T, DartType S) { var T_nullability = T.nullabilitySuffix; var S_nullability = S.nullabilitySuffix; diff --git a/pkg/analyzer/lib/src/dart/element/type.dart b/pkg/analyzer/lib/src/dart/element/type.dart index 04d8359de73c..2b059e6121a4 100644 --- a/pkg/analyzer/lib/src/dart/element/type.dart +++ b/pkg/analyzer/lib/src/dart/element/type.dart @@ -44,18 +44,12 @@ List _transformOrShare(List list, T Function(T) transform) { return list; } -/** - * The [Type] representing the type `dynamic`. - */ +/// The [Type] representing the type `dynamic`. class DynamicTypeImpl extends TypeImpl { - /** - * The unique instance of this class. - */ + /// The unique instance of this class. static final DynamicTypeImpl instance = DynamicTypeImpl._(); - /** - * Prevent the creation of instances of this class. - */ + /// Prevent the creation of instances of this class. DynamicTypeImpl._() : super(DynamicElementImpl()); @override @@ -109,9 +103,7 @@ class DynamicTypeImpl extends TypeImpl { } } -/** - * The type of a function, method, constructor, getter, or setter. - */ +/// The type of a function, method, constructor, getter, or setter. class FunctionTypeImpl extends TypeImpl implements FunctionType { @override final DartType returnType; @@ -378,21 +370,19 @@ class FunctionTypeImpl extends TypeImpl implements FunctionType { } } - /** - * 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. - */ + /// 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 Function(DartType t, DartType s) returnRelation, {bool Function(ParameterElement t, ParameterElement s) parameterRelation, @@ -542,17 +532,15 @@ class FunctionTypeImpl extends TypeImpl implements FunctionType { 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. ``) 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` and `U -> U` we can instantiate them with - * `F` to get `F -> F` and `F -> F`, which we can see are equal. - */ + /// 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. ``) 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` and `U -> U` we can instantiate them + /// with `F` to get `F -> F` and `F -> F`, which we can see are equal. static List relateTypeFormals( FunctionType f1, FunctionType f2, @@ -680,9 +668,7 @@ class FunctionTypeImpl extends TypeImpl implements FunctionType { } } -/** - * A concrete implementation of an [InterfaceType]. - */ +/// A concrete implementation of an [InterfaceType]. class InterfaceTypeImpl extends TypeImpl implements InterfaceType { @override final List typeArguments; @@ -690,19 +676,13 @@ class InterfaceTypeImpl extends TypeImpl implements InterfaceType { @override final NullabilitySuffix nullabilitySuffix; - /** - * Cached [ConstructorElement]s - members or raw elements. - */ + /// Cached [ConstructorElement]s - members or raw elements. List _constructors; - /** - * Cached [PropertyAccessorElement]s - members or raw elements. - */ + /// Cached [PropertyAccessorElement]s - members or raw elements. List _accessors; - /** - * Cached [MethodElement]s - members or raw elements. - */ + /// Cached [MethodElement]s - members or raw elements. List _methods; InterfaceTypeImpl({ @@ -898,22 +878,20 @@ class InterfaceTypeImpl extends TypeImpl implements InterfaceType { builder.writeInterfaceType(this); } - /** - * 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 {} - * class B implements A {} - * class C implements A {} - * ``` - * Asking the type `B` for the type associated with `A` will return the - * type `A`. Asking the type `C` for the type associated with `A` will - * return the type `A`. - */ + /// 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 {} + /// class B implements A {} + /// class C implements A {} + /// ``` + /// Asking the type `B` for the type associated with `A` will return the + /// type `A`. Asking the type `C` for the type associated with `A` will + /// return the type `A`. InterfaceType asInstanceOf(ClassElement targetElement) { if (element == targetElement) { return this; @@ -1462,10 +1440,8 @@ class InterfaceTypeImpl extends TypeImpl implements InterfaceType { 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`. - */ + /// 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 types, TypeSystemImpl typeSystem) { // The << relation ("more specific than") is a partial ordering on types, @@ -1518,14 +1494,12 @@ class InterfaceTypeImpl extends TypeImpl implements InterfaceType { 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]. - */ + /// 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 @@ -1538,15 +1512,13 @@ class InterfaceTypeImpl extends TypeImpl implements InterfaceType { return 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. - */ + /// 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; @@ -1656,45 +1628,35 @@ class InterfaceTypeImpl extends TypeImpl implements InterfaceType { } } -/** - * The type `Never` represents the uninhabited bottom type. - */ +/// The type `Never` represents the uninhabited bottom type. class NeverTypeImpl 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). - */ + /// 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 NeverTypeImpl instanceNullable = NeverTypeImpl._(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. - */ + /// 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 NeverTypeImpl instanceLegacy = NeverTypeImpl._(NullabilitySuffix.star); - /** - * The unique instance of this class, non-nullable. - */ + /// The unique instance of this class, non-nullable. static final NeverTypeImpl instance = NeverTypeImpl._(NullabilitySuffix.none); @override final NullabilitySuffix nullabilitySuffix; - /** - * Prevent the creation of instances of this class. - */ + /// Prevent the creation of instances of this class. NeverTypeImpl._(this.nullabilitySuffix) : super(NeverElementImpl()); @override @@ -1759,20 +1721,14 @@ class NeverTypeImpl extends TypeImpl { } } -/** - * The abstract class `TypeImpl` implements the behavior common to objects - * representing the declared type of elements in the element model. - */ +/// 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. - */ + /// 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; - /** - * Initialize a newly created type to be declared by the given [element]. - */ + /// Initialize a newly created type to be declared by the given [element]. TypeImpl(this._element); @deprecated @@ -1848,9 +1804,7 @@ abstract class TypeImpl implements DartType { @override NullabilitySuffix get nullabilitySuffix; - /** - * Append a textual representation of this type to the given [builder]. - */ + /// Append a textual representation of this type to the given [builder]. void appendTo(ElementDisplayStringBuilder builder); @override @@ -1877,10 +1831,8 @@ abstract class TypeImpl implements DartType { @override DartType resolveToBound(DartType objectType) => this; - /** - * Return the type resulting from substituting the given [argumentTypes] for - * the given [parameterTypes] in this type. - */ + /// Return the type resulting from substituting the given [argumentTypes] for + /// the given [parameterTypes] in this type. @override @deprecated DartType substitute2( @@ -1891,24 +1843,20 @@ abstract class TypeImpl implements DartType { return getDisplayString(withNullability: false); } - /** - * 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 [TypeSystemImpl]. - */ + /// 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 [TypeSystemImpl]. TypeImpl withNullability(NullabilitySuffix nullabilitySuffix); - /** - * Return `true` if corresponding elements of the [first] and [second] lists - * of type arguments are all equal. - */ + /// Return `true` if corresponding elements of the [first] and [second] lists + /// of type arguments are all equal. static bool equalArrays(List first, List second) { if (first.length != second.length) { return false; @@ -1930,10 +1878,9 @@ abstract class TypeImpl implements DartType { 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]. - */ + /// Return a list containing the results of using the given [argumentTypes] + /// and [parameterTypes] to perform a substitution on all of the given + /// [types]. @deprecated static List substitute(List types, List argumentTypes, List parameterTypes) { @@ -1949,9 +1896,7 @@ abstract class TypeImpl implements DartType { } } -/** - * A concrete implementation of a [TypeParameterType]. - */ +/// A concrete implementation of a [TypeParameterType]. class TypeParameterTypeImpl extends TypeImpl implements TypeParameterType { @override final NullabilitySuffix nullabilitySuffix; @@ -1962,10 +1907,8 @@ class TypeParameterTypeImpl extends TypeImpl implements TypeParameterType { /// is therefore the same as the bound of [element]. final DartType promotedBound; - /** - * Initialize a newly created type parameter type to be declared by the given - * [element] and to have the given name. - */ + /// Initialize a newly created type parameter type to be declared by the given + /// [element] and to have the given name. TypeParameterTypeImpl({ @required TypeParameterElement element, @required this.nullabilitySuffix, @@ -2053,7 +1996,8 @@ class TypeParameterTypeImpl extends TypeImpl implements TypeParameterType { if (parameterType is TypeParameterTypeImpl && parameterType == this) { TypeImpl argumentType = argumentTypes[i]; - // TODO(scheglov) It should not happen, but sometimes arguments are null. + // TODO(scheglov) It should not happen, but sometimes arguments are + // null. if (argumentType == null) { return argumentType; } @@ -2101,10 +2045,8 @@ class TypeParameterTypeImpl extends TypeImpl implements TypeParameterType { ); } - /** - * Return a list containing the type parameter types defined by the given - * array of type parameter elements ([typeParameters]). - */ + /// Return a list containing the type parameter types defined by the given + /// array of type parameter elements ([typeParameters]). @deprecated static List getTypes( List typeParameters) { @@ -2120,9 +2062,7 @@ class TypeParameterTypeImpl extends TypeImpl implements TypeParameterType { } } -/** - * The type `void`. - */ +/// The type `void`. abstract class VoidType implements DartType { @override @deprecated @@ -2130,18 +2070,12 @@ abstract class VoidType implements DartType { List argumentTypes, List parameterTypes); } -/** - * A concrete implementation of a [VoidType]. - */ +/// A concrete implementation of a [VoidType]. class VoidTypeImpl extends TypeImpl implements VoidType { - /** - * The unique instance of this class, with indeterminate nullability. - */ + /// The unique instance of this class, with indeterminate nullability. static final VoidTypeImpl instance = VoidTypeImpl._(); - /** - * Prevent the creation of instances of this class. - */ + /// Prevent the creation of instances of this class. VoidTypeImpl._() : super(null); @override diff --git a/pkg/analyzer/lib/src/dart/micro/cider_byte_store.dart b/pkg/analyzer/lib/src/dart/micro/cider_byte_store.dart index af6b3afae91e..60e8d0fd3c2c 100644 --- a/pkg/analyzer/lib/src/dart/micro/cider_byte_store.dart +++ b/pkg/analyzer/lib/src/dart/micro/cider_byte_store.dart @@ -4,26 +4,22 @@ import 'package:collection/collection.dart'; -/** - * Store of bytes associated with string keys and a hash. - * - * 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. - */ +/// Store of bytes associated with string keys and a hash. +/// +/// 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. abstract class CiderByteStore { - /** - * Return the bytes associated with the errors for given [key] and [signature]. - * Return `null` if the association does not exist. - */ + /// Return the bytes associated with the errors for given [key] and + /// [signature]. + /// + /// Return `null` if the association does not exist. List get(String key, List signature); - /** - * Associate the given [bytes] with the [key] and [digest]. - */ + /// Associate the given [bytes] with the [key] and [digest]. void put(String key, List signature, List bytes); } diff --git a/pkg/analyzer/lib/src/dart/micro/library_analyzer.dart b/pkg/analyzer/lib/src/dart/micro/library_analyzer.dart index 3eccdb9ac88f..afb8442ee2c9 100644 --- a/pkg/analyzer/lib/src/dart/micro/library_analyzer.dart +++ b/pkg/analyzer/lib/src/dart/micro/library_analyzer.dart @@ -49,9 +49,7 @@ import 'package:analyzer/src/workspace/workspace.dart'; import 'package:meta/meta.dart'; import 'package:pub_semver/pub_semver.dart'; -/** - * Analyzer of a single library. - */ +/// Analyzer of a single library. class LibraryAnalyzer { /// A marker object used to prevent the initialization of /// [_versionConstraintFromPubspec] when the previous initialization attempt @@ -79,11 +77,9 @@ class LibraryAnalyzer { final List _usedImportedElementsList = []; final List _usedLocalElementsList = []; - /** - * Constants in the current library. - * - * TODO(scheglov) Remove after https://github.com/dart-lang/sdk/issues/31925 - */ + /// Constants in the current library. + /// + /// TODO(scheglov) Remove after https://github.com/dart-lang/sdk/issues/31925 final Set _libraryConstants = {}; final Set _constants = {}; @@ -107,9 +103,7 @@ class LibraryAnalyzer { TypeSystemImpl get _typeSystem => _libraryElement.typeSystem; - /** - * Compute analysis results for all units of the library. - */ + /// Compute analysis results for all units of the library. Map analyzeSync({ @required String completionPath, @required int completionOffset, @@ -175,15 +169,13 @@ class LibraryAnalyzer { 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 - */ + /// 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; @@ -201,9 +193,7 @@ class LibraryAnalyzer { unit.accept(constantVerifier); } - /** - * Compute [_constants] in all units. - */ + /// Compute [_constants] in all units. void _computeConstants() { computeConstants(_typeProvider, _typeSystem, _declaredVariables, _constants.toList(), _analysisOptions.experimentStatus); @@ -412,10 +402,8 @@ class LibraryAnalyzer { unit.accept(errorVerifier); } - /** - * Return a subset of the given [errors] that are not marked as ignored in - * the [file]. - */ + /// Return a subset of the given [errors] that are not marked as ignored in + /// the [file]. List _filterIgnoredErrors( FileState file, List errors) { if (errors.isEmpty) { @@ -460,9 +448,7 @@ class LibraryAnalyzer { }); } - /** - * Catch all exceptions from the `getFileContent` function. - */ + /// Catch all exceptions from the `getFileContent` function. String _getFileContent(String path) { try { return getFileContent(path); @@ -488,10 +474,8 @@ class LibraryAnalyzer { return workspace?.findPackageFor(libraryPath); } - /** - * 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. - */ + /// 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 directivesToResolve) { for (Directive directive in partUnit.directives) { @@ -522,16 +506,12 @@ class LibraryAnalyzer { return false; } - /** - * Return `true` if the given [source] is a library. - */ + /// Return `true` if the given [source] is a library. bool _isLibrarySource(Source source) { return _isLibraryUri(source.uri); } - /** - * Return a parsed unresolved [CompilationUnit]. - */ + /// Return a parsed unresolved [CompilationUnit]. CompilationUnit _parse(FileState file) { AnalysisErrorListener errorListener = _getErrorListener(file); String content = _getFileContent(file.path); @@ -728,10 +708,8 @@ class LibraryAnalyzer { } } - /** - * Return the result of resolve the given [uriContent], reporting errors - * against the [uriLiteral]. - */ + /// 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 = @@ -779,10 +757,8 @@ class LibraryAnalyzer { } } - /** - * Check the given [directive] to see if the referenced source exists and - * report an error if it does not. - */ + /// 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; @@ -806,10 +782,8 @@ class LibraryAnalyzer { .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. - */ + /// 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) { @@ -818,10 +792,8 @@ class LibraryAnalyzer { } } - /** - * Return `true` if the given [source] refers to a file that is assumed to be - * generated. - */ + /// 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; @@ -845,9 +817,7 @@ class LibraryAnalyzer { } } -/** - * Analysis result for single file. - */ +/// Analysis result for single file. class UnitAnalysisResult { final FileState file; final CompilationUnit unit; @@ -856,9 +826,7 @@ class UnitAnalysisResult { UnitAnalysisResult(this.file, this.unit, this.errors); } -/** - * Either the name or the source associated with a part-of directive. - */ +/// Either the name or the source associated with a part-of directive. class _NameOrSource { final String name; final Source source; diff --git a/pkg/analyzer/lib/src/dart/micro/library_graph.dart b/pkg/analyzer/lib/src/dart/micro/library_graph.dart index 059515c4aa95..25f0e2c23288 100644 --- a/pkg/analyzer/lib/src/dart/micro/library_graph.dart +++ b/pkg/analyzer/lib/src/dart/micro/library_graph.dart @@ -42,19 +42,13 @@ void computeLibraryCycle(Uint32List linkedSalt, FileState file) { class FileState { final FileSystemState _fsState; - /** - * The path of the file. - */ + /// The path of the file. final String path; - /** - * The URI of the file. - */ + /// The URI of the file. final Uri uri; - /** - * The [Source] of the file with the [uri]. - */ + /// The [Source] of the file with the [uri]. final Source source; /// Files that reference this file. @@ -385,11 +379,9 @@ class FileSystemState { final AnalysisOptions _analysisOptions; final Uint32List _linkedSalt; - /** - * A function that returns the digest for a file as a String. The function - * returns a non null value, returns an empty string if file does - * not exist/has no contents. - */ + /// A function that returns the digest for a file as a String. The function + /// returns a non null value, returns an empty string if file does + /// not exist/has no contents. final String Function(String path) getFileDigest; final Map _pathToFile = {}; @@ -397,10 +389,8 @@ class FileSystemState { final FeatureSetProvider featureSetProvider; - /** - * A function that fetches the given list of files. This function can be used - * to batch file reads in systems where file fetches are expensive. - */ + /// A function that fetches the given list of files. This function can be used + /// to batch file reads in systems where file fetches are expensive. final void Function(List paths) prefetchFiles; final FileSystemStateTimers timers = FileSystemStateTimers(); diff --git a/pkg/analyzer/lib/src/dart/micro/resolve_file.dart b/pkg/analyzer/lib/src/dart/micro/resolve_file.dart index 8e34140b7f08..6dd6b7913097 100644 --- a/pkg/analyzer/lib/src/dart/micro/resolve_file.dart +++ b/pkg/analyzer/lib/src/dart/micro/resolve_file.dart @@ -58,10 +58,8 @@ class FileResolver { */ final String Function(String path) getFileDigest; - /** - * A function that fetches the given list of files. This function can be used - * to batch file reads in systems where file fetches are expensive. - */ + /// A function that fetches the given list of files. This function can be used + /// to batch file reads in systems where file fetches are expensive. final void Function(List paths) prefetchFiles; final Workspace workspace; diff --git a/pkg/analyzer/lib/src/dart/resolver/assignment_expression_resolver.dart b/pkg/analyzer/lib/src/dart/resolver/assignment_expression_resolver.dart index 15f53c7f92df..464c09c846ed 100644 --- a/pkg/analyzer/lib/src/dart/resolver/assignment_expression_resolver.dart +++ b/pkg/analyzer/lib/src/dart/resolver/assignment_expression_resolver.dart @@ -84,12 +84,10 @@ class AssignmentExpressionResolver { : node.staticType); } - /** - * Set the static type of [node] to be the least upper bound of the static - * types of subexpressions [expr1] and [expr2]. - * - * TODO(scheglov) this is duplicate - */ + /// Set the static type of [node] to be the least upper bound of the static + /// types of subexpressions [expr1] and [expr2]. + /// + /// TODO(scheglov) this is duplicate void _analyzeLeastUpperBound( Expression node, Expression expr1, Expression expr2, {bool read = false}) { @@ -99,12 +97,10 @@ class AssignmentExpressionResolver { _analyzeLeastUpperBoundTypes(node, staticType1, staticType2); } - /** - * Set the static type of [node] to be the least upper bound of the static - * types [staticType1] and [staticType2]. - * - * TODO(scheglov) this is duplicate - */ + /// Set the static type of [node] to be the least upper bound of the static + /// types [staticType1] and [staticType2]. + /// + /// TODO(scheglov) this is duplicate void _analyzeLeastUpperBoundTypes( Expression node, DartType staticType1, DartType staticType2) { // TODO(brianwilkerson) Determine whether this can still happen. @@ -122,25 +118,21 @@ class AssignmentExpressionResolver { _inferenceHelper.recordStaticType(node, staticType); } - /** - * Gets the definite type of expression, which can be used in cases where - * the most precise type is desired, for example computing the least upper - * bound. - * - * See [getExpressionType] for more information. Without strong mode, this is - * equivalent to [_getStaticType]. - * - * TODO(scheglov) this is duplicate - */ + /// Gets the definite type of expression, which can be used in cases where + /// the most precise type is desired, for example computing the least upper + /// bound. + /// + /// See [getExpressionType] for more information. Without strong mode, this is + /// equivalent to [_getStaticType]. + /// + /// TODO(scheglov) this is duplicate DartType _getExpressionType(Expression expr, {bool read = false}) => getExpressionType(expr, _typeSystem, _typeProvider, read: read); - /** - * Return the static type of the given [expression] that is to be used for - * type analysis. - * - * TODO(scheglov) this is duplicate - */ + /// Return the static type of the given [expression] that is to be used for + /// type analysis. + /// + /// TODO(scheglov) this is duplicate DartType _getStaticType1(Expression expression, {bool read = false}) { if (expression is NullLiteral) { return _typeProvider.nullType; @@ -149,11 +141,9 @@ class AssignmentExpressionResolver { return _resolveTypeParameter(type); } - /** - * Return the static type of the given [expression]. - * - * TODO(scheglov) this is duplicate - */ + /// Return the static type of the given [expression]. + /// + /// TODO(scheglov) this is duplicate DartType _getStaticType2(Expression expression, {bool read = false}) { DartType type; if (read) { @@ -179,10 +169,10 @@ class AssignmentExpressionResolver { return type; } - /// Return the non-nullable variant of the [type] if NNBD is enabled, otherwise - /// return the type itself. + /// Return the non-nullable variant of the [type] if null safety is enabled, + /// otherwise return the type itself. /// - /// TODO(scheglov) this is duplicate + // TODO(scheglov) this is duplicate DartType _nonNullable(DartType type) { if (_isNonNullableByDefault) { return _typeSystem.promoteToNonNull(type); @@ -300,21 +290,16 @@ class AssignmentExpressionResolver { _resolver.nullShortingTermination(node); } - /** - * If the given [type] is a type parameter, resolve it to the type that should - * be used when looking up members. Otherwise, return the original type. - * - * TODO(scheglov) this is duplicate - */ + /// If the given [type] is a type parameter, resolve it to the type that + /// should be used when looking up members. Otherwise, return the original + /// type. + // TODO(scheglov) this is duplicate DartType _resolveTypeParameter(DartType type) => type?.resolveToBound(_typeProvider.objectType); - /** - * Return `true` if we should report an error for the lookup [result] on - * the [type]. - * - * TODO(scheglov) this is duplicate - */ + /// Return `true` if we should report an error for the lookup [result] on + /// the [type]. + // TODO(scheglov) this is duplicate bool _shouldReportInvalidMember(DartType type, ResolutionResult result) { if (result.isNone && type != null && !type.isDynamic) { if (_typeSystem.isNonNullableByDefault && diff --git a/pkg/analyzer/lib/src/dart/resolver/resolution_visitor.dart b/pkg/analyzer/lib/src/dart/resolver/resolution_visitor.dart index 7448242b9da1..84be638dbc16 100644 --- a/pkg/analyzer/lib/src/dart/resolver/resolution_visitor.dart +++ b/pkg/analyzer/lib/src/dart/resolver/resolution_visitor.dart @@ -1112,10 +1112,8 @@ class ResolutionVisitor extends RecursiveAstVisitor { } } - /** - * For each [Annotation] found in [annotations], create a new - * [ElementAnnotation] object and set the [Annotation] to point to it. - */ + /// For each [Annotation] found in [annotations], create a new + /// [ElementAnnotation] object and set the [Annotation] to point to it. List _createElementAnnotations( List annotations) { if (annotations.isEmpty) { diff --git a/pkg/analyzer/lib/src/dart/resolver/scope.dart b/pkg/analyzer/lib/src/dart/resolver/scope.dart index 720be0578338..34e34b51ec49 100644 --- a/pkg/analyzer/lib/src/dart/resolver/scope.dart +++ b/pkg/analyzer/lib/src/dart/resolver/scope.dart @@ -10,14 +10,10 @@ import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/type.dart'; import 'package:analyzer/src/generated/engine.dart'; -/** - * The scope defined by a block. - */ +/// The scope defined by a block. class BlockScope extends EnclosedScope { - /** - * Initialize a newly created scope, enclosed within the [enclosingScope], - * based on the given [block]. - */ + /// 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 ArgumentError("block cannot be null"); @@ -31,10 +27,8 @@ class BlockScope extends EnclosedScope { } } - /** - * Return the elements that are declared directly in the given [block]. This - * does not include elements declared in nested blocks. - */ + /// Return the elements that are declared directly in the given [block]. This + /// does not include elements declared in nested blocks. static Iterable elementsInBlock(Block block) sync* { NodeList statements = block.statements; int statementCount = statements.length; @@ -53,14 +47,10 @@ class BlockScope extends EnclosedScope { } } -/** - * The scope defined by a class. - */ +/// The scope defined by a class. class ClassScope extends EnclosedScope { - /** - * Initialize a newly created scope, enclosed within the [enclosingScope], - * based on the given [classElement]. - */ + /// Initialize a newly created scope, enclosed within the [enclosingScope], + /// based on the given [classElement]. ClassScope(Scope enclosingScope, ClassElement classElement) : super(enclosingScope) { if (classElement == null) { @@ -69,9 +59,7 @@ class ClassScope extends EnclosedScope { _defineMembers(classElement); } - /** - * Define the instance members defined by the given [classElement]. - */ + /// Define the instance members defined by the given [classElement]. void _defineMembers(ClassElement classElement) { List accessors = classElement.accessors; int accessorLength = accessors.length; @@ -86,21 +74,15 @@ class ClassScope extends EnclosedScope { } } -/** - * The scope defined for the initializers in a constructor. - */ +/// The scope defined for the initializers in a constructor. class ConstructorInitializerScope extends EnclosedScope { - /** - * Initialize a newly created scope, enclosed within the [enclosingScope]. - */ + /// 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. - */ + /// 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) { @@ -110,19 +92,13 @@ class ConstructorInitializerScope extends EnclosedScope { } } -/** - * A scope that is lexically enclosed in another scope. - */ +/// A scope that is lexically enclosed in another scope. class EnclosedScope extends Scope { - /** - * The scope in which this scope is lexically enclosed. - */ + /// The scope in which this scope is lexically enclosed. @override final Scope enclosingScope; - /** - * Initialize a newly created scope, enclosed within the [enclosingScope]. - */ + /// Initialize a newly created scope, enclosed within the [enclosingScope]. EnclosedScope(this.enclosingScope); @override @@ -167,25 +143,17 @@ class ExtensionScope extends EnclosedScope { } } -/** - * The scope defined by a function. - */ +/// The scope defined by a function. class FunctionScope extends EnclosedScope { - /** - * The element representing the function that defines this scope. - */ + /// 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. - */ + /// 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]. - */ + /// Initialize a newly created scope, enclosed within the [enclosingScope], + /// that represents the given [_functionElement]. FunctionScope(Scope enclosingScope, this._functionElement) : super(EnclosedScope(EnclosedScope(enclosingScope))) { if (_functionElement == null) { @@ -194,10 +162,8 @@ class FunctionScope extends EnclosedScope { _defineTypeParameters(); } - /** - * Define the parameters for the given function in the scope that encloses - * this function. - */ + /// Define the parameters for the given function in the scope that encloses + /// this function. void defineParameters() { if (_parametersDefined) { return; @@ -214,9 +180,7 @@ class FunctionScope extends EnclosedScope { } } - /** - * Define the type parameters for the function. - */ + /// Define the type parameters for the function. void _defineTypeParameters() { Scope typeParameterScope = enclosingScope.enclosingScope; List typeParameters = _functionElement.typeParameters; @@ -228,26 +192,20 @@ class FunctionScope extends EnclosedScope { } } -/** - * The scope defined by a function type alias. - */ +/// 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]. - */ + /// Initialize a newly created scope, enclosed within the [enclosingScope], + /// that represents the given [_typeElement]. FunctionTypeScope(Scope enclosingScope, this._typeElement) : super(EnclosedScope(enclosingScope)) { _defineTypeParameters(); } - /** - * Define the parameters for the function type alias. - */ + /// Define the parameters for the function type alias. void defineParameters() { if (_parametersDefined) { return; @@ -258,9 +216,7 @@ class FunctionTypeScope extends EnclosedScope { } } - /** - * Define the type parameters for the function type alias. - */ + /// Define the type parameters for the function type alias. void _defineTypeParameters() { Scope typeParameterScope = enclosingScope; for (TypeParameterElement typeParameter in _typeElement.typeParameters) { @@ -269,37 +225,25 @@ class FunctionTypeScope extends EnclosedScope { } } -/** - * The scope statements that can be the target of unlabeled `break` and - * `continue` statements. - */ +/// 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. - */ + /// The implicit label scope associated with the top level of a function. static const ImplicitLabelScope ROOT = ImplicitLabelScope._(null, null); - /** - * The implicit label scope enclosing this implicit label scope. - */ + /// 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. - */ + /// 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]. - */ + /// 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. - */ + /// 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 @@ -312,50 +256,34 @@ class ImplicitLabelScope { 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. - */ + /// 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) => ImplicitLabelScope._(this, statement); } -/** - * A scope in which a single label is defined. - */ +/// A scope in which a single label is defined. class LabelScope { - /** - * The label scope enclosing this label scope. - */ + /// The label scope enclosing this label scope. final LabelScope _outerScope; - /** - * The label defined in this scope. - */ + /// The label defined in this scope. final String _label; - /** - * The element to which the label resolves. - */ + /// The element to which the label resolves. final LabelElement element; - /** - * The AST node to which the label resolves. - */ + /// 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. - */ + /// 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. - */ + /// 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; @@ -364,36 +292,25 @@ class LabelScope { } } -/** - * The scope containing all of the names available from imported libraries. - */ +/// 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. - */ + /// 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. - */ + /// A list of the namespaces representing the names that are available in this + /// scope from imported libraries. List _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. - */ + /// 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> _definedPrefixedNames; - /** - * Cache of public extensions defined in this library's imported namespaces. - */ + /// Cache of public extensions defined in this library's imported namespaces. List _extensions; - /** - * Initialize a newly created scope representing the names imported into the - * [_definingLibrary]. - */ + /// Initialize a newly created scope representing the names imported into the + /// [_definingLibrary]. LibraryImportScope(this._definingLibrary) { _createImportedNamespaces(); } @@ -492,11 +409,9 @@ class LibraryImportScope extends Scope { 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. - */ + /// 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 imports = _definingLibrary.imports; int count = imports.length; @@ -506,10 +421,8 @@ class LibraryImportScope extends Scope { } } - /** - * Add the given [element] to this scope without checking for duplication or - * hiding. - */ + /// Add the given [element] to this scope without checking for duplication or + /// hiding. void _definePrefixedNameWithoutChecking( String prefix, String name, Element element) { _definedPrefixedNames ??= HashMap>(); @@ -532,10 +445,8 @@ class LibraryImportScope extends Scope { 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. - */ + /// 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 unprefixedNames = _definedPrefixedNames[prefix]; @@ -597,16 +508,12 @@ class LibraryImportScope extends Scope { } } -/** - * A scope containing all of the names defined in a given library. - */ +/// A scope containing all of the names defined in a given library. class LibraryScope extends EnclosedScope { final List _extensions = []; - /** - * Initialize a newly created scope representing the names defined in the - * [definingLibrary]. - */ + /// Initialize a newly created scope representing the names defined in the + /// [definingLibrary]. LibraryScope(LibraryElement definingLibrary) : super(LibraryImportScope(definingLibrary)) { _defineTopLevelNames(definingLibrary); @@ -624,10 +531,8 @@ class LibraryScope extends EnclosedScope { List 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]. - */ + /// 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); @@ -654,10 +559,8 @@ class LibraryScope extends EnclosedScope { } } - /** - * Add to this scope all of the names that are explicitly defined in the - * [definingLibrary]. - */ + /// 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); @@ -669,55 +572,38 @@ class LibraryScope extends EnclosedScope { } } -/** - * A mapping of identifiers to the elements represented by those identifiers. - * Namespaces are the building blocks for scopes. - */ +/// A mapping of identifiers to the elements represented by those identifiers. +/// Namespaces are the building blocks for scopes. class Namespace { - /** - * An empty namespace. - */ + /// An empty namespace. static Namespace EMPTY = Namespace(HashMap()); - /** - * A table mapping names that are defined in this namespace to the element - * representing the thing declared with that name. - */ + /// A table mapping names that are defined in this namespace to the element + /// representing the thing declared with that name. final Map _definedNames; - /** - * Initialize a newly created namespace to have the [_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. - */ + /// Return a table containing the same mappings as those defined by this + /// namespace. Map 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. - */ + /// 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. - */ + /// 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. - */ +/// 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]. - */ + /// Create a namespace representing the export namespace of the given + /// [element]. Namespace createExportNamespaceForDirective(ExportElement element) { LibraryElement exportedLibrary = element.exportedLibrary; if (exportedLibrary == null) { @@ -732,17 +618,15 @@ class NamespaceBuilder { return Namespace(exportedNames); } - /** - * Create a namespace representing the export namespace of the given [library]. - */ + /// Create a namespace representing the export namespace of the given + /// [library]. Namespace createExportNamespaceForLibrary(LibraryElement library) { Map exportedNames = _getExportMapping(library); return Namespace(exportedNames); } - /** - * Create a namespace representing the import namespace of the given [element]. - */ + /// Create a namespace representing the import namespace of the given + /// [element]. Namespace createImportNamespaceForDirective(ImportElement element) { LibraryElement importedLibrary = element.importedLibrary; if (importedLibrary == null) { @@ -761,10 +645,8 @@ class NamespaceBuilder { return Namespace(exportedNames); } - /** - * Create a namespace representing the public namespace of the given - * [library]. - */ + /// Create a namespace representing the public namespace of the given + /// [library]. Namespace createPublicNamespaceForLibrary(LibraryElement library) { Map definedNames = HashMap(); _addPublicNames(definedNames, library.definingCompilationUnit); @@ -784,10 +666,8 @@ class NamespaceBuilder { return Namespace(definedNames); } - /** - * Add all of the names in the given [namespace] to the table of - * [definedNames]. - */ + /// Add all of the names in the given [namespace] to the table of + /// [definedNames]. void _addAllFromNamespace( Map definedNames, Namespace namespace) { if (namespace != null) { @@ -795,10 +675,8 @@ class NamespaceBuilder { } } - /** - * Add the given [element] to the table of [definedNames] if it has a - * publicly visible name. - */ + /// Add the given [element] to the table of [definedNames] if it has a + /// publicly visible name. void _addIfPublic(Map definedNames, Element element) { String name = element.name; if (name != null && name.isNotEmpty && !Scope.isPrivateName(name)) { @@ -806,11 +684,9 @@ class NamespaceBuilder { } } - /** - * Add to the table of [definedNames] all of the public top-level names that - * are defined in the given [compilationUnit]. - * namespace - */ + /// Add to the table of [definedNames] all of the public top-level names that + /// are defined in the given [compilationUnit]. + /// namespace void _addPublicNames(Map definedNames, CompilationUnitElement compilationUnit) { for (PropertyAccessorElement element in compilationUnit.accessors) { @@ -837,10 +713,8 @@ class NamespaceBuilder { } } - /** - * Apply the given [combinators] to all of the names in the given table of - * [definedNames]. - */ + /// Apply the given [combinators] to all of the names in the given table of + /// [definedNames]. Map _applyCombinators(Map definedNames, List combinators) { for (NamespaceCombinator combinator in combinators) { @@ -857,13 +731,11 @@ class NamespaceBuilder { 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. - */ + /// 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 _computeExportMapping( LibraryElement library, HashSet visitedElements) { visitedElements.add(library); @@ -906,10 +778,8 @@ class NamespaceBuilder { return _computeExportMapping(library, HashSet()); } - /** - * Return a new map of names which has all the names from [definedNames] - * with exception of [hiddenNames]. - */ + /// Return a new map of names which has all the names from [definedNames] + /// with exception of [hiddenNames]. Map _hide( Map definedNames, List hiddenNames) { Map newNames = HashMap.from(definedNames); @@ -920,9 +790,7 @@ class NamespaceBuilder { return newNames; } - /** - * Return a new map of names which has only [shownNames] from [definedNames]. - */ + /// Return a new map of names which has only [shownNames] from [definedNames]. Map _show( Map definedNames, List shownNames) { Map newNames = HashMap(); @@ -941,33 +809,23 @@ class NamespaceBuilder { } } -/** - * A mapping of identifiers to the elements represented by those identifiers. - * Namespaces are the building blocks for scopes. - */ +/// 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. - */ + /// The prefix that is prepended to each of the defined names. final String _prefix; - /** - * The length of the 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. - */ + /// A table mapping names that are defined in this namespace to the element + /// representing the thing declared with that name. @override final Map _definedNames; - /** - * Initialize a newly created namespace to have the names resulting from - * prefixing each of the [_definedNames] with the given [_prefix] (and a - * period). - */ + /// 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; @@ -1000,51 +858,35 @@ class PrefixedNamespace implements Namespace { } } -/** - * A name scope used by the resolver to determine which names are visible at any - * given point in the code. - */ +/// 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. - */ + /// 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. - */ + /// 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. - */ + /// 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. - */ + /// A table mapping names that are defined in this scope to the element + /// representing the thing declared with that name. Map _definedNames; - /** - * Return the scope in which this scope is lexically enclosed. - */ + /// Return the scope in which this scope is lexically enclosed. Scope get enclosingScope => null; - /** - * The list of extensions defined in this scope. - */ + /// The list of extensions defined in this scope. List get extensions => enclosingScope == null ? [] : 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. - */ + /// 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) { @@ -1053,36 +895,28 @@ abstract class Scope { } } - /** - * Add the given [element] to this scope without checking for duplication or - * hiding. - */ + /// Add the given [element] to this scope without checking for duplication or + /// hiding. void defineNameWithoutChecking(String name, Element element) { _definedNames ??= HashMap(); _definedNames[name] = element; } - /** - * Add the given [element] to this scope without checking for duplication or - * hiding. - */ + /// Add the given [element] to this scope without checking for duplication or + /// hiding. void defineWithoutChecking(Element element) { _definedNames ??= HashMap(); _definedNames[_getName(element)] = element; } - /** - * Return the element with which the given [name] is associated, or `null` if - * the name is not defined within this scope. - */ + /// Return the element with which the given [name] is associated, or `null` if + /// the name is not defined within this scope. Element internalLookup(String name); - /** - * 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. - */ + /// 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. Element localLookup(String name) { if (_definedNames != null) { return _definedNames[name]; @@ -1090,12 +924,10 @@ abstract class Scope { 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. - */ + /// 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( @@ -1104,13 +936,11 @@ abstract class Scope { return internalLookup(identifier.name); } - /** - * 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. - */ + /// 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); @@ -1118,9 +948,7 @@ abstract class Scope { return false; } - /** - * Return the name that will be used to look up the given [element]. - */ + /// Return the name that will be used to look up the given [element]. String _getName(Element element) { if (element is MethodElement) { MethodElement method = element; @@ -1131,28 +959,20 @@ abstract class Scope { 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. - */ + /// Return the element with which the given [prefix] and [name] are + /// associated, or `null` if the name is not defined within this scope. Element _internalLookupPrefixed(String prefix, String name); - /** - * Return `true` if the given [name] is a library-private name. - */ + /// Return `true` if the given [name] is a library-private name. static bool isPrivateName(String name) => name != null && name.startsWith('_'); } -/** - * The scope defined by the type parameters in an element that defines type - * parameters. - */ +/// 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]. - */ + /// 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) { @@ -1161,9 +981,7 @@ class TypeParameterScope extends EnclosedScope { _defineTypeParameters(element); } - /** - * Define the type parameters declared by the [element]. - */ + /// Define the type parameters declared by the [element]. void _defineTypeParameters(TypeParameterizedElement element) { for (TypeParameterElement typeParameter in element.typeParameters) { define(typeParameter); diff --git a/pkg/analyzer/lib/src/dart/resolver/typed_literal_resolver.dart b/pkg/analyzer/lib/src/dart/resolver/typed_literal_resolver.dart index 21f74eaf538f..57d6981f087e 100644 --- a/pkg/analyzer/lib/src/dart/resolver/typed_literal_resolver.dart +++ b/pkg/analyzer/lib/src/dart/resolver/typed_literal_resolver.dart @@ -574,14 +574,12 @@ class TypedLiteralResolver { } } - /** - * Record that the static type of the given node is the given type. - * - * @param expression the node whose type is to be recorded - * @param type the static type of the node - * - * TODO(scheglov) Inline this. - */ + /// Record that the static type of the given node is the given type. + /// + /// @param expression the node whose type is to be recorded + /// @param type the static type of the node + /// + /// TODO(scheglov) Inline this. void _recordStaticType(Expression expression, DartType type) { expression.staticType = type; // if (type == null) { diff --git a/pkg/analyzer/lib/src/dart/scanner/reader.dart b/pkg/analyzer/lib/src/dart/scanner/reader.dart index 1f1d266d48cd..931d43825c7a 100644 --- a/pkg/analyzer/lib/src/dart/scanner/reader.dart +++ b/pkg/analyzer/lib/src/dart/scanner/reader.dart @@ -7,30 +7,20 @@ import 'package:_fe_analyzer_shared/src/scanner/reader.dart'; export 'package:_fe_analyzer_shared/src/scanner/reader.dart' show CharacterReader, CharSequenceReader, SubSequenceReader; -/** - * A [CharacterReader] that reads a range of characters from another character - * reader. - */ +/// A [CharacterReader] that reads a range of characters from another character +/// reader. class CharacterRangeReader extends CharacterReader { - /** - * The reader from which the characters are actually being read. - */ + /// The reader from which the characters are actually being read. final CharacterReader baseReader; - /** - * The first character to be read. - */ + /// The first character to be read. final int startIndex; - /** - * The last character to be read. - */ + /// The last character to be read. final int endIndex; - /** - * Initialize a newly created reader to read the characters from the given - * [baseReader] between the [startIndex] inclusive to [endIndex] exclusive. - */ + /// Initialize a newly created reader to read the characters from the given + /// [baseReader] between the [startIndex] inclusive to [endIndex] exclusive. CharacterRangeReader(this.baseReader, this.startIndex, this.endIndex) { baseReader.offset = startIndex - 1; } diff --git a/pkg/analyzer/lib/src/dart/scanner/scanner.dart b/pkg/analyzer/lib/src/dart/scanner/scanner.dart index 5003402e9f50..c2ce2e87721d 100644 --- a/pkg/analyzer/lib/src/dart/scanner/scanner.dart +++ b/pkg/analyzer/lib/src/dart/scanner/scanner.dart @@ -18,77 +18,59 @@ import 'package:pub_semver/pub_semver.dart'; export 'package:analyzer/src/dart/error/syntactic_errors.dart'; -/** - * The class `Scanner` implements a scanner for Dart code. - * - * The lexical structure of Dart is ambiguous without knowledge of the context - * in which a token is being scanned. For example, without context we cannot - * determine whether source of the form "<<" should be scanned as a single - * left-shift operator or as two left angle brackets. This scanner does not have - * any context, so it always resolves such conflicts by scanning the longest - * possible token. - */ +/// The class `Scanner` implements a scanner for Dart code. +/// +/// The lexical structure of Dart is ambiguous without knowledge of the context +/// in which a token is being scanned. For example, without context we cannot +/// determine whether source of the form "<<" should be scanned as a single +/// left-shift operator or as two left angle brackets. This scanner does not +/// have any context, so it always resolves such conflicts by scanning the +/// longest possible token. class Scanner { final Source source; - /** - * The text to be scanned. - */ + /// The text to be scanned. final String _contents; - /** - * The offset of the first character from the reader. - */ + /// The offset of the first character from the reader. final int _readerOffset; - /** - * The error listener that will be informed of any errors that are found - * during the scan. - */ + /// The error listener that will be informed of any errors that are found + /// during the scan. final AnalysisErrorListener _errorListener; - /** - * If the file has [fasta.LanguageVersionToken], it is allowed to use the - * language version greater than the one specified in the package config. - * So, we need to know the full feature set for the context. - */ + /// If the file has [fasta.LanguageVersionToken], it is allowed to use the + /// language version greater than the one specified in the package config. + /// So, we need to know the full feature set for the context. FeatureSet _featureSetForOverriding; - /** - * The flag specifying whether documentation comments should be parsed. - */ + /// The flag specifying whether documentation comments should be parsed. bool _preserveComments = true; final List lineStarts = []; Token firstToken; - /** - * A flag indicating whether the scanner should recognize the `>>>` operator - * and the `>>>=` operator. - * - * Use [configureFeatures] rather than this field. - */ + /// A flag indicating whether the scanner should recognize the `>>>` operator + /// and the `>>>=` operator. + /// + /// Use [configureFeatures] rather than this field. bool enableGtGtGt = false; - /** - * A flag indicating whether the scanner should recognize the `late` and - * `required` keywords. - * - * Use [configureFeatures] rather than this field. - */ + /// A flag indicating whether the scanner should recognize the `late` and + /// `required` keywords. + /// + /// Use [configureFeatures] rather than this field. bool enableNonNullable = false; fasta.LanguageVersionToken _languageVersion; FeatureSet _featureSet; - /** - * Initialize a newly created scanner to scan characters from the given - * [source]. The given character [reader] will be used to read the characters - * in the source. The given [_errorListener] will be informed of any errors - * that are found. - */ + /// Initialize a newly created scanner to scan characters from the given + /// [source]. The given character [reader] will be used to read the characters + /// in the source. The given [_errorListener] will be informed of any errors + /// that are found. factory Scanner(Source source, CharacterReader reader, AnalysisErrorListener errorListener) => Scanner.fasta(source, errorListener, @@ -105,22 +87,18 @@ class Scanner { lineStarts.add(0); } - /** - * The features associated with this scanner. - * - * If a language version comment (e.g. '// @dart = 2.3') is detected - * when calling [tokenize] and this field is non-null, then this field - * will be updated to contain a downgraded feature set based upon the - * language version specified. - * - * Use [configureFeatures] to set the features. - */ + /// The features associated with this scanner. + /// + /// If a language version comment (e.g. '// @dart = 2.3') is detected + /// when calling [tokenize] and this field is non-null, then this field + /// will be updated to contain a downgraded feature set based upon the + /// language version specified. + /// + /// Use [configureFeatures] to set the features. FeatureSet get featureSet => _featureSet; - /** - * The language version override specified for this compilation unit using a - * token like '// @dart = 2.7', or `null` if no override is specified. - */ + /// The language version override specified for this compilation unit using a + /// token like '// @dart = 2.7', or `null` if no override is specified. fasta.LanguageVersionToken get languageVersion => _languageVersion; set preserveComments(bool preserveComments) { diff --git a/pkg/analyzer/lib/src/dart/sdk/sdk.dart b/pkg/analyzer/lib/src/dart/sdk/sdk.dart index 2826ac3016eb..ab9d317afe07 100644 --- a/pkg/analyzer/lib/src/dart/sdk/sdk.dart +++ b/pkg/analyzer/lib/src/dart/sdk/sdk.dart @@ -18,52 +18,34 @@ import 'package:analyzer/src/generated/source_io.dart'; 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. - */ +/// 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. - */ + /// 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. - */ + /// A mapping from Dart library URI's to the library represented by that URI. LibraryMap libraryMap = LibraryMap(); - /** - * The [AnalysisOptions] to use to create the [context]. - */ + /// 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. - */ + /// 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. - */ + /// The [AnalysisContext] which is used for all of the sources in this SDK. SdkAnalysisContext _analysisContext; - /** - * The mapping from Dart URI's to the corresponding sources. - */ + /// The mapping from Dart URI's to the corresponding sources. final Map _uriToSourceMap = HashMap(); - /** - * Return the analysis options for this SDK analysis context. - */ + /// 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. - */ + /// Set the [options] for this SDK analysis context. Throw [StateError] if + /// the context has been already created. set analysisOptions(AnalysisOptions options) { if (_analysisContext != null) { throw StateError( @@ -84,22 +66,16 @@ abstract class AbstractDartSdk implements DartSdk { @override List get sdkLibraries => libraryMap.sdkLibraries; - /** - * Return the path separator used by the resource provider. - */ + /// Return the path separator used by the resource provider. String get separator => resourceProvider.pathContext.separator; @override List get uris => libraryMap.uris; - /** - * Return `true` if the SDK summary will be used when available. - */ + /// Return `true` if the SDK summary will be used when available. bool get useSummary => _useSummary; - /** - * Specify whether SDK summary should be used. - */ + /// Specify whether SDK summary should be used. set useSummary(bool use) { if (_analysisContext != null) { throw StateError( @@ -108,11 +84,9 @@ abstract class AbstractDartSdk implements DartSdk { _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. - */ + /// 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 extensions) { extensions.forEach((String uri, String path) { SdkLibraryImpl library = SdkLibraryImpl(uri); @@ -121,9 +95,7 @@ abstract class AbstractDartSdk implements DartSdk { }); } - /** - * Return info for debugging https://github.com/dart-lang/sdk/issues/35226. - */ + /// Return info for debugging https://github.com/dart-lang/sdk/issues/35226. Map debugInfo() { return { 'runtimeType': '$runtimeType', @@ -238,9 +210,7 @@ abstract class AbstractDartSdk implements DartSdk { } } -/** - * An SDK backed by URI mappings derived from an `_embedder.yaml` file. - */ +/// An SDK backed by URI mappings derived from an `_embedder.yaml` file. class EmbedderSdk extends AbstractDartSdk { static const String _DART_COLON_PREFIX = 'dart:'; @@ -273,9 +243,7 @@ class EmbedderSdk extends AbstractDartSdk { // TODO(danrubel) Determine SDK version String get sdkVersion => '0'; - /** - * The url mappings for this SDK. - */ + /// The url mappings for this SDK. Map get urlMappings => _urlMappings; @override @@ -321,9 +289,7 @@ class EmbedderSdk extends AbstractDartSdk { } } - /** - * Install the mapping from [name] to [libDir]/[file]. - */ + /// 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:'. @@ -336,18 +302,16 @@ class EmbedderSdk extends AbstractDartSdk { 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. - */ + /// 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) { @@ -356,22 +320,20 @@ class EmbedderSdk extends AbstractDartSdk { } } -/** - * 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 - */ +/// 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. @@ -416,21 +378,15 @@ class FolderBasedDartSdk extends AbstractDartSdk { /// 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. - */ + /// The revision number of this SDK, or `"0"` if the revision number cannot be + /// discovered. String _sdkVersion; - /** - * The file containing the pub executable. - */ + /// The file containing the pub executable. File _pubExecutable; - /** - * Initialize a newly created SDK to represent the Dart SDK installed in the - * [sdkDirectory]. - */ + /// Initialize a newly created SDK to represent the Dart SDK installed in the + /// [sdkDirectory]. FolderBasedDartSdk(ResourceProvider resourceProvider, Folder sdkDirectory) : _sdkDirectory = sdkDirectory { this.resourceProvider = resourceProvider; @@ -450,28 +406,21 @@ class FolderBasedDartSdk extends AbstractDartSdk { } } - /** - * Return the directory containing the SDK. - */ + /// Return the directory containing the SDK. Folder get directory => _sdkDirectory; - /** - * Return the directory containing documentation for the SDK. - */ + /// 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. - */ + /// Return the directory within the SDK directory that contains the libraries. Folder get libraryDirectory { return _libraryDirectory ??= _sdkDirectory.getChildAssumingFolder(_LIB_DIRECTORY_NAME); } - /** - * Return the file containing the Pub executable, or `null` if it does not exist. - */ + /// Return the file containing the Pub executable, or `null` if it does not + /// exist. File get pubExecutable { return _pubExecutable ??= _sdkDirectory .getChildAssumingFolder(_BIN_DIRECTORY_NAME) @@ -480,10 +429,8 @@ class FolderBasedDartSdk extends AbstractDartSdk { : _PUB_EXECUTABLE_NAME); } - /** - * Return the revision number of this SDK, or `"0"` if the revision number - * cannot be discovered. - */ + /// Return the revision number of this SDK, or `"0"` if the revision number + /// cannot be discovered. @override String get sdkVersion { if (_sdkVersion == null) { @@ -502,9 +449,7 @@ class FolderBasedDartSdk extends AbstractDartSdk { return _sdkVersion; } - /** - * Determine the search order for trying to locate the [_LIBRARIES_FILE]. - */ + /// Determine the search order for trying to locate the [_LIBRARIES_FILE]. Iterable get _libraryMapLocations sync* { yield libraryDirectory .getChildAssumingFolder(_INTERNAL_DIR) @@ -516,9 +461,7 @@ class FolderBasedDartSdk extends AbstractDartSdk { .getChildAssumingFile(_LIBRARIES_FILE); } - /** - * Return info for debugging https://github.com/dart-lang/sdk/issues/35226. - */ + /// Return info for debugging https://github.com/dart-lang/sdk/issues/35226. @override Map debugInfo() { var result = super.debugInfo(); @@ -536,10 +479,8 @@ class FolderBasedDartSdk extends AbstractDartSdk { return filePath.substring(libPath.length + 1); } - /** - * Read all of the configuration files to initialize the library maps. - * Return the initialized library map. - */ + /// Read all of the configuration files to initialize the library maps. + /// Return the initialized library map. LibraryMap initialLibraryMap() { List searchedPaths = []; StackTrace lastStackTrace; @@ -598,11 +539,9 @@ class FolderBasedDartSdk extends AbstractDartSdk { } } - /** - * 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`. - */ + /// 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 @@ -653,41 +592,35 @@ class FolderBasedDartSdk extends AbstractDartSdk { } } -/** - * 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 LIBRARIES = const { - * // 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), - * }; - */ +/// 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 LIBRARIES = const { +/// // 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 { - /** - * Return the library map read from the given [file], given that the content - * of the file is already known to be [libraryFileContents]. - */ + /// 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]. - */ + /// 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) { // TODO(paulberry): initialize the feature set appropriately based on the // version of the SDK we are reading, and enable flags.