From a6ffd670acf4000e5c8d8d6a56b2fc5ff536cbdd Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Tue, 12 Oct 2021 15:52:17 -0700 Subject: [PATCH 01/21] squash --- lib/dartdoc.dart | 506 +----------------------------- lib/src/dartdoc.dart | 515 +++++++++++++++++++++++++++++++ lib/src/model/package_graph.dart | 3 +- lib/src/model_utils.dart | 49 +-- lib/src/special_elements.dart | 10 +- 5 files changed, 548 insertions(+), 535 deletions(-) create mode 100644 lib/src/dartdoc.dart diff --git a/lib/dartdoc.dart b/lib/dartdoc.dart index ebd0c991f2..453897966f 100644 --- a/lib/dartdoc.dart +++ b/lib/dartdoc.dart @@ -3,522 +3,18 @@ // BSD-style license that can be found in the LICENSE file. // @dart=2.9 - /// A documentation generator for Dart. /// /// Library interface is still experimental. @experimental library dartdoc; -import 'dart:async'; -import 'dart:convert'; -import 'dart:io' show Platform, exitCode, stderr; - -import 'package:analyzer/file_system/file_system.dart'; -import 'package:dartdoc/options.dart'; -import 'package:dartdoc/src/dartdoc_options.dart'; -import 'package:dartdoc/src/failure.dart'; -import 'package:dartdoc/src/generator/empty_generator.dart'; -import 'package:dartdoc/src/generator/generator.dart'; -import 'package:dartdoc/src/generator/html_generator.dart'; -import 'package:dartdoc/src/generator/markdown_generator.dart'; -import 'package:dartdoc/src/logging.dart'; -import 'package:dartdoc/src/matching_link_result.dart'; -import 'package:dartdoc/src/model/model.dart'; -import 'package:dartdoc/src/package_meta.dart'; -import 'package:dartdoc/src/tuple.dart'; -import 'package:dartdoc/src/utils.dart'; -import 'package:dartdoc/src/version.dart'; -import 'package:dartdoc/src/warnings.dart'; -import 'package:html/parser.dart' show parse; import 'package:meta/meta.dart'; -import 'package:path/path.dart' as path; +export 'package:dartdoc/src/dartdoc.dart'; export 'package:dartdoc/src/dartdoc_options.dart'; export 'package:dartdoc/src/element_type.dart'; export 'package:dartdoc/src/generator/generator.dart'; export 'package:dartdoc/src/model/model.dart'; export 'package:dartdoc/src/package_config_provider.dart'; export 'package:dartdoc/src/package_meta.dart'; - -const String programName = 'dartdoc'; -// Update when pubspec version changes by running `pub run build_runner build` -const String dartdocVersion = packageVersion; - -class DartdocFileWriter implements FileWriter { - final String _outputDir; - @override - final ResourceProvider resourceProvider; - final Map _fileElementMap = {}; - @override - final Set writtenFiles = {}; - - DartdocFileWriter(this._outputDir, this.resourceProvider); - - @override - void writeBytes( - String filePath, - List content, { - bool allowOverwrite = false, - }) { - // Replace '/' separators with proper separators for the platform. - var outFile = path.joinAll(filePath.split('/')); - - if (!allowOverwrite) { - _warnAboutOverwrite(outFile, null); - } - _fileElementMap[outFile] = null; - - var file = _getFile(outFile); - file.writeAsBytesSync(content); - writtenFiles.add(outFile); - logProgress(outFile); - } - - @override - void write(String filePath, String content, {Warnable element}) { - // Replace '/' separators with proper separators for the platform. - var outFile = path.joinAll(filePath.split('/')); - - _warnAboutOverwrite(outFile, element); - _fileElementMap[outFile] = element; - - var file = _getFile(outFile); - file.writeAsStringSync(content); - writtenFiles.add(outFile); - logProgress(outFile); - } - - void _warnAboutOverwrite(String outFile, Warnable element) { - if (_fileElementMap.containsKey(outFile)) { - assert(element != null, - 'Attempted overwrite of $outFile without corresponding element'); - var originalElement = _fileElementMap[outFile]; - var referredFrom = originalElement != null ? [originalElement] : null; - element?.warn(PackageWarning.duplicateFile, - message: outFile, referredFrom: referredFrom); - } - } - - /// Returns the file at [outFile] relative to [_outputDir], creating the - /// parent directory if necessary. - File _getFile(String outFile) { - var file = resourceProvider - .getFile(resourceProvider.pathContext.join(_outputDir, outFile)); - var parent = file.parent2; - if (!parent.exists) { - parent.create(); - } - return file; - } -} - -/// Generates Dart documentation for all public Dart libraries in the given -/// directory. -class Dartdoc { - Generator _generator; - final PackageBuilder packageBuilder; - final DartdocOptionContext config; - final Set _writtenFiles = {}; - Folder _outputDir; - - // Fires when the self checks make progress. - final StreamController _onCheckProgress = - StreamController(sync: true); - - Dartdoc._(this.config, this._generator, this.packageBuilder) { - _outputDir = config.resourceProvider - .getFolder(config.resourceProvider.pathContext.absolute(config.output)) - ..create(); - } - - // TODO(srawlins): Remove when https://github.com/dart-lang/linter/issues/2706 - // is fixed. - // ignore: unnecessary_getters_setters - Generator get generator => _generator; - - @visibleForTesting - // TODO(srawlins): Remove when https://github.com/dart-lang/linter/issues/2706 - // is fixed. - // ignore: unnecessary_getters_setters - set generator(Generator newGenerator) => _generator = newGenerator; - - /// Asynchronous factory method that builds Dartdoc with an empty generator. - static Future withEmptyGenerator( - DartdocOptionContext config, - PackageBuilder packageBuilder, - ) async { - return Dartdoc._( - config, - await initEmptyGenerator(config), - packageBuilder, - ); - } - - /// Asynchronous factory method that builds Dartdoc with a generator - /// determined by the given context. - static Future fromContext( - DartdocGeneratorOptionContext context, - PackageBuilder packageBuilder, - ) async { - Generator generator; - switch (context.format) { - case 'html': - generator = await initHtmlGenerator(context); - break; - case 'md': - generator = await initMarkdownGenerator(context); - break; - default: - throw DartdocFailure('Unsupported output format: ${context.format}'); - } - return Dartdoc._( - context, - generator, - packageBuilder, - ); - } - - Stream get onCheckProgress => _onCheckProgress.stream; - - @visibleForTesting - Future generateDocsBase() async { - var stopwatch = Stopwatch()..start(); - var packageGraph = await packageBuilder.buildPackageGraph(); - var seconds = stopwatch.elapsedMilliseconds / 1000.0; - var libs = packageGraph.libraries.length; - logInfo("Initialized dartdoc with $libs librar${libs == 1 ? 'y' : 'ies'} " - 'in ${seconds.toStringAsFixed(1)} seconds'); - stopwatch.reset(); - - // Create the out directory. - if (!_outputDir.exists) _outputDir.create(); - - var writer = DartdocFileWriter(_outputDir.path, config.resourceProvider); - await generator.generate(packageGraph, writer); - - _writtenFiles.addAll(writer.writtenFiles); - if (config.validateLinks && _writtenFiles.isNotEmpty) { - _validateLinks(packageGraph, _outputDir.path); - } - - var warnings = packageGraph.packageWarningCounter.warningCount; - var errors = packageGraph.packageWarningCounter.errorCount; - if (warnings == 0 && errors == 0) { - logInfo('no issues found'); - } else { - logWarning("Found $warnings ${pluralize('warning', warnings)} " - "and $errors ${pluralize('error', errors)}."); - } - - seconds = stopwatch.elapsedMilliseconds / 1000.0; - libs = packageGraph.localPublicLibraries.length; - logInfo("Documented $libs public librar${libs == 1 ? 'y' : 'ies'} " - 'in ${seconds.toStringAsFixed(1)} seconds'); - - if (config.showStats) { - logInfo(markdownStats.buildReport()); - } - return DartdocResults(config.topLevelPackageMeta, packageGraph, _outputDir); - } - - /// Generate Dartdoc documentation. - /// - /// [DartdocResults] is returned if dartdoc succeeds. [DartdocFailure] is - /// thrown if dartdoc fails in an expected way, for example if there is an - /// analysis error in the code. - Future generateDocs() async { - DartdocResults dartdocResults; - try { - logInfo('Documenting ${config.topLevelPackageMeta}...'); - - dartdocResults = await generateDocsBase(); - if (dartdocResults.packageGraph.localPublicLibraries.isEmpty) { - logWarning('dartdoc could not find any libraries to document'); - } - - final errorCount = - dartdocResults.packageGraph.packageWarningCounter.errorCount; - if (errorCount > 0) { - throw DartdocFailure('encountered $errorCount errors'); - } - var outDirPath = config.resourceProvider.pathContext - .absolute(dartdocResults.outDir.path); - logInfo('Success! Docs generated into $outDirPath'); - return dartdocResults; - } finally { - dartdocResults?.packageGraph?.dispose(); - } - } - - /// Warn on file paths. - void _warn(PackageGraph packageGraph, PackageWarning kind, String warnOn, - String origin, - {String referredFrom}) { - // Ordinarily this would go in [Package.warn], but we don't actually know what - // ModelElement to warn on yet. - Warnable warnOnElement; - var referredFromElements = {}; - Set warnOnElements; - - // Make all paths relative to origin. - if (path.isWithin(origin, warnOn)) { - warnOn = path.relative(warnOn, from: origin); - } - if (referredFrom != null) { - if (path.isWithin(origin, referredFrom)) { - referredFrom = path.relative(referredFrom, from: origin); - } - // Source paths are always relative. - if (_hrefs[referredFrom] != null) { - referredFromElements.addAll(_hrefs[referredFrom]); - } - } - warnOnElements = _hrefs[warnOn]; - - if (referredFromElements.any((e) => e.isCanonical)) { - referredFromElements.removeWhere((e) => !e.isCanonical); - } - if (warnOnElements != null) { - warnOnElement = warnOnElements.firstWhere((e) => e.isCanonical, - orElse: () => warnOnElements.isEmpty ? null : warnOnElements.first); - } - - if (referredFromElements.isEmpty && referredFrom == 'index.html') { - referredFromElements.add(packageGraph.defaultPackage); - } - var message = warnOn; - if (referredFrom == 'index.json') message = '$warnOn (from index.json)'; - packageGraph.warnOnElement(warnOnElement, kind, - message: message, referredFrom: referredFromElements); - } - - void _doOrphanCheck( - PackageGraph packageGraph, String origin, Set visited) { - var normalOrigin = path.normalize(origin); - var staticAssets = path.joinAll([normalOrigin, 'static-assets', '']); - var indexJson = path.joinAll([normalOrigin, 'index.json']); - var foundIndexJson = false; - - void checkDirectory(Folder dir) { - for (var f in dir.getChildren()) { - if (f is Folder) { - checkDirectory(f); - continue; - } - var fullPath = path.normalize(f.path); - if (fullPath.startsWith(staticAssets)) { - continue; - } - if (path.equals(fullPath, indexJson)) { - foundIndexJson = true; - _onCheckProgress.add(fullPath); - continue; - } - if (visited.contains(fullPath)) continue; - var relativeFullPath = path.relative(fullPath, from: normalOrigin); - if (!_writtenFiles.contains(relativeFullPath)) { - // This isn't a file we wrote (this time); don't claim we did. - _warn( - packageGraph, PackageWarning.unknownFile, fullPath, normalOrigin); - } else { - // Error messages are orphaned by design and do not appear in the search - // index. - if (const {'__404error.html', 'categories.json'}.contains(fullPath)) { - _warn(packageGraph, PackageWarning.orphanedFile, fullPath, - normalOrigin); - } - } - _onCheckProgress.add(fullPath); - } - } - - checkDirectory(config.resourceProvider.getFolder(normalOrigin)); - - if (!foundIndexJson) { - _warn(packageGraph, PackageWarning.brokenLink, indexJson, normalOrigin); - _onCheckProgress.add(indexJson); - } - } - - // This is extracted to save memory during the check; be careful not to hang - // on to anything referencing the full file and doc tree. - Tuple2, String> _getStringLinksAndHref(String fullPath) { - var file = config.resourceProvider.getFile(fullPath); - if (!file.exists) { - return null; - } - // TODO(srawlins): It is possible that instantiating an HtmlParser using - // `lowercaseElementName: false` and `lowercaseAttrName: false` may save - // time or memory. - var doc = parse(file.readAsBytesSync()); - var base = doc.querySelector('base'); - String baseHref; - if (base != null) { - baseHref = base.attributes['href']; - } - var links = doc.querySelectorAll('a'); - var stringLinks = links - .map((link) => link.attributes['href']) - .where((href) => href != null && href != '') - .toList(); - - return Tuple2(stringLinks, baseHref); - } - - void _doSearchIndexCheck( - PackageGraph packageGraph, String origin, Set visited) { - var fullPath = path.joinAll([origin, 'index.json']); - var indexPath = path.joinAll([origin, 'index.html']); - var file = config.resourceProvider.getFile(fullPath); - if (!file.exists) { - return; - } - var decoder = JsonDecoder(); - List jsonData = decoder.convert(file.readAsStringSync()); - - var found = {}; - found.add(fullPath); - // The package index isn't supposed to be in the search, so suppress the - // warning. - found.add(indexPath); - for (Map entry in jsonData) { - if (entry.containsKey('href')) { - var entryPath = - path.joinAll([origin, ...path.posix.split(entry['href'])]); - if (!visited.contains(entryPath)) { - _warn(packageGraph, PackageWarning.brokenLink, entryPath, - path.normalize(origin), - referredFrom: fullPath); - } - found.add(entryPath); - } - } - // Missing from search index - var missingFromSearch = visited.difference(found); - for (var s in missingFromSearch) { - _warn(packageGraph, PackageWarning.missingFromSearchIndex, s, - path.normalize(origin), - referredFrom: fullPath); - } - } - - void _doCheck(PackageGraph packageGraph, String origin, Set visited, - String pathToCheck, - [String source, String fullPath]) { - fullPath ??= path.normalize(path.joinAll([origin, pathToCheck])); - - var stringLinksAndHref = _getStringLinksAndHref(fullPath); - if (stringLinksAndHref == null) { - _warn(packageGraph, PackageWarning.brokenLink, pathToCheck, - path.normalize(origin), - referredFrom: source); - _onCheckProgress.add(pathToCheck); - // Remove so that we properly count that the file doesn't exist for - // the orphan check. - visited.remove(fullPath); - return; - } - visited.add(fullPath); - var stringLinks = stringLinksAndHref.item1; - var baseHref = stringLinksAndHref.item2; - - // Prevent extremely large stacks by storing the paths we are using - // here instead -- occasionally, very large jobs have overflowed - // the stack without this. - // (newPathToCheck, newFullPath) - var toVisit = >{}; - - final ignoreHyperlinks = RegExp(r'^(https:|http:|mailto:|ftp:)'); - for (final href in stringLinks) { - if (!href.startsWith(ignoreHyperlinks)) { - final uri = Uri.tryParse(href); - - if (uri == null || !uri.hasAuthority && !uri.hasFragment) { - String full; - if (baseHref != null) { - full = '${path.dirname(pathToCheck)}/$baseHref/$href'; - } else { - full = '${path.dirname(pathToCheck)}/$href'; - } - - final newPathToCheck = path.normalize(full); - final newFullPath = - path.normalize(path.joinAll([origin, newPathToCheck])); - if (!visited.contains(newFullPath)) { - toVisit.add(Tuple2(newPathToCheck, newFullPath)); - visited.add(newFullPath); - } - } - } - } - for (var visitPaths in toVisit) { - _doCheck(packageGraph, origin, visited, visitPaths.item1, pathToCheck, - visitPaths.item2); - } - _onCheckProgress.add(pathToCheck); - } - - Map> _hrefs; - - /// Don't call this method more than once, and only after you've - /// generated all docs for the Package. - void _validateLinks(PackageGraph packageGraph, String origin) { - assert(_hrefs == null); - _hrefs = packageGraph.allHrefs; - - final visited = {}; - logInfo('Validating docs...'); - _doCheck(packageGraph, origin, visited, 'index.html'); - _doOrphanCheck(packageGraph, origin, visited); - _doSearchIndexCheck(packageGraph, origin, visited); - } - - /// Runs [generateDocs] function and properly handles the errors. - /// - /// Passing in a [postProcessCallback] to do additional processing after - /// the documentation is generated. - void executeGuarded([ - Future Function(DartdocOptionContext) postProcessCallback, - ]) { - onCheckProgress.listen(logProgress); - // This function should *never* await `runZonedGuarded` because the errors - // thrown in generateDocs are uncaught. We want this because uncaught errors - // cause IDE debugger to automatically stop at the exception. - // - // If you await the zone, the code that comes after the await is not - // executed if the zone dies due to uncaught error. To avoid this confusion, - // never await `runZonedGuarded` and never change the return value of - // [executeGuarded]. - runZonedGuarded( - () async { - await generateDocs(); - await postProcessCallback?.call(config); - }, - (e, chain) { - if (e is DartdocFailure) { - stderr.writeln('\n$_dartdocFailedMessage: $e.'); - exitCode = 1; - } else { - stderr.writeln('\n$_dartdocFailedMessage: $e\n$chain'); - exitCode = 255; - } - }, - zoneSpecification: ZoneSpecification( - print: (_, __, ___, String line) => logPrint(line), - ), - ); - } -} - -/// The results of a [Dartdoc.generateDocs] call. -class DartdocResults { - final PackageMeta packageMeta; - final PackageGraph packageGraph; - final Folder outDir; - - DartdocResults(this.packageMeta, this.packageGraph, this.outDir); -} - -String get _dartdocFailedMessage => - 'dartdoc $packageVersion (${Platform.script.path}) failed'; diff --git a/lib/src/dartdoc.dart b/lib/src/dartdoc.dart new file mode 100644 index 0000000000..d15bc05b09 --- /dev/null +++ b/lib/src/dartdoc.dart @@ -0,0 +1,515 @@ +// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +library src.dartdoc; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io' show Platform, exitCode, stderr; + +import 'package:analyzer/file_system/file_system.dart'; +import 'package:dartdoc/options.dart'; +import 'package:dartdoc/src/dartdoc_options.dart'; +import 'package:dartdoc/src/failure.dart'; +import 'package:dartdoc/src/generator/empty_generator.dart'; +import 'package:dartdoc/src/generator/generator.dart'; +import 'package:dartdoc/src/generator/html_generator.dart'; +import 'package:dartdoc/src/generator/markdown_generator.dart'; +import 'package:dartdoc/src/logging.dart'; +import 'package:dartdoc/src/matching_link_result.dart'; +import 'package:dartdoc/src/model/model.dart'; +import 'package:dartdoc/src/package_meta.dart'; +import 'package:dartdoc/src/tuple.dart'; +import 'package:dartdoc/src/utils.dart'; +import 'package:dartdoc/src/version.dart'; +import 'package:dartdoc/src/warnings.dart'; +import 'package:html/parser.dart' show parse; +import 'package:meta/meta.dart'; +import 'package:path/path.dart' as path; + +const String programName = 'dartdoc'; +// Update when pubspec version changes by running `pub run build_runner build` +const String dartdocVersion = packageVersion; + +class DartdocFileWriter implements FileWriter { + final String _outputDir; + @override + final ResourceProvider resourceProvider; + final Map _fileElementMap = {}; + @override + final Set writtenFiles = {}; + + DartdocFileWriter(this._outputDir, this.resourceProvider); + + @override + void writeBytes( + String filePath, + List content, { + bool allowOverwrite = false, + }) { + // Replace '/' separators with proper separators for the platform. + var outFile = path.joinAll(filePath.split('/')); + + if (!allowOverwrite) { + _warnAboutOverwrite(outFile, null); + } + _fileElementMap[outFile] = null; + + var file = _getFile(outFile); + file.writeAsBytesSync(content); + writtenFiles.add(outFile); + logProgress(outFile); + } + + @override + void write(String filePath, String content, {Warnable? element}) { + // Replace '/' separators with proper separators for the platform. + var outFile = path.joinAll(filePath.split('/')); + + _warnAboutOverwrite(outFile, element); + _fileElementMap[outFile] = element; + + var file = _getFile(outFile); + file.writeAsStringSync(content); + writtenFiles.add(outFile); + logProgress(outFile); + } + + void _warnAboutOverwrite(String outFile, Warnable? element) { + if (_fileElementMap.containsKey(outFile)) { + assert(element != null, + 'Attempted overwrite of $outFile without corresponding element'); + var originalElement = _fileElementMap[outFile]; + var referredFrom = []; + if (originalElement != null) referredFrom.add(originalElement); + element?.warn(PackageWarning.duplicateFile, + message: outFile, referredFrom: referredFrom); + } + } + + /// Returns the file at [outFile] relative to [_outputDir], creating the + /// parent directory if necessary. + File _getFile(String outFile) { + var file = resourceProvider + .getFile(resourceProvider.pathContext.join(_outputDir, outFile)); + var parent = file.parent2; + if (!parent.exists) { + parent.create(); + } + return file; + } +} + +/// Generates Dart documentation for all public Dart libraries in the given +/// directory. +class Dartdoc { + Generator _generator; + final PackageBuilder packageBuilder; + final DartdocOptionContext config; + final Set _writtenFiles = {}; + late final Folder _outputDir = config.resourceProvider + .getFolder(config.resourceProvider.pathContext.absolute(config.output)) + ..create(); + + // Fires when the self checks make progress. + final StreamController _onCheckProgress = + StreamController(sync: true); + + Dartdoc._(this.config, this._generator, this.packageBuilder); + + // TODO(srawlins): Remove when https://github.com/dart-lang/linter/issues/2706 + // is fixed. + // ignore: unnecessary_getters_setters + Generator get generator => _generator; + + @visibleForTesting + // TODO(srawlins): Remove when https://github.com/dart-lang/linter/issues/2706 + // is fixed. + // ignore: unnecessary_getters_setters + set generator(Generator newGenerator) => _generator = newGenerator; + + /// Asynchronous factory method that builds Dartdoc with an empty generator. + static Future withEmptyGenerator( + DartdocOptionContext config, + PackageBuilder packageBuilder, + ) async { + return Dartdoc._( + config, + await initEmptyGenerator(config), + packageBuilder, + ); + } + + /// Asynchronous factory method that builds Dartdoc with a generator + /// determined by the given context. + static Future fromContext( + DartdocGeneratorOptionContext context, + PackageBuilder packageBuilder, + ) async { + Generator generator; + switch (context.format) { + case 'html': + generator = await initHtmlGenerator(context); + break; + case 'md': + generator = await initMarkdownGenerator(context); + break; + default: + throw DartdocFailure('Unsupported output format: ${context.format}'); + } + return Dartdoc._( + context, + generator, + packageBuilder, + ); + } + + Stream get onCheckProgress => _onCheckProgress.stream; + + @visibleForTesting + Future generateDocsBase() async { + var stopwatch = Stopwatch()..start(); + var packageGraph = await packageBuilder.buildPackageGraph(); + var seconds = stopwatch.elapsedMilliseconds / 1000.0; + var libs = packageGraph.libraries.length; + logInfo("Initialized dartdoc with $libs librar${libs == 1 ? 'y' : 'ies'} " + 'in ${seconds.toStringAsFixed(1)} seconds'); + stopwatch.reset(); + + // Create the out directory. + if (!_outputDir.exists) _outputDir.create(); + + var writer = DartdocFileWriter(_outputDir.path, config.resourceProvider); + await generator.generate(packageGraph, writer); + + _writtenFiles.addAll(writer.writtenFiles); + if (config.validateLinks && _writtenFiles.isNotEmpty) { + _validateLinks(packageGraph, _outputDir.path); + } + + var warnings = packageGraph.packageWarningCounter.warningCount; + var errors = packageGraph.packageWarningCounter.errorCount; + if (warnings == 0 && errors == 0) { + logInfo('no issues found'); + } else { + logWarning("Found $warnings ${pluralize('warning', warnings)} " + "and $errors ${pluralize('error', errors)}."); + } + + seconds = stopwatch.elapsedMilliseconds / 1000.0; + libs = packageGraph.localPublicLibraries.length; + logInfo("Documented $libs public librar${libs == 1 ? 'y' : 'ies'} " + 'in ${seconds.toStringAsFixed(1)} seconds'); + + if (config.showStats) { + logInfo(markdownStats.buildReport()); + } + return DartdocResults(config.topLevelPackageMeta, packageGraph, _outputDir); + } + + /// Generate Dartdoc documentation. + /// + /// [DartdocResults] is returned if dartdoc succeeds. [DartdocFailure] is + /// thrown if dartdoc fails in an expected way, for example if there is an + /// analysis error in the code. + Future generateDocs() async { + DartdocResults? dartdocResults; + try { + logInfo('Documenting ${config.topLevelPackageMeta}...'); + + dartdocResults = await generateDocsBase(); + if (dartdocResults.packageGraph.localPublicLibraries.isEmpty) { + logWarning('dartdoc could not find any libraries to document'); + } + + final errorCount = + dartdocResults.packageGraph.packageWarningCounter.errorCount; + if (errorCount > 0) { + throw DartdocFailure('encountered $errorCount errors'); + } + var outDirPath = config.resourceProvider.pathContext + .absolute(dartdocResults.outDir.path); + logInfo('Success! Docs generated into $outDirPath'); + return dartdocResults; + } finally { + dartdocResults?.packageGraph.dispose(); + } + } + + /// Warn on file paths. + void _warn(PackageGraph packageGraph, PackageWarning kind, String warnOn, + String origin, + {String? referredFrom}) { + // Ordinarily this would go in [Package.warn], but we don't actually know what + // ModelElement to warn on yet. + Warnable? warnOnElement; + var referredFromElements = {}; + Set? warnOnElements; + + // Make all paths relative to origin. + if (path.isWithin(origin, warnOn)) { + warnOn = path.relative(warnOn, from: origin); + } + if (referredFrom != null) { + if (path.isWithin(origin, referredFrom)) { + referredFrom = path.relative(referredFrom, from: origin); + } + var hrefReferredFrom = _hrefs[referredFrom]; + // Source paths are always relative. + if (hrefReferredFrom != null) { + referredFromElements.addAll(hrefReferredFrom); + } + } + warnOnElements = _hrefs[warnOn]; + + if (referredFromElements.any((e) => e.isCanonical)) { + referredFromElements.removeWhere((e) => !e.isCanonical); + } + if (warnOnElements != null) { + for (var e in warnOnElements) { + if (e.isCanonical) { + warnOnElement = e; + break; + } + } + } + + if (referredFromElements.isEmpty && referredFrom == 'index.html') { + referredFromElements.add(packageGraph.defaultPackage); + } + var message = warnOn; + if (referredFrom == 'index.json') message = '$warnOn (from index.json)'; + packageGraph.warnOnElement(warnOnElement, kind, + message: message, referredFrom: referredFromElements); + } + + void _doOrphanCheck( + PackageGraph packageGraph, String origin, Set visited) { + var normalOrigin = path.normalize(origin); + var staticAssets = path.joinAll([normalOrigin, 'static-assets', '']); + var indexJson = path.joinAll([normalOrigin, 'index.json']); + var foundIndexJson = false; + + void checkDirectory(Folder dir) { + for (var f in dir.getChildren()) { + if (f is Folder) { + checkDirectory(f); + continue; + } + var fullPath = path.normalize(f.path); + if (fullPath.startsWith(staticAssets)) { + continue; + } + if (path.equals(fullPath, indexJson)) { + foundIndexJson = true; + _onCheckProgress.add(fullPath); + continue; + } + if (visited.contains(fullPath)) continue; + var relativeFullPath = path.relative(fullPath, from: normalOrigin); + if (!_writtenFiles.contains(relativeFullPath)) { + // This isn't a file we wrote (this time); don't claim we did. + _warn( + packageGraph, PackageWarning.unknownFile, fullPath, normalOrigin); + } else { + // Error messages are orphaned by design and do not appear in the search + // index. + if (const {'__404error.html', 'categories.json'}.contains(fullPath)) { + _warn(packageGraph, PackageWarning.orphanedFile, fullPath, + normalOrigin); + } + } + _onCheckProgress.add(fullPath); + } + } + + checkDirectory(config.resourceProvider.getFolder(normalOrigin)); + + if (!foundIndexJson) { + _warn(packageGraph, PackageWarning.brokenLink, indexJson, normalOrigin); + _onCheckProgress.add(indexJson); + } + } + + // This is extracted to save memory during the check; be careful not to hang + // on to anything referencing the full file and doc tree. + Tuple2, String?>? _getStringLinksAndHref(String fullPath) { + var file = config.resourceProvider.getFile(fullPath); + if (!file.exists) { + return null; + } + // TODO(srawlins): It is possible that instantiating an HtmlParser using + // `lowercaseElementName: false` and `lowercaseAttrName: false` may save + // time or memory. + var doc = parse(file.readAsBytesSync()); + var base = doc.querySelector('base'); + String? baseHref; + if (base != null) { + baseHref = base.attributes['href']; + } + var links = doc.querySelectorAll('a'); + var stringLinks = links + .map((link) => link.attributes['href']) + .whereType() + .where((href) => href != '') + .toList(); + + return Tuple2(stringLinks, baseHref); + } + + void _doSearchIndexCheck( + PackageGraph packageGraph, String origin, Set visited) { + var fullPath = path.joinAll([origin, 'index.json']); + var indexPath = path.joinAll([origin, 'index.html']); + var file = config.resourceProvider.getFile(fullPath); + if (!file.exists) { + return; + } + var decoder = JsonDecoder(); + List jsonData = decoder.convert(file.readAsStringSync()); + + var found = {}; + found.add(fullPath); + // The package index isn't supposed to be in the search, so suppress the + // warning. + found.add(indexPath); + for (Map entry in jsonData) { + if (entry.containsKey('href')) { + var entryPath = + path.joinAll([origin, ...path.posix.split(entry['href'])]); + if (!visited.contains(entryPath)) { + _warn(packageGraph, PackageWarning.brokenLink, entryPath, + path.normalize(origin), + referredFrom: fullPath); + } + found.add(entryPath); + } + } + // Missing from search index + var missingFromSearch = visited.difference(found); + for (var s in missingFromSearch) { + _warn(packageGraph, PackageWarning.missingFromSearchIndex, s, + path.normalize(origin), + referredFrom: fullPath); + } + } + + void _doCheck(PackageGraph packageGraph, String origin, Set visited, + String pathToCheck, + [String? source, String? fullPath]) { + fullPath ??= path.normalize(path.joinAll([origin, pathToCheck])); + + var stringLinksAndHref = _getStringLinksAndHref(fullPath); + if (stringLinksAndHref == null) { + _warn(packageGraph, PackageWarning.brokenLink, pathToCheck, + path.normalize(origin), + referredFrom: source); + _onCheckProgress.add(pathToCheck); + // Remove so that we properly count that the file doesn't exist for + // the orphan check. + visited.remove(fullPath); + return; + } + visited.add(fullPath); + var stringLinks = stringLinksAndHref.item1; + var baseHref = stringLinksAndHref.item2; + + // Prevent extremely large stacks by storing the paths we are using + // here instead -- occasionally, very large jobs have overflowed + // the stack without this. + // (newPathToCheck, newFullPath) + var toVisit = >{}; + + final ignoreHyperlinks = RegExp(r'^(https:|http:|mailto:|ftp:)'); + for (final href in stringLinks) { + if (!href.startsWith(ignoreHyperlinks)) { + final uri = Uri.tryParse(href); + + if (uri == null || !uri.hasAuthority && !uri.hasFragment) { + String full; + if (baseHref != null) { + full = '${path.dirname(pathToCheck)}/$baseHref/$href'; + } else { + full = '${path.dirname(pathToCheck)}/$href'; + } + + final newPathToCheck = path.normalize(full); + final newFullPath = + path.normalize(path.joinAll([origin, newPathToCheck])); + if (!visited.contains(newFullPath)) { + toVisit.add(Tuple2(newPathToCheck, newFullPath)); + visited.add(newFullPath); + } + } + } + } + for (var visitPaths in toVisit) { + _doCheck(packageGraph, origin, visited, visitPaths.item1, pathToCheck, + visitPaths.item2); + } + _onCheckProgress.add(pathToCheck); + } + + late final Map> _hrefs; + + /// Don't call this method more than once, and only after you've + /// generated all docs for the Package. + void _validateLinks(PackageGraph packageGraph, String origin) { + _hrefs = packageGraph.allHrefs; + + final visited = {}; + logInfo('Validating docs...'); + _doCheck(packageGraph, origin, visited, 'index.html'); + _doOrphanCheck(packageGraph, origin, visited); + _doSearchIndexCheck(packageGraph, origin, visited); + } + + /// Runs [generateDocs] function and properly handles the errors. + /// + /// Passing in a [postProcessCallback] to do additional processing after + /// the documentation is generated. + void executeGuarded([ + Future Function(DartdocOptionContext)? postProcessCallback, + ]) { + onCheckProgress.listen(logProgress); + // This function should *never* await `runZonedGuarded` because the errors + // thrown in generateDocs are uncaught. We want this because uncaught errors + // cause IDE debugger to automatically stop at the exception. + // + // If you await the zone, the code that comes after the await is not + // executed if the zone dies due to uncaught error. To avoid this confusion, + // never await `runZonedGuarded` and never change the return value of + // [executeGuarded]. + runZonedGuarded( + () async { + await generateDocs(); + await postProcessCallback?.call(config); + }, + (e, chain) { + if (e is DartdocFailure) { + stderr.writeln('\n$_dartdocFailedMessage: $e.'); + exitCode = 1; + } else { + stderr.writeln('\n$_dartdocFailedMessage: $e\n$chain'); + exitCode = 255; + } + }, + zoneSpecification: ZoneSpecification( + print: (_, __, ___, String line) => logPrint(line), + ), + ); + } +} + +/// The results of a [Dartdoc.generateDocs] call. +class DartdocResults { + final PackageMeta packageMeta; + final PackageGraph packageGraph; + final Folder outDir; + + DartdocResults(this.packageMeta, this.packageGraph, this.outDir); +} + +String get _dartdocFailedMessage => + 'dartdoc $packageVersion (${Platform.script.path}) failed'; diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index be9690206c..cfc76e9d0c 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -753,7 +753,8 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// This doesn't know anything about [PackageGraph.inheritThrough] and probably /// shouldn't, so using it with [Inheritable]s without special casing is /// not advised. - ModelElement findCanonicalModelElementFor(Element e, + // FIXME(nnbd): remove null check ignore in model_utils after migration + ModelElement /*?*/ findCanonicalModelElementFor(Element e, {Container preferredClass}) { assert(allLibrariesAdded); var lib = findCanonicalLibraryFor(e); diff --git a/lib/src/model_utils.dart b/lib/src/model_utils.dart index 670fd9d0f2..6509d6cb58 100644 --- a/lib/src/model_utils.dart +++ b/lib/src/model_utils.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 - library dartdoc.model_utils; import 'dart:convert'; @@ -28,11 +26,11 @@ final Map _fileContents = {}; /// On windows, globs are assumed to use absolute Windows paths with drive /// letters in combination with globs, e.g. `C:\foo\bar\*.txt`. `fullName` /// also is assumed to have a drive letter. -bool matchGlobs(List globs, String fullName, {bool isWindows}) { - isWindows ??= Platform.isWindows; +bool matchGlobs(List globs, String fullName, {bool? isWindows}) { + var windows = isWindows ?? Platform.isWindows; var filteredGlobs = []; - if (isWindows) { + if (windows) { // TODO(jcollins-g): port this special casing to the glob package. var fullNameDriveLetter = _driveLetterMatcher.stringMatch(fullName); if (fullNameDriveLetter == null) { @@ -55,20 +53,18 @@ bool matchGlobs(List globs, String fullName, {bool isWindows}) { } return filteredGlobs.any((g) => - Glob(g, context: isWindows ? path.windows : path.posix) - .matches(fullName)); + Glob(g, context: windows ? path.windows : path.posix).matches(fullName)); } /// Returns the [AstNode] for a given [Element]. /// /// Uses a precomputed map of [element.source.fullName] to [CompilationUnit] /// to avoid linear traversal in [ResolvedLibraryElementImpl.getElementDeclaration]. -AstNode getAstNode( +AstNode? getAstNode( Element element, Map compilationUnitMap) { - if (element?.source?.fullName != null && - !element.isSynthetic && - element.nameOffset != -1) { - var unit = compilationUnitMap[element.source.fullName]; + var fullName = element.source?.fullName; + if (fullName != null && !element.isSynthetic && element.nameOffset != -1) { + var unit = compilationUnitMap[fullName]; if (unit != null) { var locator = NodeLocator2(element.nameOffset); return (locator.searchWithin(unit)?.parent); @@ -100,6 +96,8 @@ Iterable findCanonicalFor( return containers.map((c) => c.packageGraph.findCanonicalModelElementFor(c.element) as InheritingContainer ?? + // FIXME(nnbd) : remove ignore after package_graph is migrated + // ignore: dead_null_aware_expression c); } @@ -109,9 +107,9 @@ Iterable findCanonicalFor( /// allowed in some environments, so avoid using this. // TODO(jcollins-g): consider deprecating this and the `--include-source` // feature that uses it now that source code linking is possible. -String getFileContentsFor(Element e, ResourceProvider resourceProvider) { - var location = e.source.fullName; - if (!_fileContents.containsKey(location)) { +String? getFileContentsFor(Element e, ResourceProvider resourceProvider) { + var location = e.source?.fullName; + if (location != null && !_fileContents.containsKey(location)) { var contents = resourceProvider.getFile(location).readAsStringSync(); _fileContents.putIfAbsent(location, () => contents); } @@ -120,15 +118,17 @@ String getFileContentsFor(Element e, ResourceProvider resourceProvider) { final RegExp slashes = RegExp(r'[\/]'); bool hasPrivateName(Element e) { - if (e.name == null) return false; + var elementName = e.name; + if (elementName == null) return false; - if (e.name.startsWith('_')) { + if (elementName.startsWith('_')) { return true; } // GenericFunctionTypeElements have the name we care about in the enclosing // element. if (e is GenericFunctionTypeElement) { - if (e.enclosingElement.name.startsWith('_')) { + var enclosingElementName = e.enclosingElement?.name; + if (enclosingElementName != null && enclosingElementName.startsWith('_')) { return true; } } @@ -139,11 +139,14 @@ bool hasPrivateName(Element e) { return true; } if (e is LibraryElement) { - var locationParts = e.location.components[0].split(slashes); - // TODO(jcollins-g): Implement real cross package detection - if (locationParts.length >= 2 && - locationParts[0].startsWith('package:') && - locationParts[1] == 'src') return true; + var elementLocation = e.location; + if (elementLocation != null) { + var locationParts = elementLocation.components[0].split(slashes); + // TODO(jcollins-g): Implement real cross package detection + if (locationParts.length >= 2 && + locationParts[0].startsWith('package:') && + locationParts[1] == 'src') return true; + } } return false; } diff --git a/lib/src/special_elements.dart b/lib/src/special_elements.dart index fd8d98191e..49907b57c2 100644 --- a/lib/src/special_elements.dart +++ b/lib/src/special_elements.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 - /// Handling for special elements within Dart. When identified these /// may alter the interpretation and documentation generated for other /// [ModelElement]s. @@ -60,7 +58,7 @@ class _SpecialClassDefinition { /// Get the filename for the Dart Library where this [ModelElement] /// is declared, or `null` if its URI does not denote a library in /// the specified SDK. - String /*?*/ getSpecialFilename(DartSdk sdk) => + String? getSpecialFilename(DartSdk sdk) => sdk.mapDartUri(specialFileUri)?.fullName; bool matchesClass(Class modelClass) { @@ -90,7 +88,7 @@ const Map _specialClassDefinitions = { /// classes. Set specialLibraryFiles(DartSdk sdk) => _specialClassDefinitions.values .map((_SpecialClassDefinition d) => d.getSpecialFilename(sdk)) - .where((String s) => s != null) + .whereType() .toSet(); /// Class for managing special [Class] objects inside Dartdoc. @@ -102,7 +100,7 @@ class SpecialClasses { /// Add a class object that could be special. void addSpecial(Class aClass) { if (_specialClassDefinitions.containsKey(aClass.name)) { - var d = _specialClassDefinitions[aClass.name]; + var d = _specialClassDefinitions[aClass.name]!; if (d.matchesClass(aClass)) { assert(!_specialClass.containsKey(d.specialClass) || _specialClass[d.specialClass] == aClass); @@ -119,5 +117,5 @@ class SpecialClasses { } } - Class operator [](SpecialClass specialClass) => _specialClass[specialClass]; + Class? operator [](SpecialClass specialClass) => _specialClass[specialClass]; } From e58770bb9c10bc5ac7bb8279051efed3d9a038c3 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Tue, 12 Oct 2021 15:55:40 -0700 Subject: [PATCH 02/21] rebuild --- .../templates.runtime_renderers.dart | 35 +++++++++---------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/lib/src/generator/templates.runtime_renderers.dart b/lib/src/generator/templates.runtime_renderers.dart index 16816e4561..6dbb9a312e 100644 --- a/lib/src/generator/templates.runtime_renderers.dart +++ b/lib/src/generator/templates.runtime_renderers.dart @@ -1963,12 +1963,13 @@ class _Renderer_CommentReferable extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => + c.referenceGrandparentOverrides == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.referenceGrandparentOverrides.map((e) => - renderSimple(e, ast, r.template, sink, - parent: r, - getters: _invisibleGetters['CommentReferable'])); + renderSimple( + c.referenceGrandparentOverrides, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'referenceName': Property( @@ -10761,18 +10762,6 @@ class _Renderer_Object extends RendererBase { parent: r, getters: _invisibleGetters['int']); }, ), - 'runtimeType': Property( - getValue: (CT_ c) => c.runtimeType, - renderVariable: (CT_ c, Property self, - List remainingNames) => - self.renderSimpleVariable(c, remainingNames, 'Type'), - isNullValue: (CT_ c) => c.runtimeType == null, - renderValue: (CT_ c, RendererBase r, - List ast, StringSink sink) { - renderSimple(c.runtimeType, ast, r.template, sink, - parent: r, getters: _invisibleGetters['Type']); - }, - ), }); _Renderer_Object(Object context, RendererBase parent, @@ -15598,6 +15587,17 @@ const _invisibleGetters = { 'overriddenDepth' }, 'InheritanceManager3': {'hashCode', 'runtimeType'}, + 'Iterable': { + 'hashCode', + 'runtimeType', + 'iterator', + 'length', + 'isEmpty', + 'isNotEmpty', + 'first', + 'last', + 'single' + }, 'LibraryElement': { 'hashCode', 'runtimeType', @@ -15888,7 +15888,6 @@ const _invisibleGetters = { 'customFooterContent', 'customInnerFooterText' }, - 'Type': {'hashCode', 'runtimeType'}, 'TypeAliasElement': { 'hashCode', 'runtimeType', From 42b408488ca7611e09cedd6517a5d8bb9f658be1 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Wed, 13 Oct 2021 11:05:38 -0700 Subject: [PATCH 03/21] migrate more things --- tool/builder.dart | 2 - tool/doc_packages.dart | 28 +++++------ tool/subprocess_launcher.dart | 91 ++++++++++++++++------------------- 3 files changed, 54 insertions(+), 67 deletions(-) diff --git a/tool/builder.dart b/tool/builder.dart index 31e7804ee5..c9d1aad05a 100644 --- a/tool/builder.dart +++ b/tool/builder.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 - import 'dart:async'; import 'package:build/build.dart'; diff --git a/tool/doc_packages.dart b/tool/doc_packages.dart index b8ea616150..244798f4a1 100644 --- a/tool/doc_packages.dart +++ b/tool/doc_packages.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 - /// A CLI tool to generate documentation for packages from pub.dartlang.org. library dartdoc.doc_packages; @@ -86,7 +84,7 @@ void performGenerate(int page) { _packageUrls(page).then((List packages) { return _getPackageInfos(packages).then((List infos) { - return Future.forEach(infos, (info) { + return Future.forEach(infos, (PackageInfo info) { return _printGenerationResult(info, _generateFor(info)); }); }); @@ -147,7 +145,7 @@ Future> _getPackageInfos(List packageUrls) { return Future.wait(futures); } -StringBuffer _logBuffer; +StringBuffer? _logBuffer; /// Generate the docs for the given package into _rootDir. Return whether /// generation was performed or was skipped (due to an older package). @@ -195,7 +193,7 @@ Future _generateFor(PackageInfo package) async { } Future _exec(String command, List args, - {String cwd, + {String? cwd, bool quiet = false, Duration timeout = const Duration(seconds: 60)}) { return Process.start(command, args, workingDirectory: cwd) @@ -209,20 +207,16 @@ Future _exec(String command, List args, if (code != 0) throw code; }); - if (timeout != null) { - return f.timeout(timeout, onTimeout: () { - _log('Timing out operation $command.'); - process.kill(); - throw 'timeout on $command'; - }); - } else { - return f; - } + return f.timeout(timeout, onTimeout: () { + _log('Timing out operation $command.'); + process.kill(); + throw 'timeout on $command'; + }); }); } bool _isOldSdkConstraint(Map pubspecInfo) { - var environment = pubspecInfo['environment'] as Map; + var environment = pubspecInfo['environment'] as Map?; if (environment != null) { var sdk = environment['sdk']; if (sdk != null) { @@ -243,8 +237,10 @@ bool _isOldSdkConstraint(Map pubspecInfo) { return false; } +/// Log entries will be dropped if [_logBuffer] has not been initialized. void _log(String str) { - _logBuffer.write(str); + assert(_logBuffer != null); + _logBuffer?.write(str); } class PackageInfo { diff --git a/tool/subprocess_launcher.dart b/tool/subprocess_launcher.dart index 679427ad70..f8770f0844 100644 --- a/tool/subprocess_launcher.dart +++ b/tool/subprocess_launcher.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 - import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -14,11 +12,11 @@ import 'package:path/path.dart' as p; /// Keeps track of coverage data automatically for any processes run by this /// [CoverageSubprocessLauncher]. Requires that these be dart processes. class CoverageSubprocessLauncher extends SubprocessLauncher { - CoverageSubprocessLauncher(String context, [Map environment]) - : super(context, environment) { - environment ??= {}; - environment['DARTDOC_COVERAGE_DATA'] = tempDir.path; - } + CoverageSubprocessLauncher(String context, [Map? environment]) + : super( + context, + (environment ?? {}) + ..addAll({'DARTDOC_COVERAGE_DATA': tempDir.path})); static int nextRun = 0; @@ -31,24 +29,20 @@ class CoverageSubprocessLauncher extends SubprocessLauncher { // is enabled. static List>>> coverageResults = []; - static Directory _tempDir; - static Directory get tempDir { - if (_tempDir == null) { - if (Platform.environment['DARTDOC_COVERAGE_DATA'] != null) { - _tempDir = Directory(Platform.environment['DARTDOC_COVERAGE_DATA']); - } else { - _tempDir = Directory.systemTemp.createTempSync('dartdoc_coverage_data'); - } + static Directory tempDir = () { + var coverageData = Platform.environment['DARTDOC_COVERAGE_DATA']; + if (coverageData != null) { + return Directory(coverageData); } - return _tempDir; - } + return Directory.systemTemp.createTempSync('dartdoc_coverage_data'); + }(); static String buildNextCoverageFilename() => p.join(tempDir.path, 'dart-cov-$pid-${nextRun++}.json'); /// Call once all coverage runs have been generated by calling runStreamed /// on all [CoverageSubprocessLaunchers]. - static Future generateCoverageToFile( + static Future generateCoverageToFile( File outputFile, ResourceProvider resourceProvider) async { if (!coverageEnabled) return Future.value(null); var currentCoverageResults = coverageResults; @@ -77,10 +71,10 @@ class CoverageSubprocessLauncher extends SubprocessLauncher { @override Future>> runStreamed( String executable, List arguments, - {String workingDirectory, - Map environment, + {String? workingDirectory, + Map? environment, bool includeParentEnvironment = true, - void Function(String) perLine}) async { + void Function(String)? perLine}) async { environment ??= {}; assert( executable == Platform.executable || @@ -91,16 +85,17 @@ class CoverageSubprocessLauncher extends SubprocessLauncher { void parsePortAsString(String line) { if (!portAsString.isCompleted && coverageEnabled) { var m = _observatoryPortRegexp.matchAsPrefix(line); - if (m?.group(1) != null) portAsString.complete(m.group(1)); + if (m != null) { + if (m.group(1) != null) portAsString.complete(m.group(1)); + } } else { if (perLine != null) perLine(line); } } - Completer>> coverageResult; + Completer>> coverageResult = Completer(); if (coverageEnabled) { - coverageResult = Completer(); // This must be added before awaiting in this method. coverageResults.add(coverageResult.future); arguments = [ @@ -139,29 +134,27 @@ class CoverageSubprocessLauncher extends SubprocessLauncher { class SubprocessLauncher { final String context; - final Map environmentDefaults; + final Map environmentDefaults = {}; String get prefix => context.isNotEmpty ? '$context: ' : ''; // from flutter:dev/tools/dartdoc.dart, modified static Future _printStream(Stream> stream, Stdout output, - {String prefix = '', Iterable Function(String line) filter}) { - assert(prefix != null); - filter ??= (line) => [line]; + {String prefix = '', + required Iterable Function(String line) filter}) { return stream .transform(utf8.decoder) .transform(const LineSplitter()) .expand(filter) .listen((String line) { - if (line != null) { - output.write('$prefix$line'.trim()); - output.write('\n'); - } + output.write('$prefix$line'.trim()); + output.write('\n'); }).asFuture(); } - SubprocessLauncher(this.context, [Map environment]) - : environmentDefaults = environment ?? {}; + SubprocessLauncher(this.context, [Map? environment]) { + environmentDefaults.addAll(environment ?? {}); + } /// A wrapper around start/await process.exitCode that will display the /// output of the executable continuously and fail on non-zero exit codes. @@ -175,20 +168,21 @@ class SubprocessLauncher { /// and their associated JSON objects. Future>> runStreamed( String executable, List arguments, - {String workingDirectory, - Map environment, + {String? workingDirectory, + Map? environment, bool includeParentEnvironment = true, - void Function(String) perLine}) async { - environment ??= {}; - environment.addAll(environmentDefaults); - List> jsonObjects; + void Function(String)? perLine}) async { + environment = {} + ..addAll(environmentDefaults) + ..addAll(environment ?? {}); + List> jsonObjects = []; /// Allow us to pretend we didn't pass the JSON flag in to dartdoc by /// printing what dartdoc would have printed without it, yet storing /// json objects into [jsonObjects]. Iterable jsonCallback(String line) { if (perLine != null) perLine(line); - Map result; + Map? result; try { result = json.decoder.convert(line); } on FormatException { @@ -198,10 +192,9 @@ class SubprocessLauncher { // line. Just ignore it and leave result null. } if (result != null) { - jsonObjects ??= []; jsonObjects.add(result); if (result.containsKey('message')) { - line = result['message']; + line = result['message'] as String; } else if (result.containsKey('data')) { var data = result['data'] as Map; line = data['text']; @@ -212,12 +205,12 @@ class SubprocessLauncher { stderr.write('$prefix+ '); if (workingDirectory != null) stderr.write('(cd "$workingDirectory" && '); - if (environment != null) { - stderr.write(environment.keys.map((String key) { - if (environment[key].contains(_quotables)) { - return "$key='${environment[key]}'"; + if (environment.isNotEmpty) { + stderr.write(environment.entries.map((MapEntry entry) { + if (entry.key.contains(_quotables)) { + return "${entry.key}='${entry.value}'"; } else { - return '$key=${environment[key]}'; + return '${entry.key}=${entry.value}'; } }).join(' ')); stderr.write(' '); @@ -235,7 +228,7 @@ class SubprocessLauncher { if (workingDirectory != null) stderr.write(')'); stderr.write('\n'); - if (Platform.environment.containsKey('DRY_RUN')) return null; + if (Platform.environment.containsKey('DRY_RUN')) return {}; var realExecutable = executable; var realArguments = []; From cd518ea67da7f7e77ed1b2f22f721330ce8a7700 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Wed, 13 Oct 2021 12:36:49 -0700 Subject: [PATCH 04/21] subprocess --- tool/subprocess_launcher.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tool/subprocess_launcher.dart b/tool/subprocess_launcher.dart index f8770f0844..783c231835 100644 --- a/tool/subprocess_launcher.dart +++ b/tool/subprocess_launcher.dart @@ -69,7 +69,7 @@ class CoverageSubprocessLauncher extends SubprocessLauncher { } @override - Future>> runStreamed( + Future>> runStreamed( String executable, List arguments, {String? workingDirectory, Map? environment, @@ -166,7 +166,7 @@ class SubprocessLauncher { /// Windows (though some of the bashisms will no longer make sense). /// TODO(jcollins-g): refactor to return a stream of stderr/stdout lines /// and their associated JSON objects. - Future>> runStreamed( + Future>> runStreamed( String executable, List arguments, {String? workingDirectory, Map? environment, @@ -175,14 +175,14 @@ class SubprocessLauncher { environment = {} ..addAll(environmentDefaults) ..addAll(environment ?? {}); - List> jsonObjects = []; + List> jsonObjects = []; /// Allow us to pretend we didn't pass the JSON flag in to dartdoc by /// printing what dartdoc would have printed without it, yet storing /// json objects into [jsonObjects]. Iterable jsonCallback(String line) { if (perLine != null) perLine(line); - Map? result; + Map? result; try { result = json.decoder.convert(line); } on FormatException { From 574f9e0e311e5d05974898b7c71bda0f7a58498d Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Wed, 13 Oct 2021 12:54:49 -0700 Subject: [PATCH 05/21] type adjustment in grinder --- tool/grind.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tool/grind.dart b/tool/grind.dart index a1ebc02b6b..c8653315b9 100644 --- a/tool/grind.dart +++ b/tool/grind.dart @@ -553,7 +553,7 @@ Future testWithAnalyzerSdk() async { workingDirectory: sdkDartdoc); } -Future>> _buildSdkDocs( +Future>> _buildSdkDocs( String sdkDocsPath, Future futureCwd, [String label]) async { label ??= ''; @@ -576,7 +576,7 @@ Future>> _buildSdkDocs( workingDirectory: cwd); } -Future>> _buildTestPackageDocs( +Future>> _buildTestPackageDocs( String outputDir, String cwd, {List params, String label = '', String testPackagePath}) async { if (label != '') label = '-$label'; @@ -924,7 +924,7 @@ class FlutterRepo { SubprocessLauncher launcher; } -Future>> _buildFlutterDocs( +Future>> _buildFlutterDocs( String flutterPath, Future futureCwd, Map env, [String label]) async { var flutterRepo = await FlutterRepo.copyFromExistingFlutterRepo( From a058b820d21f4a700c9a9bdb86fb38ad0abe68f8 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 14 Oct 2021 15:00:53 -0700 Subject: [PATCH 06/21] partial --- lib/dartdoc.dart | 2 +- lib/src/element_type.dart | 7 +- lib/src/generator/generator_utils.dart | 12 +- lib/src/generator/template_data.dart | 3 +- lib/src/logging.dart | 10 +- lib/src/model/accessor.dart | 164 +++++----- lib/src/model/annotation.dart | 26 +- lib/src/model/canonicalization.dart | 12 +- lib/src/model/categorization.dart | 56 ++-- lib/src/model/class.dart | 44 +-- lib/src/model/comment_referable.dart | 1 - lib/src/model/constructor.dart | 87 +++--- lib/src/model/container.dart | 92 +++--- lib/src/model/container_member.dart | 28 +- lib/src/model/documentable.dart | 20 +- lib/src/model/documentation.dart | 20 +- lib/src/model/documentation_comment.dart | 104 +++---- lib/src/model/dynamic.dart | 10 +- lib/src/model/enclosed_element.dart | 4 +- lib/src/model/enum.dart | 40 +-- lib/src/model/extendable.dart | 2 +- lib/src/model/extension.dart | 72 ++--- lib/src/model/extension_target.dart | 12 +- lib/src/model/feature.dart | 16 +- lib/src/model/feature_set.dart | 6 +- lib/src/model/field.dart | 60 ++-- lib/src/model/getter_setter_combo.dart | 124 ++++---- lib/src/model/indexable.dart | 6 +- lib/src/model/inheritable.dart | 74 ++--- lib/src/model/inheriting_container.dart | 217 +++++++------- lib/src/model/library.dart | 198 ++++++------ lib/src/model/library_container.dart | 14 +- lib/src/model/locatable.dart | 6 +- lib/src/model/method.dart | 58 ++-- lib/src/model/mixin.dart | 28 +- lib/src/model/model.dart | 2 +- lib/src/model/model_element.dart | 367 +++++++++++------------ lib/src/model/model_function.dart | 42 +-- lib/src/model/model_node.dart | 22 +- lib/src/model/nameable.dart | 18 +- lib/src/model/never.dart | 8 +- lib/src/model/operator.dart | 14 +- lib/src/model/package.dart | 118 ++++---- lib/src/model/package_builder.dart | 65 ++-- lib/src/model/package_graph.dart | 252 ++++++++-------- lib/src/model/parameter.dart | 62 ++-- lib/src/model/prefix.dart | 20 +- lib/src/model/privacy.dart | 4 +- lib/src/model/source_code_mixin.dart | 12 +- lib/src/model/top_level_container.dart | 22 +- lib/src/model/top_level_variable.dart | 24 +- lib/src/model/type_parameter.dart | 58 ++-- lib/src/model/typedef.dart | 48 +-- 53 files changed, 1365 insertions(+), 1428 deletions(-) diff --git a/lib/dartdoc.dart b/lib/dartdoc.dart index 453897966f..351827f0eb 100644 --- a/lib/dartdoc.dart +++ b/lib/dartdoc.dart @@ -2,7 +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. -// @dart=2.9 + /// A documentation generator for Dart. /// /// Library interface is still experimental. diff --git a/lib/src/element_type.dart b/lib/src/element_type.dart index 4bdcb5ebd0..d2a7815de8 100644 --- a/lib/src/element_type.dart +++ b/lib/src/element_type.dart @@ -260,8 +260,7 @@ class AliasedElementType extends ParameterizedElementType with Aliased { ParameterizedType get type; /// Parameters, if available, for the underlying typedef. - List get aliasedParameters => - modelElement.isCallable ? modelElement.parameters : []; + late final List aliasedParameters = modelElement.isCallable ? modelElement.parameters : []; @override ElementTypeRenderer get _renderer => @@ -298,7 +297,7 @@ abstract class DefinedElementType extends ElementType { this.modelElement, ElementType? returnedFrom) : super(type, library, packageGraph, returnedFrom); - Element get element => modelElement.element; + Element get element => modelElement.element!; @override String get name => type.element!.name!; @@ -372,7 +371,7 @@ abstract class DefinedElementType extends ElementType { modelElement.referenceParents; @override - Iterable get referenceGrandparentOverrides => + Iterable? get referenceGrandparentOverrides => modelElement.referenceGrandparentOverrides; @internal diff --git a/lib/src/generator/generator_utils.dart b/lib/src/generator/generator_utils.dart index 23a5173440..6766aa7e34 100644 --- a/lib/src/generator/generator_utils.dart +++ b/lib/src/generator/generator_utils.dart @@ -14,9 +14,9 @@ import 'package:dartdoc/src/model/model_element.dart'; /// will likely want the same content for this. String generateCategoryJson(Iterable categories, bool pretty) { // ignore: omit_local_variable_types - final List> indexItems = + final List> indexItems = categories.map((Categorization categorization) { - final data = { + final data = { 'name': categorization.name, 'qualifiedName': categorization.fullyQualifiedName, 'href': categorization.href, @@ -49,7 +49,7 @@ String generateCategoryJson(Iterable categories, bool pretty) { String generateSearchIndexJson( Iterable indexedElements, bool pretty) { final indexItems = indexedElements.map((Indexable indexable) { - final data = { + final data = { 'name': indexable.name, 'qualifiedName': indexable.fullyQualifiedName, 'href': indexable.href, @@ -61,9 +61,9 @@ String generateSearchIndexJson( } if (indexable is EnclosedElement) { final ee = indexable as EnclosedElement; - data['enclosedBy'] = { - 'name': ee.enclosingElement.name, - 'type': ee.enclosingElement.kind + data['enclosedBy'] = { + 'name': ee.enclosingElement!.name, + 'type': ee.enclosingElement!.kind }; data['qualifiedName'] = indexable.fullyQualifiedName; diff --git a/lib/src/generator/template_data.dart b/lib/src/generator/template_data.dart index 95b58832d5..3d553b621e 100644 --- a/lib/src/generator/template_data.dart +++ b/lib/src/generator/template_data.dart @@ -51,7 +51,8 @@ abstract class TemplateData { String get bareHref { if (self is Indexable) { - return (self as Indexable).href.replaceAll(htmlBasePlaceholder, ''); + var selfHref = (self as Indexable).href ?? ''; + return selfHref.replaceAll(htmlBasePlaceholder, ''); } return ''; } diff --git a/lib/src/logging.dart b/lib/src/logging.dart index ddce9f144d..02a255d6cb 100644 --- a/lib/src/logging.dart +++ b/lib/src/logging.dart @@ -23,23 +23,23 @@ const Level progressLevel = Level('PROGRESS', 501); /// Has a value of `1201` – one more than [Level.SHOUT]. const Level printLevel = Level('PRINT', 1201); -void logWarning(Object message) { +void logWarning(String? message) { _logger.log(Level.WARNING, message); } -void logInfo(Object message) { +void logInfo(String? message) { _logger.log(Level.INFO, message); } -void logDebug(Object message) { +void logDebug(String? message) { _logger.log(Level.FINE, message); } -void logProgress(Object message) { +void logProgress(String? message) { _logger.log(progressLevel, message); } -void logPrint(Object message) { +void logPrint(String? message) { _logger.log(printLevel, message); } diff --git a/lib/src/model/accessor.dart b/lib/src/model/accessor.dart index 8fe507ba71..cfa80af228 100644 --- a/lib/src/model/accessor.dart +++ b/lib/src/model/accessor.dart @@ -2,12 +2,13 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/source/line_info.dart'; // ignore: implementation_imports import 'package:analyzer/src/dart/element/member.dart' show ExecutableMember; +import 'package:collection/collection.dart' show IterableExtension; import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -17,57 +18,59 @@ import 'package:dartdoc/src/warnings.dart'; /// Getters and setters. class Accessor extends ModelElement implements EnclosedElement { - GetterSetterCombo enclosingCombo; + /// The combo ([Field] or [TopLevelVariable] containing this accessor. + /// Initialized by the combo's constructor. + late final GetterSetterCombo enclosingCombo; - Accessor(PropertyAccessorElement element, Library library, + Accessor(PropertyAccessorElement? element, Library? library, PackageGraph packageGraph, - [ExecutableMember /*?*/ originalMember]) + [ExecutableMember? originalMember]) : super(element, library, packageGraph, originalMember); @override - CharacterLocation get characterLocation { - if (element.nameOffset < 0) { - assert(element.isSynthetic, 'Invalid offset for non-synthetic element'); + CharacterLocation? get characterLocation { + if (element!.nameOffset < 0) { + assert(element!.isSynthetic, 'Invalid offset for non-synthetic element'); // TODO(jcollins-g): switch to [element.nonSynthetic] after analyzer 1.8 - return enclosingCombo.characterLocation; + return enclosingCombo!.characterLocation; } return super.characterLocation; } @override - PropertyAccessorElement get element => super.element; + PropertyAccessorElement? get element => super.element as PropertyAccessorElement?; @override - ExecutableMember get originalMember => super.originalMember; + ExecutableMember? get originalMember => super.originalMember as ExecutableMember?; - Callable _modelType; - Callable get modelType => _modelType ??= - modelBuilder.typeFrom((originalMember ?? element).type, library); + Callable? _modelType; + Callable get modelType => (_modelType ??= + modelBuilder.typeFrom((originalMember ?? element)!.type, library!) as Callable?)!; - bool get isSynthetic => element.isSynthetic; + bool get isSynthetic => element!.isSynthetic; SourceCodeRenderer get _sourceCodeRenderer => packageGraph.rendererFactory.sourceCodeRenderer; - GetterSetterCombo _definingCombo; + GetterSetterCombo? _definingCombo; // The [enclosingCombo] where this element was defined. - GetterSetterCombo get definingCombo { + GetterSetterCombo? get definingCombo { if (_definingCombo == null) { - var variable = element.variable; - _definingCombo = modelBuilder.fromElement(variable); + var variable = element!.variable; + _definingCombo = modelBuilder.fromElement(variable) as GetterSetterCombo?; assert(_definingCombo != null, 'Unable to find defining combo'); } return _definingCombo; } - String _sourceCode; + String? _sourceCode; @override - String get sourceCode { + String? get sourceCode { if (_sourceCode == null) { if (isSynthetic) { _sourceCode = _sourceCodeRenderer.renderSourceCode( - packageGraph.getModelNodeFor(definingCombo.element).sourceCode); + packageGraph.getModelNodeFor(definingCombo!.element)!.sourceCode!); } else { _sourceCode = super.sourceCode; } @@ -76,10 +79,10 @@ class Accessor extends ModelElement implements EnclosedElement { } bool _documentationCommentComputed = false; - String _documentationComment; + String? _documentationComment; @override String get documentationComment => _documentationCommentComputed - ? _documentationComment + ? _documentationComment! : _documentationComment ??= () { _documentationCommentComputed = true; if (isSynthetic) { @@ -88,33 +91,30 @@ class Accessor extends ModelElement implements EnclosedElement { return stripComments(super.documentationComment); }(); - String /*!*/ __syntheticDocumentationComment; - /// Build a documentation comment for this accessor assuming it is synthetic. /// Value here is not useful if [isSynthetic] is false. - String /*!*/ get _syntheticDocumentationComment => - __syntheticDocumentationComment ??= () { + late final String _syntheticDocumentationComment = () { if (_hasSyntheticDocumentationComment) { - return definingCombo.documentationComment ?? ''; + return definingCombo!.documentationComment ?? ''; } return ''; - }(); + } (); /// If this is a getter, assume we want synthetic documentation. /// If the definingCombo has a nodoc tag, we want synthetic documentation /// for a synthetic accessor just in case it is inherited somewhere /// down the line due to split inheritance. bool get _hasSyntheticDocumentationComment => - (isGetter || definingCombo.hasNodoc || _comboDocsAreIndependent()) && - definingCombo.hasDocumentationComment; + (isGetter || definingCombo!.hasNodoc! || _comboDocsAreIndependent()) && + definingCombo!.hasDocumentationComment; // If we're a setter, and a getter exists, do not add synthetic // documentation if the combo's documentation is actually derived // from that getter. bool _comboDocsAreIndependent() { - if (isSetter && definingCombo.hasGetter) { - if (definingCombo.getter.isSynthetic || - !definingCombo.documentationFrom.contains(this)) { + if (isSetter && definingCombo!.hasGetter) { + if (definingCombo!.getter!.isSynthetic || + !definingCombo!.documentationFrom!.contains(this)) { return true; } } @@ -124,54 +124,54 @@ class Accessor extends ModelElement implements EnclosedElement { @override bool get hasDocumentationComment => isSynthetic ? _hasSyntheticDocumentationComment - : element.documentationComment != null; + : element!.documentationComment != null; @override void warn( PackageWarning kind, { - String message, + String? message, Iterable referredFrom = const [], Iterable extendedDebug = const [], }) { - enclosingCombo.warn(kind, + enclosingCombo!.warn(kind, message: message, referredFrom: referredFrom, extendedDebug: extendedDebug); } @override - ModelElement get enclosingElement { - if (element.enclosingElement is CompilationUnitElement) { + ModelElement? get enclosingElement { + if (element!.enclosingElement is CompilationUnitElement) { return modelBuilder - .fromElement(element.enclosingElement.enclosingElement); + .fromElement(element!.enclosingElement.enclosingElement!); } - return modelBuilder.from(element.enclosingElement, library); + return modelBuilder.from(element!.enclosingElement, library!); } @override - String get filePath => enclosingCombo.filePath; + String? get filePath => enclosingCombo!.filePath; @override - bool get isCanonical => enclosingCombo.isCanonical; + bool get isCanonical => enclosingCombo!.isCanonical; @override - String get href { - return enclosingCombo.href; + String? get href { + return enclosingCombo!.href; } - bool get isGetter => element.isGetter; + bool get isGetter => element!.isGetter; - bool get isSetter => element.isSetter; + bool get isSetter => element!.isSetter; @override String get kind => 'accessor'; - String _namePart; + String? _namePart; @override - String get namePart { - _namePart ??= super.namePart.split('=').first; + String? get namePart { + _namePart ??= super.namePart!.split('=').first; return _namePart; } @@ -180,63 +180,44 @@ class Accessor extends ModelElement implements EnclosedElement { /// Accessors should never be participating directly in comment reference /// lookups. Map get referenceChildren => - enclosingCombo.referenceChildren; + enclosingCombo!.referenceChildren; @override /// Accessors should never be participating directly in comment reference /// lookups. Iterable get referenceParents => - enclosingCombo.referenceParents; + enclosingCombo!.referenceParents; } /// A getter or setter that is a member of a [Container]. class ContainerAccessor extends Accessor with ContainerMember, Inheritable { - /// Factory will return an [ContainerAccessor] with isInherited = true - /// if [element] is in [inheritedAccessors]. - factory ContainerAccessor.from( - PropertyAccessorElement element, - Set inheritedAccessors, - Container enclosingContainer) { - ContainerAccessor accessor; - if (element == null) return null; - if (inheritedAccessors.contains(element)) { - accessor = enclosingContainer.packageGraph.modelBuilder.from( - element, enclosingContainer.library, - enclosingContainer: enclosingContainer); - } else { - accessor = enclosingContainer.packageGraph.modelBuilder - .from(element, enclosingContainer.library); - } - return accessor; - } - /// The index and values fields are never declared, and must be special cased. bool get _isEnumSynthetic => enclosingCombo is EnumField && (name == 'index' || name == 'values'); @override - CharacterLocation get characterLocation { - if (_isEnumSynthetic) return enclosingElement.characterLocation; + CharacterLocation? get characterLocation { + if (_isEnumSynthetic) return enclosingElement!.characterLocation; // TODO(jcollins-g): Remove the enclosingCombo case below once // https://github.com/dart-lang/sdk/issues/46154 is fixed. - if (enclosingCombo is EnumField) return enclosingCombo.characterLocation; + if (enclosingCombo is EnumField) return enclosingCombo!.characterLocation; return super.characterLocation; } - ModelElement _enclosingElement; + ModelElement? _enclosingElement; bool _isInherited = false; @override - bool get isCovariant => isSetter && parameters.first.isCovariant; + bool get isCovariant => isSetter && parameters!.first.isCovariant; - ContainerAccessor(PropertyAccessorElement element, Library library, + ContainerAccessor(PropertyAccessorElement? element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); - ContainerAccessor.inherited(PropertyAccessorElement element, Library library, + ContainerAccessor.inherited(PropertyAccessorElement element, Library? library, PackageGraph packageGraph, this._enclosingElement, - {ExecutableMember originalMember}) + {ExecutableMember? originalMember}) : super(element, library, packageGraph, originalMember) { _isInherited = true; } @@ -245,35 +226,34 @@ class ContainerAccessor extends Accessor with ContainerMember, Inheritable { bool get isInherited => _isInherited; @override - Container get enclosingElement { + Container? get enclosingElement { _enclosingElement ??= super.enclosingElement; - return _enclosingElement; + return _enclosingElement as Container?; } bool _overriddenElementIsSet = false; - ModelElement _overriddenElement; + ModelElement? _overriddenElement; @override - ContainerAccessor get overriddenElement { + ContainerAccessor? get overriddenElement { assert(packageGraph.allLibrariesAdded); if (!_overriddenElementIsSet) { _overriddenElementIsSet = true; - var parent = element.enclosingElement; + var parent = element!.enclosingElement; if (parent is ClassElement) { for (var t in parent.allSupertypes) { - Element accessor = - isGetter ? t.getGetter(element.name) : t.getSetter(element.name); + Element? accessor = + isGetter ? t.getGetter(element!.name) : t.getSetter(element!.name); if (accessor != null) { accessor = accessor.declaration; InheritingContainer parentContainer = - modelBuilder.fromElement(t.element); + modelBuilder.fromElement(t.element) as InheritingContainer; var possibleFields = []; possibleFields.addAll(parentContainer.instanceFields); possibleFields.addAll(parentContainer.staticFields); - var fieldName = accessor.name.replaceFirst('=', ''); - var foundField = possibleFields.firstWhere( - (f) => f.element.name == fieldName, - orElse: () => null); + var fieldName = accessor!.name!.replaceFirst('=', ''); + var foundField = possibleFields.firstWhereOrNull( + (f) => f.element!.name == fieldName); if (foundField != null) { if (isGetter) { _overriddenElement = foundField.getter; @@ -287,6 +267,6 @@ class ContainerAccessor extends Accessor with ContainerMember, Inheritable { } } } - return _overriddenElement; + return _overriddenElement as ContainerAccessor?; } } diff --git a/lib/src/model/annotation.dart b/lib/src/model/annotation.dart index cc0bb678f0..161b6905e0 100644 --- a/lib/src/model/annotation.dart +++ b/lib/src/model/annotation.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; @@ -16,31 +16,31 @@ import 'package:dartdoc/src/model/package_graph.dart'; /// `@`. class Annotation extends Feature with ModelBuilder { final ElementAnnotation annotation; - final Library library; + final Library? library; @override final PackageGraph packageGraph; Annotation(this.annotation, this.library, this.packageGraph) - : super(annotation.element.name); + : super(annotation.element!.name); - String _linkedNameWithParameters; + String? _linkedNameWithParameters; @override String get linkedNameWithParameters => _linkedNameWithParameters ??= packageGraph.rendererFactory.featureRenderer.renderAnnotation(this); /// Return the linked name of the annotation. @override - String get linkedName => annotation.element is PropertyAccessorElement - ? modelBuilder.fromElement(annotation.element).linkedName + String? get linkedName => annotation.element is PropertyAccessorElement + ? modelBuilder.fromElement(annotation.element!).linkedName // TODO(jcollins-g): consider linking to constructor instead of type? - : modelType.linkedName; + : modelType!.linkedName; - ElementType _modelType; - ElementType get modelType { + ElementType? _modelType; + ElementType? get modelType { if (_modelType == null) { var annotatedWith = annotation.element; if (annotatedWith is ConstructorElement) { - _modelType = modelBuilder.typeFrom(annotatedWith.returnType, library); + _modelType = modelBuilder.typeFrom(annotatedWith.returnType, library!); } else if (annotatedWith is PropertyAccessorElement) { _modelType = (modelBuilder.fromElement(annotatedWith.variable) as GetterSetterCombo) @@ -53,8 +53,8 @@ class Annotation extends Feature with ModelBuilder { return _modelType; } - String _parameterText; - String get parameterText { + String? _parameterText; + String? get parameterText { // TODO(srawlins): Attempt to revive constructor arguments in an annotation, // akin to source_gen's Reviver, in order to link to inner components. For // example, in `@Foo(const Bar(), baz: [Baz.one, Baz.two])`, link to @@ -70,7 +70,7 @@ class Annotation extends Feature with ModelBuilder { @override bool get isPublic => - modelType.isPublic && + modelType!.isPublic! && modelType is DefinedElementType && !packageGraph.invisibleAnnotations .contains((modelType as DefinedElementType).modelElement); diff --git a/lib/src/model/canonicalization.dart b/lib/src/model/canonicalization.dart index 152db508ec..93b32c38f0 100644 --- a/lib/src/model/canonicalization.dart +++ b/lib/src/model/canonicalization.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/comment_references/model_comment_reference.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -11,7 +11,7 @@ import 'package:dartdoc/src/model/model.dart'; abstract class Canonicalization implements Locatable, Documentable { bool get isCanonical; - Library get canonicalLibrary; + Library? get canonicalLibrary; /// A map of [ModelCommentReference.codeRef] to [ModelCommentReference]. /// This map deduplicates comment references as all identical reference @@ -44,25 +44,25 @@ abstract class Canonicalization implements Locatable, Documentable { // Penalty for deprecated libraries. if (lib.isDeprecated) scoredCandidate._alterScore(-1.0, 'is deprecated'); // Give a big boost if the library has the package name embedded in it. - if (lib.package.namePieces.intersection(lib.namePieces).isEmpty) { + if (lib.package.namePieces!.intersection(lib.namePieces!).isEmpty) { scoredCandidate._alterScore(1.0, 'embeds package name'); } // Give a tiny boost for libraries with long names, assuming they're // more specific (and therefore more likely to be the owner of this symbol). - scoredCandidate._alterScore(.01 * lib.namePieces.length, 'name is long'); + scoredCandidate._alterScore(.01 * lib.namePieces!.length, 'name is long'); // If we don't know the location of this element, return our best guess. // TODO(jcollins-g): is that even possible? assert(locationPieces.isNotEmpty); if (locationPieces.isEmpty) return scoredCandidate; // The more pieces we have of the location in our library name, the more we should boost our score. scoredCandidate._alterScore( - lib.namePieces.intersection(locationPieces).length.toDouble() / + lib.namePieces!.intersection(locationPieces).length.toDouble() / locationPieces.length.toDouble(), 'element location shares parts with name'); // If pieces of location at least start with elements of our library name, boost the score a little bit. var scoreBoost = 0.0; for (var piece in resplit(locationPieces)) { - for (var namePiece in lib.namePieces) { + for (var namePiece in lib.namePieces!) { if (piece.startsWith(namePiece)) { scoreBoost += 0.001; } diff --git a/lib/src/model/categorization.dart b/lib/src/model/categorization.dart index 08c190a120..2861fe092b 100644 --- a/lib/src/model/categorization.dart +++ b/lib/src/model/categorization.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/model/model.dart'; @@ -13,7 +13,7 @@ final RegExp _categoryRegExp = RegExp( /// Mixin implementing dartdoc categorization for ModelElements. abstract class Categorization implements ModelElement { @override - String buildDocumentationAddition(String rawDocs) => + String buildDocumentationAddition(String? rawDocs) => _stripAndSetDartdocCategories(rawDocs ??= ''); /// Parse `{@category ...}` and related information in API comments, stripping @@ -29,16 +29,16 @@ abstract class Categorization implements ModelElement { switch (match[1]) { case 'category': case 'api': - categorySet.add(match[2].trim()); + categorySet.add(match[2]!.trim()); break; case 'subCategory': - subCategorySet.add(match[2].trim()); + subCategorySet.add(match[2]!.trim()); break; case 'image': - _image = match[2].trim(); + _image = match[2]!.trim(); break; case 'samples': - _samples = match[2].trim(); + _samples = match[2]!.trim(); break; } return ''; @@ -51,57 +51,56 @@ abstract class Categorization implements ModelElement { return rawDocs; } - bool get hasSubCategoryNames => subCategoryNames.isNotEmpty; - List _subCategoryNames; + bool get hasSubCategoryNames => subCategoryNames!.isNotEmpty; + List? _subCategoryNames; /// Either a set of strings containing all declared subcategories for this symbol, /// or a set containing Null if none were declared. - List get subCategoryNames { + List? get subCategoryNames { // TODO(jcollins-g): avoid side-effect dependency if (_subCategoryNames == null) documentationLocal; return _subCategoryNames; } @override - bool get hasCategoryNames => categoryNames.isNotEmpty; - List _categoryNames; + bool get hasCategoryNames => categoryNames!.isNotEmpty; + List? _categoryNames; /// Either a set of strings containing all declared categories for this symbol, /// or a set containing Null if none were declared. - List get categoryNames { + List? get categoryNames { // TODO(jcollins-g): avoid side-effect dependency if (_categoryNames == null) documentationLocal; return _categoryNames; } - bool get hasImage => image.isNotEmpty; - String _image; + bool get hasImage => image!.isNotEmpty; + String? _image; /// Either a URI to a defined image, or the empty string if none /// was declared. - String get image { + String? get image { // TODO(jcollins-g): avoid side-effect dependency if (_image == null) documentationLocal; return _image; } - bool get hasSamples => samples.isNotEmpty; - String _samples; + bool get hasSamples => samples!.isNotEmpty; + String? _samples; /// Either a URI to documentation with samples, or the empty string if none /// was declared. - String get samples { + String? get samples { // TODO(jcollins-g): avoid side-effect dependency if (_samples == null) documentationLocal; return _samples; } - bool _hasCategorization; - Iterable _categories; + Iterable? _categories; - Iterable get categories { - _categories ??= categoryNames + Iterable? get categories { + _categories ??= categoryNames! .map((n) => package.nameToCategory[n]) .where((c) => c != null) .toList() @@ -110,15 +109,16 @@ abstract class Categorization implements ModelElement { } @override - Iterable get displayedCategories { - if (config.showUndocumentedCategories) return categories; - return categories.where((c) => c.isDocumented); + Iterable? get displayedCategories { + if (config!.showUndocumentedCategories) return categories; + return categories!.where((c) => c!.isDocumented); } + bool? _hasCategorization; /// True if categories, subcategories, a documentation icon, or samples were /// declared. - bool get hasCategorization { + late final bool hasCategorization = () { if (_hasCategorization == null) documentationLocal; - return _hasCategorization; - } + return _hasCategorization!; + } (); } diff --git a/lib/src/model/class.dart b/lib/src/model/class.dart index 41cff0ff9b..b745783a13 100644 --- a/lib/src/model/class.dart +++ b/lib/src/model/class.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -18,17 +18,17 @@ import 'comment_referable.dart'; /// **inherited**: Filtered getters giving only inherited children. class Class extends InheritingContainer with Constructable, TypeImplementing, MixedInTypes { - Class(ClassElement element, Library library, PackageGraph packageGraph) + Class(ClassElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph) { packageGraph.specialClasses.addSpecial(this); } - List _allModelElements; + List? _allModelElements; @override - List get allModelElements { + List? get allModelElements { _allModelElements ??= [ - ...super.allModelElements, + ...super.allModelElements!, ...constructors, ]; return _allModelElements; @@ -36,13 +36,13 @@ class Class extends InheritingContainer /// Returns the library that encloses this element. @override - ModelElement get enclosingElement => library; + ModelElement? get enclosingElement => library; @override String get fileName => '$name-class.$fileType'; @override - String get filePath => '${library.dirName}/$fileName'; + String get filePath => '${library!.dirName}/$fileName'; @override String get fullkind { @@ -51,7 +51,7 @@ class Class extends InheritingContainer } @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -60,10 +60,10 @@ class Class extends InheritingContainer return '${package.baseHref}$filePath'; } - bool get isAbstract => element.isAbstract; + bool get isAbstract => element!.isAbstract; @override - bool get isCanonical => super.isCanonical && isPublic; + bool get isCanonical => super.isCanonical && isPublic!; bool get isErrorOrException { bool _doCheck(ClassElement element) { @@ -72,15 +72,15 @@ class Class extends InheritingContainer } // if this class is itself Error or Exception, return true - if (_doCheck(element)) return true; + if (_doCheck(element!)) return true; - return element.allSupertypes.map((t) => t.element).any(_doCheck); + return element!.allSupertypes.map((t) => t.element).any(_doCheck); } @override String get kind => 'class'; - List _inheritanceChain; + List? _inheritanceChain; /// Not the same as superChain as it may include mixins. /// It's really not even the same as ordinary Dart inheritance, either, @@ -88,42 +88,42 @@ class Class extends InheritingContainer /// to include them in the set of things we might link to for documentation /// purposes in abstract classes. @override - List get inheritanceChain { + List get inheritanceChain { if (_inheritanceChain == null) { _inheritanceChain = []; - _inheritanceChain.add(this); + _inheritanceChain!.add(this); /// Caching should make this recursion a little less painful. for (var c in mixedInTypes.reversed .map((e) => (e.modelElement as InheritingContainer))) { - _inheritanceChain.addAll(c.inheritanceChain); + _inheritanceChain!.addAll(c.inheritanceChain); } for (var c in superChain.map((e) => (e.modelElement as InheritingContainer))) { - _inheritanceChain.addAll(c.inheritanceChain); + _inheritanceChain!.addAll(c.inheritanceChain); } /// Interfaces need to come last, because classes in the superChain might /// implement them even when they aren't mentioned. - _inheritanceChain.addAll(interfaces.expand( + _inheritanceChain!.addAll(interfaces.expand( (e) => (e.modelElement as InheritingContainer).inheritanceChain)); } - return _inheritanceChain.toList(growable: false); + return _inheritanceChain!.toList(growable: false); } - Iterable _instanceFields; + Iterable? _instanceFields; @override Iterable get instanceFields => - _instanceFields ??= allFields.where((f) => !f.isStatic); + _instanceFields ??= allFields!.where((f) => !f.isStatic); @override bool get publicInheritedInstanceFields => publicInstanceFields.every((f) => f.isInherited); @override - Iterable get constantFields => allFields.where((f) => f.isConst); + Iterable get constantFields => allFields!.where((f) => f.isConst); static Iterable> _constructorGenerator( Iterable source) sync* { diff --git a/lib/src/model/comment_referable.dart b/lib/src/model/comment_referable.dart index 7c3f022b04..cbcf0d5ad1 100644 --- a/lib/src/model/comment_referable.dart +++ b/lib/src/model/comment_referable.dart @@ -226,7 +226,6 @@ mixin CommentReferable implements Nameable, ModelBuilderInterface { Library? get library => null; @internal - /// For testing / comparison only, get the comment referable from where this /// [ElementType] was defined. Override where an [Element] is available. CommentReferable get definingCommentReferable => this; diff --git a/lib/src/model/constructor.dart b/lib/src/model/constructor.dart index a46b2ec78f..b65c5b7fc5 100644 --- a/lib/src/model/constructor.dart +++ b/lib/src/model/constructor.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/source/line_info.dart'; @@ -14,12 +14,12 @@ class Constructor extends ModelElement with TypeParameters, ContainerMember implements EnclosedElement { Constructor( - ConstructorElement element, Library library, PackageGraph packageGraph) + ConstructorElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); @override - CharacterLocation get characterLocation { - if (element.isSynthetic) { + CharacterLocation? get characterLocation { + if (element!.isSynthetic) { // Make warnings for a synthetic constructor refer to somewhere reasonable // since a synthetic constructor has no definition independent of the // parent class. @@ -29,20 +29,20 @@ class Constructor extends ModelElement } @override - ConstructorElement get element => super.element; + ConstructorElement? get element => super.element as ConstructorElement?; @override // TODO(jcollins-g): Revisit this when dart-lang/sdk#31517 is implemented. - List get typeParameters => + List? get typeParameters => (enclosingElement as Class).typeParameters; @override ModelElement get enclosingElement => - modelBuilder.from(element.enclosingElement, library); + modelBuilder.from(element!.enclosingElement, library!); @override String get filePath => - '${enclosingElement.library.dirName}/${enclosingElement.name}/$fileName'; + '${enclosingElement.library!.dirName}/${enclosingElement.name}/$fileName'; String get fullKind { if (isConst) return 'const $kind'; @@ -53,11 +53,11 @@ class Constructor extends ModelElement @override String get fullyQualifiedName { if (isUnnamedConstructor) return super.fullyQualifiedName; - return '${library.name}.$name'; + return '${library!.name}.$name'; } @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -67,82 +67,71 @@ class Constructor extends ModelElement } @override - bool get isConst => element.isConst; + bool get isConst => element!.isConst; bool get isUnnamedConstructor => name == enclosingElement.name; bool get isDefaultConstructor => name == '${enclosingElement.name}.new' || isUnnamedConstructor; - bool get isFactory => element.isFactory; + bool get isFactory => element!.isFactory; @override String get kind => 'constructor'; - Callable _modelType; + Callable? _modelType; Callable get modelType => - _modelType ??= modelBuilder.typeFrom(element.type, library); - - String _name; + (_modelType ??= modelBuilder.typeFrom(element!.type, library!) as Callable?)!; @override - String get name { - if (_name == null) { - // TODO(jcollins-g): After the old lookup code is retired, rationalize - // [name] around the conventions used in referenceChildren and replace - // code there and elsewhere with simple references to the name. - var constructorName = element.name; - if (constructorName.isEmpty) { - _name = enclosingElement.name; - } else { - _name = '${enclosingElement.name}.$constructorName'; - } + late final String name = () { + // TODO(jcollins-g): After the old lookup code is retired, rationalize + // [name] around the conventions used in referenceChildren and replace + // code there and elsewhere with simple references to the name. + var constructorName = element!.name; + if (constructorName.isEmpty) { + return enclosingElement.name; } - return _name; - } + return '${enclosingElement.name}.$constructorName'; + } (); - String _nameWithGenerics; @override - String get nameWithGenerics { - if (_nameWithGenerics == null) { - var constructorName = element.name; + late final String nameWithGenerics = () { + var constructorName = element!.name; if (constructorName.isEmpty) { - _nameWithGenerics = '${enclosingElement.name}$genericParameters'; - } else { - _nameWithGenerics = - '${enclosingElement.name}$genericParameters.$constructorName'; + return '${enclosingElement.name}$genericParameters'; } - } - return _nameWithGenerics; - } + return + '${enclosingElement.name}$genericParameters.$constructorName'; + } (); - String get shortName { - if (name.contains('.')) { - return name.substring(element.enclosingElement.name.length + 1); + String? get shortName { + if (name!.contains('.')) { + return name!.substring(element!.enclosingElement.name.length + 1); } else { return name; } } - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; - _referenceChildren.addEntries(allParameters.map((param) { + _referenceChildren!.addEntries(allParameters!.map((param) { var paramElement = param.element; if (paramElement is FieldFormalParameterElement) { - return modelBuilder.fromElement(paramElement.field); + return modelBuilder.fromElement(paramElement.field!); } return param; }).generateEntries()); - _referenceChildren.addEntries(typeParameters.generateEntries()); + _referenceChildren!.addEntries(typeParameters!.generateEntries()); } - return _referenceChildren; + return _referenceChildren!; } @override String get referenceName => - isUnnamedConstructor ? enclosingElement.name : element.name; + isUnnamedConstructor ? enclosingElement.name! : element!.name; } diff --git a/lib/src/model/container.dart b/lib/src/model/container.dart index f4ae78af47..6bc1ecac03 100644 --- a/lib/src/model/container.dart +++ b/lib/src/model/container.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/scope.dart'; @@ -33,12 +33,12 @@ import 'package:meta/meta.dart'; /// **all** : Referring to all children. abstract class Container extends ModelElement with Categorization, TypeParameters { - Container(Element element, Library library, PackageGraph packageGraph) + Container(Element element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); // TODO(jcollins-g): Implement a ContainerScope that flattens supertypes? @override - Scope get scope => null; + Scope? get scope => null; @override bool get hasParameters => false; @@ -58,29 +58,29 @@ abstract class Container extends ModelElement element is ClassElement && (element as ClassElement).isMixin; @mustCallSuper - Iterable get allModelElements => quiver.concat([ + Iterable? get allModelElements => quiver.concat([ instanceMethods, instanceFields, - instanceOperators, + instanceOperators!, instanceAccessors, staticFields, staticAccessors, staticMethods, ]); - List _allCanonicalModelElements; + List? _allCanonicalModelElements; List get allCanonicalModelElements { return (_allCanonicalModelElements ??= - allModelElements.where((e) => e.isCanonical).toList()); + allModelElements!.where((e) => e.isCanonical).toList()); } /// All methods, including operators and statics, declared as part of this /// [Container]. [declaredMethods] must be the union of [instanceMethods], /// [staticMethods], and [instanceOperators]. - Iterable get declaredMethods; + Iterable? get declaredMethods; - Iterable get instanceMethods => declaredMethods + Iterable get instanceMethods => declaredMethods! .where((m) => !m.isStatic && !m.isOperator) .toList(growable: false); @@ -105,21 +105,17 @@ abstract class Container extends ModelElement Iterable get publicInstanceMethods => model_utils.filterNonPublic(instanceMethods); - List _publicInstanceMethodsSorted; + List? _publicInstanceMethodsSorted; List get publicInstanceMethodsSorted => _publicInstanceMethodsSorted ?? publicInstanceMethods.toList() ..sort(byName); - Iterable _declaredOperators; @nonVirtual - Iterable get declaredOperators { - _declaredOperators ??= - declaredMethods.whereType().toList(growable: false); - return _declaredOperators; - } + late final Iterable declaredOperators = + declaredMethods!.whereType().toList(growable: false); @override - ModelElement get enclosingElement; + ModelElement? get enclosingElement; Iterable get instanceOperators => declaredOperators; @@ -129,19 +125,19 @@ abstract class Container extends ModelElement @nonVirtual Iterable get publicInstanceOperators => - model_utils.filterNonPublic(instanceOperators); + model_utils.filterNonPublic(instanceOperators!); - List _publicInstanceOperatorsSorted; + List? _publicInstanceOperatorsSorted; List get publicInstanceOperatorsSorted => _publicInstanceOperatorsSorted ??= publicInstanceOperators.toList() ..sort(byName); /// Fields fully declared in this [Container]. - Iterable get declaredFields; + Iterable? get declaredFields; /// All fields accessible in this instance that are not static. Iterable get instanceFields => - declaredFields.where((f) => !f.isStatic); + declaredFields!.where((f) => !f.isStatic); bool get hasInstanceFields => instanceFields.isNotEmpty; @@ -152,18 +148,18 @@ abstract class Container extends ModelElement @nonVirtual bool get hasPublicInstanceFields => publicInstanceFields.isNotEmpty; - List _publicInstanceFieldsSorted; + List? _publicInstanceFieldsSorted; List get publicInstanceFieldsSorted => _publicInstanceFieldsSorted ??= publicInstanceFields.toList()..sort(byName); - Iterable get constantFields => declaredFields.where((f) => f.isConst); + Iterable get constantFields => declaredFields!.where((f) => f.isConst); Iterable get publicConstantFields => model_utils.filterNonPublic(constantFields); bool get hasPublicConstantFields => publicConstantFieldsSorted.isNotEmpty; - List _publicConstantFieldsSorted; + List? _publicConstantFieldsSorted; List get publicConstantFieldsSorted => _publicConstantFieldsSorted ??= publicConstantFields.toList()..sort(byName); @@ -175,13 +171,13 @@ abstract class Container extends ModelElement /// This container might be canonical for elements it does not contain. /// See [Inheritable.canonicalEnclosingContainer]. - bool containsElement(Element element) => allElements.contains(element); + bool containsElement(Element? element) => allElements.contains(element); - Set _allElements; - Set get allElements => - _allElements ??= allModelElements.map((e) => e.element).toSet(); + Set? _allElements; + Set get allElements => + _allElements ??= allModelElements!.map((e) => e.element).toSet(); - Map> _membersByName; + Map>? _membersByName; /// Given a ModelElement that is a member of some other class, return /// the member of this class that has the same name and runtime type. @@ -191,18 +187,18 @@ abstract class Container extends ModelElement T memberByExample(T example) { if (_membersByName == null) { _membersByName = {}; - for (var me in allModelElements) { - if (!_membersByName.containsKey(me.name)) { - _membersByName[me.name] = []; + for (var me in allModelElements!) { + if (!_membersByName!.containsKey(me.name)) { + _membersByName![me.name] = []; } - _membersByName[me.name].add(me); + _membersByName![me.name]!.add(me); } } ModelElement member; // [T] is insufficiently specific to disambiguate between different // subtypes of [Inheritable] or other mixins/implementations of // [ModelElement] via [Iterable.whereType]. - var possibleMembers = _membersByName[example.name] + var possibleMembers = _membersByName![example.name]! .where((e) => e.runtimeType == example.runtimeType); if (example is Accessor) { possibleMembers = possibleMembers @@ -210,7 +206,7 @@ abstract class Container extends ModelElement } member = possibleMembers.first; assert(possibleMembers.length == 1); - return member; + return member as T; } bool get hasPublicStaticFields => publicStaticFieldsSorted.isNotEmpty; @@ -218,11 +214,11 @@ abstract class Container extends ModelElement Iterable get publicStaticFields => model_utils.filterNonPublic(staticFields); - List _publicStaticFieldsSorted; + List? _publicStaticFieldsSorted; List get publicStaticFieldsSorted => _publicStaticFieldsSorted ??= publicStaticFields.toList()..sort(byName); - Iterable get staticFields => declaredFields.where((f) => f.isStatic); + Iterable get staticFields => declaredFields!.where((f) => f.isStatic); Iterable get variableStaticFields => staticFields.where((f) => !f.isConst); @@ -233,13 +229,13 @@ abstract class Container extends ModelElement Iterable get publicVariableStaticFields => model_utils.filterNonPublic(variableStaticFields); - List _publicVariableStaticFieldsSorted; + List? _publicVariableStaticFieldsSorted; List get publicVariableStaticFieldsSorted => _publicVariableStaticFieldsSorted ??= publicVariableStaticFields.toList() ..sort(byName); Iterable get staticMethods => - declaredMethods.where((m) => m.isStatic); + declaredMethods!.where((m) => m.isStatic); bool get hasPublicStaticMethods => model_utils.filterNonPublic(publicStaticMethodsSorted).isNotEmpty; @@ -247,7 +243,7 @@ abstract class Container extends ModelElement Iterable get publicStaticMethods => model_utils.filterNonPublic(staticMethods); - List _publicStaticMethodsSorted; + List? _publicStaticMethodsSorted; List get publicStaticMethodsSorted => _publicStaticMethodsSorted ??= publicStaticMethods.toList()..sort(byName); @@ -255,33 +251,33 @@ abstract class Container extends ModelElement /// parameter-global. Iterable> get extraReferenceChildren => []; - Map _referenceChildren; + Map? _referenceChildren; @override @mustCallSuper Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; - _referenceChildren.addEntries(allModelElements + _referenceChildren!.addEntries(allModelElements! .whereNotType() .whereNotType() .generateEntries()); - _referenceChildren.addEntriesIfAbsent(extraReferenceChildren); + _referenceChildren!.addEntriesIfAbsent(extraReferenceChildren); // Process unscoped parameters last to make sure they don't override // other options. - for (var modelElement in allModelElements) { + for (var modelElement in allModelElements!) { // Don't complain about references to parameter names, but prefer // referring to anything else. // TODO(jcollins-g): Figure out something good to do in the ecosystem // here to wean people off the habit of unscoped parameter references. if (modelElement.hasParameters) { - _referenceChildren - .addEntriesIfAbsent(modelElement.parameters.generateEntries()); + _referenceChildren! + .addEntriesIfAbsent(modelElement.parameters!.generateEntries()); } } - _referenceChildren['this'] = this; + _referenceChildren!['this'] = this; } - return _referenceChildren; + return _referenceChildren!; } @override diff --git a/lib/src/model/container_member.dart b/lib/src/model/container_member.dart index adf5e674ce..db00cfd08a 100644 --- a/lib/src/model/container_member.dart +++ b/lib/src/model/container_member.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/model/feature.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -20,11 +20,11 @@ mixin ContainerMember on ModelElement implements EnclosedElement { // implemented. bool get isExtended => false; - Container _definingEnclosingContainer; + Container? _definingEnclosingContainer; - Container get definingEnclosingContainer { + Container? get definingEnclosingContainer { _definingEnclosingContainer ??= - modelBuilder.fromElement(element.enclosingElement); + modelBuilder.fromElement(element!.enclosingElement!) as Container?; return _definingEnclosingContainer; } @@ -35,27 +35,27 @@ mixin ContainerMember on ModelElement implements EnclosedElement { }; bool _canonicalEnclosingContainerIsSet = false; - Container _canonicalEnclosingContainer; + Container? _canonicalEnclosingContainer; - Container get canonicalEnclosingContainer { + Container? get canonicalEnclosingContainer { if (!_canonicalEnclosingContainerIsSet) { _canonicalEnclosingContainer = computeCanonicalEnclosingContainer(); _canonicalEnclosingContainerIsSet = true; assert(_canonicalEnclosingContainer == null || - _canonicalEnclosingContainer.isDocumented); + _canonicalEnclosingContainer!.isDocumented); } return _canonicalEnclosingContainer; } - Container computeCanonicalEnclosingContainer() { + Container? computeCanonicalEnclosingContainer() { // TODO(jcollins-g): move Extension specific code to [Extendable] - if (enclosingElement is Extension && enclosingElement.isDocumented) { + if (enclosingElement is Extension && enclosingElement!.isDocumented) { return packageGraph - .findCanonicalModelElementFor(enclosingElement.element); + .findCanonicalModelElementFor(enclosingElement!.element) as Container?; } if (enclosingElement is! Extension) { return packageGraph - .findCanonicalModelElementFor(element.enclosingElement); + .findCanonicalModelElementFor(element!.enclosingElement) as Container?; } return null; } @@ -68,16 +68,16 @@ mixin ContainerMember on ModelElement implements EnclosedElement { // references are resolved wrt documentation inheritance, // that has to be resolved in the source by not inheriting // documentation. - [enclosingElement, documentationFrom.first.enclosingElement]; + [enclosingElement as Container, documentationFrom!.first.enclosingElement as Container]; @override Iterable get referenceGrandparentOverrides sync* { // TODO(jcollins-g): split Field documentation up between accessors // and resolve the pieces with different scopes. dart-lang/dartdoc#2693. // Until then, just pretend we're handling this correctly. - yield (documentationFrom.first as ModelElement).definingLibrary; + yield (documentationFrom!.first as ModelElement).definingLibrary; // TODO(jcollins-g): Wean users off of depending on canonical library // resolution. dart-lang/dartdoc#2696 - if (canonicalLibrary != null) yield canonicalLibrary; + if (canonicalLibrary != null) yield canonicalLibrary!; } } diff --git a/lib/src/model/documentable.dart b/lib/src/model/documentable.dart index dc773426b8..a81203259b 100644 --- a/lib/src/model/documentable.dart +++ b/lib/src/model/documentable.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/file_system/file_system.dart'; import 'package:dartdoc/src/dartdoc_options.dart'; @@ -13,15 +13,15 @@ import 'model.dart'; /// Bridges the gap between model elements and packages, /// both of which have documentation. abstract class Documentable extends Nameable { - String get documentation; + String? get documentation; - String get documentationAsHtml; + String? get documentationAsHtml; bool get hasDocumentation; bool get hasExtendedDocumentation; - String get oneLineDoc; + String? get oneLineDoc; PackageGraph get packageGraph; @@ -29,7 +29,7 @@ abstract class Documentable extends Nameable { DartdocOptionContext get config; - String get href; + String? get href; String get kind; } @@ -47,16 +47,16 @@ enum DocumentLocation { mixin MarkdownFileDocumentation implements Documentable, Canonicalization { DocumentLocation get documentedWhere; - Documentation __documentation; + Documentation? __documentation; - Documentation get _documentation { + Documentation? get _documentation { if (__documentation != null) return __documentation; __documentation = Documentation.forElement(this); return __documentation; } @override - String get documentationAsHtml => _documentation.asHtml; + String? get documentationAsHtml => _documentation!.asHtml; @override String get documentation { @@ -78,9 +78,9 @@ mixin MarkdownFileDocumentation implements Documentable, Canonicalization { bool get isDocumented; @override - String get oneLineDoc => __documentation.asOneLiner; + String? get oneLineDoc => __documentation!.asOneLiner; - File get documentationFile; + File? get documentationFile; @override String get location => '(${documentationFile.path})'; diff --git a/lib/src/model/documentation.dart b/lib/src/model/documentation.dart index 8830e78d2c..a50d9acee9 100644 --- a/lib/src/model/documentation.dart +++ b/lib/src/model/documentation.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/comment_references/model_comment_reference.dart'; import 'package:dartdoc/src/markdown_processor.dart'; @@ -15,18 +15,18 @@ class Documentation { Documentation.forElement(this._element); - bool _hasExtendedDocs; + bool? _hasExtendedDocs; - bool get hasExtendedDocs { + bool? get hasExtendedDocs { if (_hasExtendedDocs == null) { _renderDocumentation(_element.isCanonical && _asHtml == null); } return _hasExtendedDocs; } - String _asHtml; + String? _asHtml; - String get asHtml { + String? get asHtml { if (_asHtml == null) { assert(_asOneLiner == null || _element.isCanonical); _renderDocumentation(true); @@ -34,9 +34,9 @@ class Documentation { return _asHtml; } - String _asOneLiner; + String? _asOneLiner; - String get asOneLiner { + String? get asOneLiner { if (_asOneLiner == null) { assert(_asHtml == null); _renderDocumentation(_element.isCanonical); @@ -44,7 +44,7 @@ class Documentation { return _asOneLiner; } - Map get commentRefs => _element.commentRefs; + Map? get commentRefs => _element.commentRefs; void _renderDocumentation(bool processFullDocs) { var parseResult = _parseDocumentation(processFullDocs); @@ -70,8 +70,8 @@ class Documentation { if (text == null || text.isEmpty) { return DocumentationParseResult.empty; } - showWarningsForGenericsOutsideSquareBracketsBlocks(text, _element); - var document = MarkdownDocument.withElementLinkResolver(_element); + showWarningsForGenericsOutsideSquareBracketsBlocks(text, _element as Warnable); + var document = MarkdownDocument.withElementLinkResolver(_element as Warnable); return document.parseMarkdownText(text, processFullDocs); } diff --git a/lib/src/model/documentation_comment.dart b/lib/src/model/documentation_comment.dart index 1a7dea6bcc..f6f723262d 100644 --- a/lib/src/model/documentation_comment.dart +++ b/lib/src/model/documentation_comment.dart @@ -1,4 +1,4 @@ -// @dart=2.9 + import 'package:args/args.dart'; import 'package:crypto/crypto.dart' as crypto; @@ -41,7 +41,7 @@ final RegExp _needsPrecacheRegExp = RegExp(r'{@(template|tool|inject-html)'); /// entrypoints. mixin DocumentationComment on Documentable, Warnable, Locatable, SourceCodeMixin { - List _documentationFrom; + List? _documentationFrom; /// Returns the ModelElement(s) from which we will get documentation. /// Can be more than one if this is a Field composing documentation from @@ -51,46 +51,46 @@ mixin DocumentationComment /// to find docs, if the current class doesn't have docs /// for this element. @override - List get documentationFrom => + List? get documentationFrom => _documentationFrom ??= () { if (!hasDocumentationComment && this is Inheritable && (this as Inheritable).overriddenElement != null) { - return (this as Inheritable).overriddenElement.documentationFrom; + return (this as Inheritable).overriddenElement!.documentationFrom; } else if (this is Inheritable && (this as Inheritable).isInherited) { - var fromThis = modelBuilder.fromElement(element); + var fromThis = modelBuilder.fromElement(element!); return fromThis.documentationFrom; } else { return [this]; } }(); - String _documentationAsHtml; + String? _documentationAsHtml; @override - String get documentationAsHtml { + String? get documentationAsHtml { if (_documentationAsHtml != null) return _documentationAsHtml; _documentationAsHtml = _injectHtmlFragments(elementDocumentation.asHtml); return _documentationAsHtml; } - Documentation _elementDocumentation; + Documentation? _elementDocumentation; Documentation get elementDocumentation => _elementDocumentation ??= Documentation.forElement(this); - String /*!*/ get documentationComment; + String get documentationComment; /// True if [this] has a synthetic/inherited or local documentation /// comment. False otherwise. bool get hasDocumentationComment; /// Returns true if the raw documentation comment has a nodoc indication. - bool get hasNodoc { + bool? get hasNodoc { if (hasDocumentationComment && (documentationComment.contains('@nodoc') || documentationComment.contains(''))) { return true; } - return packageGraph.configSetsNodocFor(element.source.fullName); + return packageGraph.configSetsNodocFor(element!.source!.fullName); } /// Process a [documentationComment], performing various actions based on @@ -141,7 +141,7 @@ mixin DocumentationComment String get sourceFileName; - String get fullyQualifiedNameWithoutLibrary; + String? get fullyQualifiedNameWithoutLibrary; path.Context get pathContext; @@ -254,13 +254,13 @@ mixin DocumentationComment /// ## Content to send to tool. /// 2018-09-18T21:15+00:00 Future _evaluateTools(String rawDocs) async { - if (!config.allowTools) { + if (!config!.allowTools) { return rawDocs; } var invocationIndex = 0; return await _replaceAllMappedAsync(rawDocs, _basicToolPattern, (basicMatch) async { - var args = _splitUpQuotedArgs(basicMatch[1]).toList(); + var args = _splitUpQuotedArgs(basicMatch[1]!).toList(); // Tool name must come first. if (args.isEmpty) { warn(PackageWarning.toolError, @@ -270,15 +270,15 @@ mixin DocumentationComment // Count the number of invocations of tools in this dartdoc block, // so that tools can differentiate different blocks from each other. invocationIndex++; - return await config.tools.runner.run(args, content: basicMatch[2], + return await config!.tools.runner.run(args, content: basicMatch[2]!, toolErrorCallback: (String message) async { warn(PackageWarning.toolError, message: message); - }, environment: _toolsEnvironment(invocationIndex: invocationIndex)); + }, environment: _toolsEnvironment(invocationIndex: invocationIndex) as Map); }); } /// The environment variables to use when running a tool. - Map _toolsEnvironment({@required int invocationIndex}) { + Map _toolsEnvironment({required int invocationIndex}) { return { 'SOURCE_LINE': characterLocation?.lineNumber.toString(), 'SOURCE_COLUMN': characterLocation?.columnNumber.toString(), @@ -313,13 +313,13 @@ mixin DocumentationComment String _injectExamples(String rawdocs) { final dirPath = package.packageMeta.dir.path; return rawdocs.replaceAllMapped(_examplePattern, (match) { - var args = _getExampleArgs(match[1]); + var args = _getExampleArgs(match[1]!); if (args == null) { // Already warned about an invalid parameter if this happens. return ''; } var lang = args['lang'] ?? - pathContext.extension(args['src']).replaceFirst('.', ''); + pathContext.extension(args['src']!).replaceFirst('.', ''); var replacement = match[0]; // default to fully matched string. @@ -331,14 +331,14 @@ mixin DocumentationComment replacement = replacement.replaceFirst('```', '```$lang'); } } else { - var filePath = element.source.fullName.substring(dirPath.length + 1); + var filePath = element!.source!.fullName.substring(dirPath.length + 1); // TODO(srawlins): If a file exists at the location without the // appended 'md' extension, note this. warn(PackageWarning.missingExampleFile, message: '${fragmentFile.path}; path listed at $filePath'); } - return replacement; + return replacement!; }); } @@ -353,7 +353,7 @@ mixin DocumentationComment /// Returns a map of arguments. The first unnamed argument will have key /// 'src'. The computed file path, constructed from 'src' and 'region' will /// have key 'file'. - Map _getExampleArgs(String argsAsString) { + Map? _getExampleArgs(String argsAsString) { var results = _parseArgs(argsAsString, _exampleArgParser, 'example'); if (results == null) { return null; @@ -363,7 +363,7 @@ mixin DocumentationComment var src = results.rest.isEmpty ? '' : results.rest.first.replaceAll('/', pathContext.separator); - var args = { + var args = { 'src': src, 'lang': results['lang'], 'region': results['region'] ?? '', @@ -379,9 +379,9 @@ mixin DocumentationComment var ext = pathContext.extension(src); file = pathContext.join(dir, '$basename-$region$ext$fragExtension'); } - args['file'] = config.examplePathPrefix == null + args['file'] = config!.examplePathPrefix == null ? file - : pathContext.join(config.examplePathPrefix, file); + : pathContext.join(config!.examplePathPrefix, file); return args; } @@ -423,7 +423,7 @@ mixin DocumentationComment /// found in the address bar of the browser when viewing a YouTube video. String _injectYouTube(String rawDocs) { return rawDocs.replaceAllMapped(_basicYouTubePattern, (basicMatch) { - var args = _parseArgs(basicMatch[1], _youTubeArgParser, 'youtube'); + var args = _parseArgs(basicMatch[1]!, _youTubeArgParser, 'youtube'); if (args == null) { // Already warned about an invalid parameter if this happens. return ''; @@ -464,7 +464,7 @@ mixin DocumentationComment 'https://www.youtube.com/watch?v=oHg5SJYRHA0.'); return ''; } - var youTubeId = url.group(url.groupCount); + var youTubeId = url.group(url.groupCount)!; var aspectRatio = (height / width * 100).toStringAsFixed(2); return modelElementRenderer.renderYoutubeUrl(youTubeId, aspectRatio); @@ -510,7 +510,7 @@ mixin DocumentationComment var id = '$base$animationIdCount'; // We check for duplicate IDs so that we make sure not to collide with // user-supplied ids on the same page. - while (package.usedAnimationIdsByHref[href].contains(id)) { + while (package.usedAnimationIdsByHref[href]!.contains(id)) { animationIdCount++; id = '$base$animationIdCount'; } @@ -521,7 +521,7 @@ mixin DocumentationComment // Make sure we have a set to keep track of used IDs for this href. package.usedAnimationIdsByHref[href] ??= {}; - var args = _parseArgs(basicMatch[1], _animationArgParser, 'animation'); + var args = _parseArgs(basicMatch[1]!, _animationArgParser, 'animation'); if (args == null) { // Already warned about an invalid parameter if this happens. return ''; @@ -551,13 +551,13 @@ mixin DocumentationComment 'and must not begin with a number.'); return ''; } - if (package.usedAnimationIdsByHref[href].contains(uniqueId)) { + if (package.usedAnimationIdsByHref[href]!.contains(uniqueId)) { warn(PackageWarning.invalidParameter, message: 'An animation has a non-unique identifier, "$uniqueId". ' 'Animation identifiers must be unique.'); return ''; } - package.usedAnimationIdsByHref[href].add(uniqueId); + package.usedAnimationIdsByHref[href]!.add(uniqueId); int width; try { @@ -616,8 +616,8 @@ mixin DocumentationComment /// String _stripMacroTemplatesAndAddToIndex(String rawDocs) { return rawDocs.replaceAllMapped(_templatePattern, (match) { - var name = match[1].trim(); - var content = match[2].trim(); + var name = match[1]!.trim(); + var content = match[2]!.trim(); var trailingNewline = match[3]; packageGraph.addMacro(name, content); return '{@macro $name}$trailingNewline'; @@ -636,9 +636,9 @@ mixin DocumentationComment /// {@end-inject-html} /// String _stripHtmlAndAddToIndex(String rawDocs) { - if (!config.injectHtml) return rawDocs; + if (!config!.injectHtml) return rawDocs; return rawDocs.replaceAllMapped(_htmlPattern, (match) { - var fragment = match[1]; + var fragment = match[1]!; var digest = crypto.sha1.convert(fragment.codeUnits).toString(); packageGraph.addHtmlFragment(digest, fragment); // The newlines are so that Markdown will pass this through without @@ -652,7 +652,7 @@ mixin DocumentationComment /// First, this will split the given [argsAsString] into separate arguments /// with [_splitUpQuotedArgs] it then parses the resulting argument list /// normally with [argParser] and returns the result. - ArgResults _parseArgs( + ArgResults? _parseArgs( String argsAsString, ArgParser argParser, String directiveName) { var args = _splitUpQuotedArgs(argsAsString, convertToArgs: true); try { @@ -711,7 +711,7 @@ mixin DocumentationComment // by an equals sign), add a "--" in front so that they parse as options. return matches.map((Match match) { var option = ''; - if (convertToArgs && match[1] != null && !match[1].startsWith('-')) { + if (convertToArgs && match[1] != null && !match[1]!.startsWith('-')) { option = '--'; } if (match[2] != null) { @@ -736,7 +736,7 @@ mixin DocumentationComment } } for (var element in firstOfPair) { - final result = element.group(2).trim(); + final result = element.group(2)!.trim(); if (result.isEmpty) { warn(PackageWarning.missingCodeBlockLanguage, message: @@ -749,9 +749,9 @@ mixin DocumentationComment /// [config.dropTextFrom] indicates it should not be returned. Macro /// definitions are stripped, but macros themselves are not injected. This /// is a two stage process to avoid ordering problems. - String _documentationLocal; + String? _documentationLocal; - String get documentationLocal => + String? get documentationLocal => _documentationLocal ??= _buildDocumentationLocal(); /// Unconditionally precache local documentation. @@ -761,25 +761,25 @@ mixin DocumentationComment _documentationLocal = await _buildDocumentationBase(); } - bool _needsPrecache; + bool? _needsPrecache; bool get needsPrecache => _needsPrecache ??= _needsPrecacheRegExp.hasMatch(documentationComment ?? ''); - String _rawDocs; + String? _rawDocs; - String _buildDocumentationLocal() => _buildDocumentationBaseSync(); + String? _buildDocumentationLocal() => _buildDocumentationBaseSync(); /// Override this to add more features to the documentation builder in a /// subclass. - String buildDocumentationAddition(String docs) => docs ?? ''; + String buildDocumentationAddition(String? docs) => docs ?? ''; /// Separate from _buildDocumentationLocal for overriding. - String _buildDocumentationBaseSync() { + String? _buildDocumentationBaseSync() { assert(_rawDocs == null, 'reentrant calls to _buildDocumentation* not allowed'); // Do not use the sync method if we need to evaluate tools or templates. assert(!isCanonical || !needsPrecache); - if (config.dropTextFrom.contains(element.library.name)) { + if (config!.dropTextFrom.contains(element!.library!.name)) { _rawDocs = ''; } else { _rawDocs = _processCommentWithoutTools(documentationComment ?? ''); @@ -790,11 +790,11 @@ mixin DocumentationComment /// Separate from _buildDocumentationLocal for overriding. Can only be /// used as part of [PackageGraph.setUpPackageGraph]. - Future _buildDocumentationBase() async { + Future _buildDocumentationBase() async { assert(_rawDocs == null, 'reentrant calls to _buildDocumentation* not allowed'); // Do not use the sync method if we need to evaluate tools or templates. - if (config.dropTextFrom.contains(element.library.name)) { + if (config!.dropTextFrom.contains(element!.library!.name)) { _rawDocs = ''; } else { _rawDocs = await processComment(documentationComment ?? ''); @@ -837,11 +837,11 @@ mixin DocumentationComment /// /// And the HTML fragment will not have been processed or changed by Markdown, /// but just injected verbatim. - String _injectHtmlFragments(String rawDocs) { - if (!config.injectHtml) return rawDocs; + String? _injectHtmlFragments(String? rawDocs) { + if (!config!.injectHtml) return rawDocs; - return rawDocs.replaceAllMapped(_htmlInjectRegExp, (match) { - var fragment = packageGraph.getHtmlFragment(match[1]); + return rawDocs!.replaceAllMapped(_htmlInjectRegExp, (match) { + var fragment = packageGraph.getHtmlFragment(match[1])!; if (fragment == null) { warn(PackageWarning.unknownHtmlFragment, message: match[1]); } diff --git a/lib/src/model/dynamic.dart b/lib/src/model/dynamic.dart index 4d130dd65e..34fa1fc7b8 100644 --- a/lib/src/model/dynamic.dart +++ b/lib/src/model/dynamic.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; @@ -19,15 +19,15 @@ class Dynamic extends ModelElement { /// [dynamic] is not a real object, and so we can't document it, so there /// can be nothing canonical for it. @override - ModelElement get canonicalModelElement => null; + ModelElement? get canonicalModelElement => null; @override - ModelElement get enclosingElement => null; + ModelElement? get enclosingElement => null; /// And similarly, even if someone references it directly it can have /// no hyperlink. @override - String get href => null; + String? get href => null; @override String get kind => 'dynamic'; @@ -36,7 +36,7 @@ class Dynamic extends ModelElement { String get linkedName => 'dynamic'; @override - String get filePath => null; + String? get filePath => null; @override Map get referenceChildren => {}; diff --git a/lib/src/model/enclosed_element.dart b/lib/src/model/enclosed_element.dart index bc285f4505..42184290d7 100644 --- a/lib/src/model/enclosed_element.dart +++ b/lib/src/model/enclosed_element.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/model/model.dart'; @@ -10,5 +10,5 @@ import 'package:dartdoc/src/model/model.dart'; /// /// Libraries are not enclosed. abstract class EnclosedElement { - ModelElement get enclosingElement; + ModelElement? get enclosingElement; } diff --git a/lib/src/model/enum.dart b/lib/src/model/enum.dart index a15cfb6fd4..bc0b23fd89 100644 --- a/lib/src/model/enum.dart +++ b/lib/src/model/enum.dart @@ -2,7 +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. -// @dart=2.9 + // TODO(jcollins-g): Consider Enum as subclass of Container? import 'package:analyzer/dart/element/element.dart'; @@ -11,28 +11,28 @@ import 'package:dartdoc/src/render/enum_field_renderer.dart'; import 'package:dartdoc/src/special_elements.dart'; class Enum extends InheritingContainer with TypeImplementing { - Enum(ClassElement element, Library library, PackageGraph packageGraph) + Enum(ClassElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); - List _inheritanceChain; + List? _inheritanceChain; @override - List get inheritanceChain { + List get inheritanceChain { if (_inheritanceChain == null) { _inheritanceChain = []; - _inheritanceChain.add(this); + _inheritanceChain!.add(this); for (var c in superChain.map((e) => (e.modelElement as InheritingContainer))) { - _inheritanceChain.addAll(c.inheritanceChain); + _inheritanceChain!.addAll(c.inheritanceChain); } - _inheritanceChain.addAll(interfaces.expand( + _inheritanceChain!.addAll(interfaces.expand( (e) => (e.modelElement as InheritingContainer).inheritanceChain)); - assert(_inheritanceChain + assert(_inheritanceChain! .contains(packageGraph.specialClasses[SpecialClass.enumClass])); } - return _inheritanceChain.toList(growable: false); + return _inheritanceChain!.toList(growable: false); } @override @@ -42,21 +42,21 @@ class Enum extends InheritingContainer with TypeImplementing { /// Enum's fields are virtual, so we do a little work to create /// usable values for the docs. class EnumField extends Field { - int index; + int? index; EnumField(FieldElement element, Library library, PackageGraph packageGraph, - Accessor getter, Accessor setter) - : super(element, library, packageGraph, getter, setter); + Accessor? getter, Accessor? setter) + : super(element, library, packageGraph, getter as ContainerAccessor?, setter as ContainerAccessor?); EnumField.forConstant(this.index, FieldElement element, Library library, - PackageGraph packageGraph, Accessor getter) - : super(element, library, packageGraph, getter, null); + PackageGraph packageGraph, Accessor? getter) + : super(element, library, packageGraph, getter as ContainerAccessor?, null); @override String get constantValueBase => _fieldRenderer.renderValue(this); @override - List get documentationFrom { + List? get documentationFrom { if (name == 'values' || name == 'index') return [this]; return super.documentationFrom; } @@ -81,18 +81,18 @@ class EnumField extends Field { } @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } assert(!(canonicalLibrary == null || canonicalEnclosingContainer == null)); assert(canonicalLibrary == library); assert(canonicalEnclosingContainer == enclosingElement); - return '${package.baseHref}${enclosingElement.library.dirName}/${enclosingElement.fileName}'; + return '${package.baseHref}${enclosingElement!.library!.dirName}/${enclosingElement!.fileName}'; } @override - String get linkedName => name; + String? get linkedName => name; @override bool get isCanonical { @@ -109,10 +109,10 @@ class EnumField extends Field { } @override - String get oneLineDoc => documentationAsHtml; + String? get oneLineDoc => documentationAsHtml; @override - Inheritable get overriddenElement => null; + Inheritable? get overriddenElement => null; EnumFieldRenderer get _fieldRenderer => packageGraph.rendererFactory.enumFieldRenderer; diff --git a/lib/src/model/extendable.dart b/lib/src/model/extendable.dart index 909bd30a13..e296fd1c47 100644 --- a/lib/src/model/extendable.dart +++ b/lib/src/model/extendable.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/extension.dart b/lib/src/model/extension.dart index 09cf1a6430..5615637cfc 100644 --- a/lib/src/model/extension.dart +++ b/lib/src/model/extension.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; @@ -13,50 +13,50 @@ import 'package:dartdoc/src/quiver.dart' as quiver; /// Extension methods class Extension extends Container implements EnclosedElement { - ElementType extendedType; + ElementType? extendedType; Extension( ExtensionElement element, Library library, PackageGraph packageGraph) : super(element, library, packageGraph) { - extendedType = modelBuilder.typeFrom(_extension.extendedType, library); + extendedType = modelBuilder.typeFrom(_extension!.extendedType, library); } /// Detect if this extension applies to every object. bool get alwaysApplies => - extendedType.instantiatedType.isDynamic || - extendedType.instantiatedType.isVoid || - extendedType.instantiatedType.isDartCoreObject; + extendedType!.instantiatedType.isDynamic || + extendedType!.instantiatedType.isVoid || + extendedType!.instantiatedType.isDartCoreObject; bool couldApplyTo(T c) => - _couldApplyTo(c.modelType); + _couldApplyTo(c.modelType as DefinedElementType); /// Return true if this extension could apply to [t]. bool _couldApplyTo(DefinedElementType t) { - if (extendedType.instantiatedType.isDynamic || - extendedType.instantiatedType.isVoid) { + if (extendedType!.instantiatedType.isDynamic || + extendedType!.instantiatedType.isVoid) { return true; } - return t.instantiatedType == extendedType.instantiatedType || - (t.instantiatedType.element == extendedType.instantiatedType.element && - extendedType.isSubtypeOf(t)) || - extendedType.isBoundSupertypeTo(t); + return t.instantiatedType == extendedType!.instantiatedType || + (t.instantiatedType.element == extendedType!.instantiatedType.element && + extendedType!.isSubtypeOf(t)) || + extendedType!.isBoundSupertypeTo(t); } /// Returns the library that encloses this element. @override - ModelElement get enclosingElement => library; + ModelElement? get enclosingElement => library; - ExtensionElement get _extension => (element as ExtensionElement); + ExtensionElement? get _extension => (element as ExtensionElement?); @override String get kind => 'extension'; - List _methods; + List? _methods; @override - List get declaredMethods { - _methods ??= _extension.methods.map((e) { - return modelBuilder.from(e, library) as Method; + List? get declaredMethods { + _methods ??= _extension!.methods.map((e) { + return modelBuilder.from(e, library!) as Method; }).toList(growable: false); return _methods; } @@ -64,11 +64,11 @@ class Extension extends Container implements EnclosedElement { @override String get name => super.name ?? ''; - List _declaredFields; + List? _declaredFields; @override - List get declaredFields { - _declaredFields ??= _extension.fields.map((f) { + List? get declaredFields { + _declaredFields ??= _extension!.fields.map((f) { Accessor getter, setter; if (f.getter != null) { getter = ContainerAccessor(f.getter, library, packageGraph); @@ -76,41 +76,41 @@ class Extension extends Container implements EnclosedElement { if (f.setter != null) { setter = ContainerAccessor(f.setter, library, packageGraph); } - return modelBuilder.fromPropertyInducingElement(f, library, + return modelBuilder.fromPropertyInducingElement(f, library!, getter: getter, setter: setter) as Field; }).toList(growable: false); return _declaredFields; } - List _typeParameters; + List? _typeParameters; // a stronger hash? @override - List get typeParameters { - _typeParameters ??= _extension.typeParameters.map((f) { - var lib = modelBuilder.fromElement(f.enclosingElement.library); - return modelBuilder.from(f, lib) as TypeParameter; + List? get typeParameters { + _typeParameters ??= _extension!.typeParameters.map((f) { + var lib = modelBuilder.fromElement(f.enclosingElement!.library!); + return modelBuilder.from(f, lib as Library) as TypeParameter; }).toList(); return _typeParameters; } - List _allModelElements; + List? _allModelElements; @override - List get allModelElements { + List? get allModelElements { _allModelElements ??= List.from( quiver.concat([ - super.allModelElements, - typeParameters, + super.allModelElements!, + typeParameters!, ]), growable: false); return _allModelElements; } @override - String get filePath => '${library.dirName}/$fileName'; + String get filePath => '${library!.dirName}/$fileName'; @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -119,11 +119,11 @@ class Extension extends Container implements EnclosedElement { return '${package.baseHref}$filePath'; } - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { return _referenceChildren ??= { - ...extendedType.referenceChildren, + ...extendedType!.referenceChildren, // Override extendedType entries with local items. ...super.referenceChildren, }; diff --git a/lib/src/model/extension_target.dart b/lib/src/model/extension_target.dart index 3291c2de05..db0a065d1f 100644 --- a/lib/src/model/extension_target.dart +++ b/lib/src/model/extension_target.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -13,17 +13,17 @@ mixin ExtensionTarget on ModelElement { bool get hasModifiers; bool get hasPotentiallyApplicableExtensions => - potentiallyApplicableExtensions.isNotEmpty; + potentiallyApplicableExtensions!.isNotEmpty; - List _potentiallyApplicableExtensions; + List? _potentiallyApplicableExtensions; /// The set of potentiallyApplicableExtensions, for display in templates. /// /// This is defined as those extensions where an instantiation of the type /// defined by [element] can exist where this extension applies, not including /// any extension that applies to every type. - Iterable get potentiallyApplicableExtensions { - _potentiallyApplicableExtensions ??= packageGraph.documentedExtensions + Iterable? get potentiallyApplicableExtensions { + _potentiallyApplicableExtensions ??= packageGraph.documentedExtensions! .where((e) => !e.alwaysApplies) .where((e) => e.couldApplyTo(this)) .toList(growable: false); @@ -33,5 +33,5 @@ mixin ExtensionTarget on ModelElement { ElementType get modelType; List get potentiallyApplicableExtensionsSorted => - potentiallyApplicableExtensions.toList()..sort(byName); + potentiallyApplicableExtensions!.toList()..sort(byName); } diff --git a/lib/src/model/feature.dart b/lib/src/model/feature.dart index eaa2638c8b..befff3805b 100644 --- a/lib/src/model/feature.dart +++ b/lib/src/model/feature.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:collection/collection.dart'; import 'package:dartdoc/src/model/privacy.dart'; @@ -10,11 +10,11 @@ import 'package:dartdoc/src/model/privacy.dart'; int byFeatureOrdering(Feature a, Feature b) { if (a.sortGroup < b.sortGroup) return -1; if (a.sortGroup > b.sortGroup) return 1; - return compareAsciiLowerCaseNatural(a.name, b.name); + return compareAsciiLowerCaseNatural(a.name!, b.name!); } class ElementFeatureNotFoundError extends Error { - final String message; + final String? message; ElementFeatureNotFoundError([this.message]); @@ -25,7 +25,7 @@ class ElementFeatureNotFoundError extends Error { /// A "feature" includes both explicit annotations in code (e.g. `deprecated`) /// as well as others added by the documentation system (`read-write`); class Feature implements Privacy { - final String _name; + final String? _name; /// Do not use this except in subclasses, prefer const members of this /// class instead. @@ -33,14 +33,14 @@ class Feature implements Privacy { final String featurePrefix = ''; - String get name => _name; + String? get name => _name; - String get linkedName => name; + String? get linkedName => name; - String get linkedNameWithParameters => linkedName; + String? get linkedNameWithParameters => linkedName; @override - bool get isPublic => !name.startsWith('_'); + bool get isPublic => !name!.startsWith('_'); /// Numerical sort group for this feature. /// Less than zero will sort before custom annotations. diff --git a/lib/src/model/feature_set.dart b/lib/src/model/feature_set.dart index 31b67d84cf..a6365c6f55 100644 --- a/lib/src/model/feature_set.dart +++ b/lib/src/model/feature_set.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/model/language_feature.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -11,7 +11,7 @@ import 'package:dartdoc/src/model/model.dart'; /// the user interpretation of the interface. mixin FeatureSet { PackageGraph get packageGraph; - Library get library; + Library? get library; /// A list of language features that both apply to this [ModelElement] and /// make sense to display in context. @@ -28,5 +28,5 @@ mixin FeatureSet { // TODO(jcollins-g): This is an approximation and not strictly true for // inheritance/reexports. - bool get isNullSafety => library.isNullSafety; + bool get isNullSafety => library!.isNullSafety; } diff --git a/lib/src/model/field.dart b/lib/src/model/field.dart index 150912e40a..acc801f11b 100644 --- a/lib/src/model/field.dart +++ b/lib/src/model/field.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/feature.dart'; @@ -13,18 +13,18 @@ class Field extends ModelElement with GetterSetterCombo, ContainerMember, Inheritable implements EnclosedElement { bool _isInherited = false; - Container _enclosingContainer; + Container? _enclosingContainer; @override - final ContainerAccessor getter; + final ContainerAccessor? getter; @override - final ContainerAccessor setter; + final ContainerAccessor? setter; Field(FieldElement element, Library library, PackageGraph packageGraph, this.getter, this.setter) : super(element, library, packageGraph) { assert(getter != null || setter != null); - if (getter != null) getter.enclosingCombo = this; - if (setter != null) setter.enclosingCombo = this; + if (getter != null) getter!.enclosingCombo = this; + if (setter != null) setter!.enclosingCombo = this; } factory Field.inherited( @@ -32,9 +32,9 @@ class Field extends ModelElement Container enclosingContainer, Library library, PackageGraph packageGraph, - Accessor getter, - Accessor setter) { - var newField = Field(element, library, packageGraph, getter, setter); + Accessor? getter, + Accessor? setter) { + var newField = Field(element, library, packageGraph, getter as ContainerAccessor?, setter as ContainerAccessor?); newField._isInherited = true; newField._enclosingContainer = enclosingContainer; // Can't set _isInherited to true if this is the defining element, because @@ -57,17 +57,17 @@ class Field extends ModelElement } @override - Container get enclosingElement { - _enclosingContainer ??= modelBuilder.from(field.enclosingElement, library); + Container? get enclosingElement { + _enclosingContainer ??= modelBuilder.from(field!.enclosingElement, library!) as Container?; return _enclosingContainer; } @override String get filePath => - '${enclosingElement.library.dirName}/${enclosingElement.name}/$fileName'; + '${enclosingElement!.library!.dirName}/${enclosingElement!.name}/$fileName'; @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -78,23 +78,23 @@ class Field extends ModelElement } @override - bool get isConst => field.isConst; + bool get isConst => field!.isConst; /// Returns true if the FieldElement is covariant, or if the first parameter /// for the setter is covariant. @override - bool get isCovariant => setter?.isCovariant == true || field.isCovariant; + bool get isCovariant => setter?.isCovariant == true || field!.isCovariant; @override bool get isFinal { /// isFinal returns true for the field even if it has an explicit getter /// (which means we should not document it as "final"). if (hasExplicitGetter) return false; - return field.isFinal; + return field!.isFinal; } @override - bool get isLate => isFinal && field.isLate; + bool get isLate => isFinal && field!.isLate; @override bool get isInherited => _isInherited; @@ -103,7 +103,7 @@ class Field extends ModelElement String get kind => isConst ? 'constant' : 'property'; String get fullkind { - if (field.isAbstract) return 'abstract $kind'; + if (field!.isAbstract) return 'abstract $kind'; return kind; } @@ -114,28 +114,28 @@ class Field extends ModelElement // either the getter or setter has one of those properties, but that's not // really specific enough for [Field]s that have public getter/setters. if (hasPublicGetter && hasPublicSetter) { - if (getter.isInherited && setter.isInherited) { + if (getter!.isInherited && setter!.isInherited) { allFeatures.add(Feature.inherited); } else { allFeatures.remove(Feature.inherited); - if (getter.isInherited) allFeatures.add(Feature.inheritedGetter); - if (setter.isInherited) allFeatures.add(Feature.inheritedSetter); + if (getter!.isInherited) allFeatures.add(Feature.inheritedGetter); + if (setter!.isInherited) allFeatures.add(Feature.inheritedSetter); } - if (getter.isOverride && setter.isOverride) { + if (getter!.isOverride! && setter!.isOverride!) { allFeatures.add(Feature.overrideFeature); } else { allFeatures.remove(Feature.overrideFeature); - if (getter.isOverride) allFeatures.add(Feature.overrideGetter); - if (setter.isOverride) allFeatures.add(Feature.overrideSetter); + if (getter!.isOverride!) allFeatures.add(Feature.overrideGetter); + if (setter!.isOverride!) allFeatures.add(Feature.overrideSetter); } } else { if (isInherited) allFeatures.add(Feature.inherited); - if (isOverride) allFeatures.add(Feature.overrideFeature); + if (isOverride!) allFeatures.add(Feature.overrideFeature); } return allFeatures; } - FieldElement get field => (element as FieldElement); + FieldElement? get field => (element as FieldElement?); @override String get fileName => '${isConst ? '$name-constant' : name}.$fileType'; @@ -143,13 +143,13 @@ class Field extends ModelElement SourceCodeRenderer get _sourceCodeRenderer => packageGraph.rendererFactory.sourceCodeRenderer; - String _sourceCode; + String? _sourceCode; @override - String get sourceCode { + String? get sourceCode { if (_sourceCode == null) { // We could use a set to figure the dupes out, but that would lose ordering. - var fieldSourceCode = modelNode.sourceCode ?? ''; + var fieldSourceCode = modelNode!.sourceCode ?? ''; var getterSourceCode = getter?.sourceCode ?? ''; var setterSourceCode = setter?.sourceCode ?? ''; var buffer = StringBuffer(); @@ -173,5 +173,5 @@ class Field extends ModelElement } @override - Inheritable get overriddenElement => null; + Inheritable? get overriddenElement => null; } diff --git a/lib/src/model/getter_setter_combo.dart b/lib/src/model/getter_setter_combo.dart index ffecb26fb1..02be89585b 100644 --- a/lib/src/model/getter_setter_combo.dart +++ b/lib/src/model/getter_setter_combo.dart @@ -2,7 +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. -// @dart=2.9 + import 'dart:convert'; @@ -24,15 +24,15 @@ import 'package:meta/meta.dart'; /// Mixin for top-level variables and fields (aka properties) mixin GetterSetterCombo on ModelElement { - Accessor get getter; + Accessor? get getter; - Accessor get setter; + Accessor? get setter; @override Iterable get annotations => [ ...super.annotations, - if (hasGetter) ...getter.annotations, - if (hasSetter) ...setter.annotations, + if (hasGetter) ...getter!.annotations, + if (hasSetter) ...setter!.annotations, ]; Iterable get allAccessors sync* { @@ -43,36 +43,36 @@ mixin GetterSetterCombo on ModelElement { @protected Set get comboFeatures => { - if (hasExplicitGetter && hasPublicGetter) ...getter.features, - if (hasExplicitSetter && hasPublicSetter) ...setter.features, + if (hasExplicitGetter && hasPublicGetter) ...getter!.features, + if (hasExplicitSetter && hasPublicSetter) ...setter!.features, if (readOnly && !isFinal && !isConst) Feature.readOnly, if (writeOnly) Feature.writeOnly, if (readWrite && !isLate) Feature.readWrite, }; @override - ModelElement enclosingElement; + ModelElement? enclosingElement; bool get isInherited; - Expression get constantInitializer => + Expression? get constantInitializer => (element as ConstVariableElement).constantInitializer; String linkifyConstantValue(String original) { if (constantInitializer is! InstanceCreationExpression) return original; var creationExpression = constantInitializer as InstanceCreationExpression; var constructorName = creationExpression.constructorName.toString(); - Element staticElement = creationExpression.constructorName.staticElement; + Element? staticElement = creationExpression.constructorName.staticElement; if (staticElement == null) { warn(PackageWarning.missingConstantConstructor, message: constructorName); return original; } - Constructor target = modelBuilder.fromElement(staticElement); - Class targetClass = target.enclosingElement; + Constructor target = modelBuilder.fromElement(staticElement) as Constructor; + Class targetClass = target.enclosingElement as Class; // TODO(jcollins-g): this logic really should be integrated into Constructor, // but that's not trivial because of linkedName's usage. if (targetClass.name == target.name) { - return original.replaceAll(constructorName, target.linkedName); + return original.replaceAll(constructorName, target.linkedName!); } return original.replaceAll('${targetClass.name}.${target.name}', '${targetClass.linkedName}.${target.linkedName}'); @@ -84,14 +84,14 @@ mixin GetterSetterCombo on ModelElement { } @override - CharacterLocation get characterLocation { + CharacterLocation? get characterLocation { // Handle all synthetic possibilities. Ordinarily, warnings for // explicit setters/getters will be handled by those objects, but // if a warning comes up for an enclosing synthetic field we have to // put it somewhere. So pick an accessor. - if (element.isSynthetic) { - if (hasExplicitGetter) return getter.characterLocation; - if (hasExplicitSetter) return setter.characterLocation; + if (element!.isSynthetic) { + if (hasExplicitGetter) return getter!.characterLocation; + if (hasExplicitSetter) return setter!.characterLocation; assert(false, 'Field and accessors can not all be synthetic'); } return super.characterLocation; @@ -101,31 +101,31 @@ mixin GetterSetterCombo on ModelElement { String get constantValueTruncated => linkifyConstantValue(truncateString(constantValueBase, 200)); - String _constantValueBase; + String? _constantValueBase; String get constantValueBase => _constantValueBase ??= _buildConstantValueBase(); - bool get hasPublicGetter => hasGetter && getter.isPublic; + bool get hasPublicGetter => hasGetter && getter!.isPublic!; - bool get hasPublicSetter => hasSetter && setter.isPublic; + bool get hasPublicSetter => hasSetter && setter!.isPublic!; @override bool get isPublic => hasPublicGetter || hasPublicSetter; - List _documentationFrom; + List? _documentationFrom; @override - List get documentationFrom { + List? get documentationFrom { if (_documentationFrom == null) { _documentationFrom = []; if (hasPublicGetter) { - _documentationFrom.addAll(getter.documentationFrom); + _documentationFrom!.addAll(getter!.documentationFrom!); } else if (hasPublicSetter) { - _documentationFrom.addAll(setter.documentationFrom); + _documentationFrom!.addAll(setter!.documentationFrom!); } - if (_documentationFrom.isEmpty || - _documentationFrom.every((e) => e.documentationComment == '')) { + if (_documentationFrom!.isEmpty || + _documentationFrom!.every((e) => e.documentationComment == '')) { _documentationFrom = super.documentationFrom; } } @@ -133,28 +133,28 @@ mixin GetterSetterCombo on ModelElement { } bool get hasAccessorsWithDocs => - (hasPublicGetter && !getter.isSynthetic && getter.hasDocumentation || - hasPublicSetter && !setter.isSynthetic && setter.hasDocumentation); + (hasPublicGetter && !getter!.isSynthetic && getter!.hasDocumentation || + hasPublicSetter && !setter!.isSynthetic && setter!.hasDocumentation); bool get getterSetterBothAvailable => (hasPublicGetter && - getter.hasDocumentation && + getter!.hasDocumentation && hasPublicSetter && - setter.hasDocumentation); + setter!.hasDocumentation); - String _oneLineDoc; + String? _oneLineDoc; @override - String get oneLineDoc { + String? get oneLineDoc { if (_oneLineDoc == null) { if (!hasAccessorsWithDocs) { _oneLineDoc = super.oneLineDoc; } else { var buffer = StringBuffer(); - if (hasPublicGetter && getter.oneLineDoc.isNotEmpty) { - buffer.write(getter.oneLineDoc); + if (hasPublicGetter && getter!.oneLineDoc!.isNotEmpty) { + buffer.write(getter!.oneLineDoc); } - if (hasPublicSetter && setter.oneLineDoc.isNotEmpty) { - buffer.write(getterSetterBothAvailable ? "" : setter.oneLineDoc); + if (hasPublicSetter && setter!.oneLineDoc!.isNotEmpty) { + buffer.write(getterSetterBothAvailable ? "" : setter!.oneLineDoc); } _oneLineDoc = buffer.toString(); } @@ -163,47 +163,47 @@ mixin GetterSetterCombo on ModelElement { } bool _documentationCommentComputed = false; - String _documentationComment; + String? _documentationComment; @override - String /*!*/ get documentationComment => _documentationCommentComputed - ? _documentationComment + String get documentationComment => _documentationCommentComputed + ? _documentationComment! : _documentationComment ??= () { _documentationCommentComputed = true; var docs = _getterSetterDocumentationComment; - if (docs.isEmpty) return element.documentationComment ?? ''; + if (docs.isEmpty) return element!.documentationComment ?? ''; return docs; }(); @override bool get hasDocumentationComment => _getterSetterDocumentationComment.isNotEmpty || - element.documentationComment != null; + element!.documentationComment != null; - String __getterSetterDocumentationComment; + String? __getterSetterDocumentationComment; /// Derive a documentation comment for the combo by copying documentation /// from the [getter] and/or [setter]. - String /*!*/ get _getterSetterDocumentationComment => + String get _getterSetterDocumentationComment => __getterSetterDocumentationComment ??= () { var buffer = StringBuffer(); // Check for synthetic before public, always, or stack overflow. - if (hasGetter && !getter.isSynthetic && getter.isPublic) { - assert(getter.documentationFrom.length == 1); - var fromGetter = getter.documentationFrom.first; + if (hasGetter && !getter!.isSynthetic && getter!.isPublic!) { + assert(getter!.documentationFrom!.length == 1); + var fromGetter = getter!.documentationFrom!.first; // We have to check against dropTextFrom here since documentationFrom // doesn't yield the real elements for GetterSetterCombos. - if (!config.dropTextFrom.contains(fromGetter.element.library.name)) { + if (!config!.dropTextFrom.contains(fromGetter.element!.library!.name)) { if (fromGetter.hasDocumentationComment) { buffer.write(fromGetter.documentationComment); } } } - if (hasSetter && !setter.isSynthetic && setter.isPublic) { - assert(setter.documentationFrom.length == 1); - var fromSetter = setter.documentationFrom.first; - if (!config.dropTextFrom.contains(fromSetter.element.library.name)) { + if (hasSetter && !setter!.isSynthetic && setter!.isPublic!) { + assert(setter!.documentationFrom!.length == 1); + var fromSetter = setter!.documentationFrom!.first; + if (!config!.dropTextFrom.contains(fromSetter.element!.library!.name)) { if (fromSetter.hasDocumentationComment) { if (buffer.isNotEmpty) buffer.write('\n\n'); buffer.write(fromSetter.documentationComment); @@ -214,8 +214,8 @@ mixin GetterSetterCombo on ModelElement { }(); ElementType get modelType { - if (hasGetter) return getter.modelType.returnType; - return setter.parameters.first.modelType; + if (hasGetter) return getter!.modelType.returnType; + return setter!.parameters!.first.modelType; } @override @@ -225,17 +225,17 @@ mixin GetterSetterCombo on ModelElement { bool get hasParameters => hasSetter; @override - List get parameters => setter.parameters; + List? get parameters => setter!.parameters; @override - String get linkedParamsNoMetadata { - if (hasSetter) return setter.linkedParamsNoMetadata; + String? get linkedParamsNoMetadata { + if (hasSetter) return setter!.linkedParamsNoMetadata; return null; } - bool get hasExplicitGetter => hasPublicGetter && !getter.isSynthetic; + bool get hasExplicitGetter => hasPublicGetter && !getter!.isSynthetic; - bool get hasExplicitSetter => hasPublicSetter && !setter.isSynthetic; + bool get hasExplicitSetter => hasPublicSetter && !setter!.isSynthetic; bool get hasGetter => getter != null; @@ -264,17 +264,17 @@ mixin GetterSetterCombo on ModelElement { bool get writeOnly => hasPublicSetter && !hasPublicGetter; - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; if (hasParameters) { - _referenceChildren.addEntries(parameters.explicitOnCollisionWith(this)); + _referenceChildren!.addEntries(parameters!.explicitOnCollisionWith(this)); } - _referenceChildren + _referenceChildren! .addEntries(modelType.typeArguments.explicitOnCollisionWith(this)); } - return _referenceChildren; + return _referenceChildren!; } } diff --git a/lib/src/model/indexable.dart b/lib/src/model/indexable.dart index 24d47da254..6c46312c83 100644 --- a/lib/src/model/indexable.dart +++ b/lib/src/model/indexable.dart @@ -2,15 +2,15 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 + import 'package:dartdoc/src/model/model.dart'; /// Something able to be indexed. abstract class Indexable implements Nameable { - String get href; + String? get href; String get kind; - int get overriddenDepth => 0; + int? get overriddenDepth => 0; } diff --git a/lib/src/model/inheritable.dart b/lib/src/model/inheritable.dart index 453606972e..27c8b70fd1 100644 --- a/lib/src/model/inheritable.dart +++ b/lib/src/model/inheritable.dart @@ -2,8 +2,9 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 + +import 'package:collection/collection.dart' show IterableExtension; import 'package:dartdoc/src/model/feature.dart'; import 'package:dartdoc/src/model/model.dart'; import 'package:dartdoc/src/special_elements.dart'; @@ -33,24 +34,23 @@ mixin Inheritable on ContainerMember { @override Set get features => { ...super.features, - if (isOverride) Feature.overrideFeature, + if (isOverride!) Feature.overrideFeature, if (isInherited) Feature.inherited, if (isCovariant) Feature.covariant, }; @override - Library get canonicalLibrary => canonicalEnclosingContainer?.canonicalLibrary; + Library? get canonicalLibrary => canonicalEnclosingContainer?.canonicalLibrary; @override - ModelElement buildCanonicalModelElement() { + ModelElement? buildCanonicalModelElement() { // TODO(jcollins-g): factor out extension logic into [Extendable] if (canonicalEnclosingContainer is Extension) { return this; } if (canonicalEnclosingContainer is Container) { - return canonicalEnclosingContainer.allCanonicalModelElements.firstWhere( - (m) => m.name == name && m.isPropertyAccessor == isPropertyAccessor, - orElse: () => null); + return canonicalEnclosingContainer!.allCanonicalModelElements.firstWhereOrNull( + (m) => m.name == name && m.isPropertyAccessor == isPropertyAccessor); } if (canonicalEnclosingContainer != null) { throw UnimplementedError('$canonicalEnclosingContainer: unknown type'); @@ -59,27 +59,27 @@ mixin Inheritable on ContainerMember { } @override - Container computeCanonicalEnclosingContainer() { + Container? computeCanonicalEnclosingContainer() { if (isInherited) { - var searchElement = element.declaration; + var searchElement = element!.declaration; // TODO(jcollins-g): generate warning if an inherited element's definition // is in an intermediate non-canonical class in the inheritance chain? - Container previous; - Container previousNonSkippable; - Container found; + Container? previous; + Container? previousNonSkippable; + Container? found; for (var c in inheritance.reversed) { // Filter out mixins. - if (c.containsElement(searchElement)) { - if ((packageGraph.inheritThrough.contains(previous) && + if (c!.containsElement(searchElement)) { + if ((packageGraph.inheritThrough!.contains(previous) && c != definingEnclosingContainer) || - (packageGraph.inheritThrough.contains(c) && + (packageGraph.inheritThrough!.contains(c) && c == definingEnclosingContainer)) { - return previousNonSkippable + return previousNonSkippable! .memberByExample(this) .canonicalEnclosingContainer; } - Container canonicalC = - packageGraph.findCanonicalModelElementFor(c.element); + Container? canonicalC = + packageGraph.findCanonicalModelElementFor(c.element) as Container?; // TODO(jcollins-g): invert this lookup so traversal is recursive // starting from the ModelElement. if (canonicalC != null) { @@ -90,14 +90,14 @@ mixin Inheritable on ContainerMember { } } previous = c; - if (!packageGraph.inheritThrough.contains(c)) { + if (!packageGraph.inheritThrough!.contains(c)) { previousNonSkippable = c; } } // This is still OK because we're never supposed to cloak public // classes. - if (definingEnclosingContainer.isCanonical && - definingEnclosingContainer.isPublic) { + if (definingEnclosingContainer!.isCanonical && + definingEnclosingContainer!.isPublic!) { assert(definingEnclosingContainer == found); } if (found != null) { @@ -106,13 +106,13 @@ mixin Inheritable on ContainerMember { } else if (!isInherited && definingEnclosingContainer is! Extension) { // TODO(jcollins-g): factor out extension logic into [Extendable]. return packageGraph - .findCanonicalModelElementFor(element.enclosingElement); + .findCanonicalModelElementFor(element!.enclosingElement) as Container?; } return super.computeCanonicalEnclosingContainer(); } - List get inheritance { - var inheritance = []; + List get inheritance { + var inheritance = []; inheritance .addAll((enclosingElement as InheritingContainer).inheritanceChain); var object = packageGraph.specialClasses[SpecialClass.object]; @@ -129,12 +129,12 @@ mixin Inheritable on ContainerMember { return inheritance; } - Inheritable get overriddenElement; + Inheritable? get overriddenElement; - bool _isOverride; + bool? _isOverride; /// True if this [Inheritable] is overriding a superclass. - bool get isOverride { + bool? get isOverride { if (_isOverride == null) { // The canonical version of the enclosing element -- not canonicalEnclosingElement, // as that is the element enclosing the canonical version of this element, @@ -146,11 +146,11 @@ mixin Inheritable on ContainerMember { _isOverride = false; return _isOverride; } - InheritingContainer enclosingCanonical = - enclosingElement.canonicalModelElement; + InheritingContainer? enclosingCanonical = + enclosingElement!.canonicalModelElement as InheritingContainer?; // The container in which this element was defined, canonical if available. - Container definingCanonical = - definingEnclosingContainer.canonicalModelElement ?? + Container? definingCanonical = + definingEnclosingContainer!.canonicalModelElement as Container? ?? definingEnclosingContainer; // The canonical version of the element we're overriding, if available. var overriddenCanonical = @@ -164,22 +164,22 @@ mixin Inheritable on ContainerMember { enclosingCanonical == definingCanonical && // If the overridden element isn't public, we shouldn't be an // override in most cases. Approximation until #1623 is fixed. - overriddenCanonical.isPublic; - assert(!(_isOverride && isInherited)); + overriddenCanonical!.isPublic!; + assert(!(_isOverride! && isInherited)); } return _isOverride; } - int _overriddenDepth; + int? _overriddenDepth; @override - int get overriddenDepth { + int? get overriddenDepth { if (_overriddenDepth == null) { _overriddenDepth = 0; - var e = this; + Inheritable e = this; while (e.overriddenElement != null) { _overriddenDepth += 1; - e = e.overriddenElement; + e = e.overriddenElement!; } } return _overriddenDepth; diff --git a/lib/src/model/inheriting_container.dart b/lib/src/model/inheriting_container.dart index cfe78f4b97..750d10d908 100644 --- a/lib/src/model/inheriting_container.dart +++ b/lib/src/model/inheriting_container.dart @@ -2,10 +2,11 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; +import 'package:collection/collection.dart' show IterableExtension; import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; import 'package:dartdoc/src/model/extension_target.dart'; @@ -20,10 +21,10 @@ import 'package:meta/meta.dart'; /// Note that [Constructor]s are not considered to be modifiers so a /// [hasModifier] override is not necessary for this mixin. mixin Constructable on InheritingContainer { - List _constructors; + List? _constructors; Iterable get constructors => _constructors ??= [ - ...element.constructors - .map((e) => modelBuilder.from(e, library) as Constructor) + ...element!.constructors + .map((e) => modelBuilder.from(e, library!) as Constructor) ]; @override @@ -33,24 +34,24 @@ mixin Constructable on InheritingContainer { Iterable get publicConstructors => model_utils.filterNonPublic(constructors); - List _publicConstructorsSorted; + List? _publicConstructorsSorted; @override Iterable get publicConstructorsSorted => _publicConstructorsSorted ??= publicConstructors.toList()..sort(byName); - Constructor _unnamedConstructor; - Constructor get unnamedConstructor { + Constructor? _unnamedConstructor; + Constructor? get unnamedConstructor { _unnamedConstructor ??= constructors - .firstWhere((c) => c.isUnnamedConstructor, orElse: () => null); + .firstWhereOrNull((c) => c.isUnnamedConstructor); return _unnamedConstructor; } - Constructor _defaultConstructor; + Constructor? _defaultConstructor; /// With constructor tearoffs, this is no longer equivalent to the unnamed /// constructor and assumptions based on that are incorrect. - Constructor get defaultConstructor { + Constructor? get defaultConstructor { _defaultConstructor ??= unnamedConstructor ?? constructors.firstWhere((c) => c.isDefaultConstructor); return _defaultConstructor; @@ -92,13 +93,13 @@ mixin Constructable on InheritingContainer { /// Add the ability to support mixed-in types to an [InheritingContainer]. mixin MixedInTypes on InheritingContainer { - List _mixedInTypes; + List? _mixedInTypes; List get mixedInTypes => _mixedInTypes ?? [ - ...element.mixins - .map((f) => modelBuilder.typeFrom(f, library)) + ...element!.mixins + .map((f) => modelBuilder.typeFrom(f, library!) as DefinedElementType) .where((mixin) => mixin != null) ]; @@ -114,12 +115,12 @@ mixin MixedInTypes on InheritingContainer { /// Add the ability for an [InheritingContainer] to be implemented by other /// InheritingContainers and to reference what it itself implements. mixin TypeImplementing on InheritingContainer { - List _directInterfaces; + List? _directInterfaces; List get directInterfaces => _directInterfaces ?? [ - ...element.interfaces - .map((f) => modelBuilder.typeFrom(f, library)) + ...element!.interfaces + .map((f) => modelBuilder.typeFrom(f, library!) as DefinedElementType) .toList(growable: false) ]; @@ -203,7 +204,7 @@ mixin TypeImplementing on InheritingContainer { return result; } - List _publicImplementorsSorted; + List? _publicImplementorsSorted; Iterable get publicImplementorsSorted => _publicImplementorsSorted ??= publicImplementors.toList()..sort(byName); @@ -222,21 +223,21 @@ abstract class InheritingContainer extends Container @override /// [ClassElement] is analogous to [InheritingContainer]. - ClassElement get element => super.element; + ClassElement? get element => super.element as ClassElement?; - DefinedElementType _supertype; - DefinedElementType get supertype => - _supertype ??= element.supertype?.element?.supertype == null + DefinedElementType? _supertype; + DefinedElementType? get supertype => + _supertype ??= element!.supertype?.element?.supertype == null ? null - : modelBuilder.typeFrom(element.supertype, library); + : modelBuilder.typeFrom(element!.supertype!, library!) as DefinedElementType?; InheritingContainer( - ClassElement element, Library library, PackageGraph packageGraph) + ClassElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); @override Iterable get instanceMethods => - quiver.concat([super.instanceMethods, inheritedMethods]); + quiver.concat([super.instanceMethods, inheritedMethods!]); @override bool get publicInheritedInstanceMethods => @@ -244,20 +245,20 @@ abstract class InheritingContainer extends Container @override Iterable get instanceOperators => - quiver.concat([super.instanceOperators, inheritedOperators]); + quiver.concat([super.instanceOperators!, inheritedOperators!]); @override bool get publicInheritedInstanceOperators => publicInstanceOperators.every((f) => f.isInherited); - List _allModelElements; + List? _allModelElements; @override - List get allModelElements { + List? get allModelElements { _allModelElements ??= List.from( quiver.concat([ - super.allModelElements, - typeParameters, + super.allModelElements!, + typeParameters!, ]), growable: false); return _allModelElements; @@ -265,14 +266,14 @@ abstract class InheritingContainer extends Container /// Returns the [InheritingContainer] with the library in which [element] is defined. InheritingContainer get definingContainer => - modelBuilder.from(element, definingLibrary); + modelBuilder.from(element!, definingLibrary) as InheritingContainer; /// Returns the library that encloses this element. @override - ModelElement get enclosingElement => library; + ModelElement? get enclosingElement => library; @override - String get filePath => '${library.dirName}/$fileName'; + String get filePath => '${library!.dirName}/$fileName'; String get fullkind => kind; @@ -285,7 +286,7 @@ abstract class InheritingContainer extends Container bool get hasPublicSuperChainReversed => publicSuperChainReversed.isNotEmpty; @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -295,14 +296,14 @@ abstract class InheritingContainer extends Container } /*lazy final*/ - List _inheritedMethods; + List? _inheritedMethods; - Iterable get inheritedMethods { + Iterable? get inheritedMethods { if (_inheritedMethods == null) { _inheritedMethods = []; - var methodNames = declaredMethods.map((m) => m.element.name).toSet(); + var methodNames = declaredMethods.map((m) => m.element!.name).toSet(); - var inheritedMethodElements = _inheritedElements.where((e) { + var inheritedMethodElements = _inheritedElements!.where((e) { return (e is MethodElement && !e.isOperator && e is! PropertyAccessorElement && @@ -310,40 +311,40 @@ abstract class InheritingContainer extends Container }).toSet(); for (var e in inheritedMethodElements) { - Method m = modelBuilder.from(e, library, enclosingContainer: this); - _inheritedMethods.add(m); + Method m = modelBuilder.from(e!, library!, enclosingContainer: this) as Method; + _inheritedMethods!.add(m); } } return _inheritedMethods; } Iterable get publicInheritedMethods => - model_utils.filterNonPublic(inheritedMethods); + model_utils.filterNonPublic(inheritedMethods!); bool get hasPublicInheritedMethods => publicInheritedMethods.isNotEmpty; /*lazy final*/ - List _inheritedOperators; + List? _inheritedOperators; - Iterable get inheritedOperators { + Iterable? get inheritedOperators { if (_inheritedOperators == null) { _inheritedOperators = []; - var operatorNames = declaredOperators.map((o) => o.element.name).toSet(); + var operatorNames = declaredOperators!.map((o) => o.element!.name).toSet(); - var inheritedOperatorElements = _inheritedElements.where((e) { + var inheritedOperatorElements = _inheritedElements!.where((e) { return (e is MethodElement && e.isOperator && !operatorNames.contains(e.name)); }).toSet(); for (var e in inheritedOperatorElements) { - Operator o = modelBuilder.from(e, library, enclosingContainer: this); - _inheritedOperators.add(o); + Operator o = modelBuilder.from(e!, library!, enclosingContainer: this) as Operator; + _inheritedOperators!.add(o); } } return _inheritedOperators; } - Iterable get inheritedFields => allFields.where((f) => f.isInherited); + Iterable get inheritedFields => allFields!.where((f) => f.isInherited); Iterable get publicInterfaces => []; @@ -351,25 +352,25 @@ abstract class InheritingContainer extends Container model_utils.filterNonPublic(inheritedFields); @override - bool get isCanonical => super.isCanonical && isPublic; + bool get isCanonical => super.isCanonical && isPublic!; /// Returns true if [other] is a parent class for this class. - bool _isInheritingFrom(InheritingContainer other) => superChain + bool _isInheritingFrom(InheritingContainer? other) => superChain .map((et) => (et.modelElement as InheritingContainer)) .contains(other); - DefinedElementType _modelType; + DefinedElementType? _modelType; @override DefinedElementType get modelType => - _modelType ??= modelBuilder.typeFrom(element.thisType, library); + (_modelType ??= modelBuilder.typeFrom(element!.thisType, library!) as DefinedElementType?)!; /// Not the same as superChain as it may include mixins. /// It's really not even the same as ordinary Dart inheritance, either, /// because we pretend that interfaces are part of the inheritance chain /// to include them in the set of things we might link to for documentation /// purposes in abstract classes. - List get inheritanceChain; + List get inheritanceChain; List get superChain { var typeChain = []; @@ -383,7 +384,7 @@ abstract class InheritingContainer extends Container parent = null; } else { parent = modelBuilder.typeFrom( - (parent.type as InterfaceType).superclass, library); + (parent.type as InterfaceType).superclass!, library!) as DefinedElementType?; } } else { parent = (parent.modelElement as Class).supertype; @@ -398,11 +399,11 @@ abstract class InheritingContainer extends Container Iterable get publicSuperChainReversed => publicSuperChain.toList().reversed; - List __inheritedElements; + List? __inheritedElements; - List get _inheritedElements { + List? get _inheritedElements { if (__inheritedElements == null) { - if (element.isDartCoreObject) { + if (element!.isDartCoreObject) { return __inheritedElements = []; } @@ -416,13 +417,13 @@ abstract class InheritingContainer extends Container return __inheritedElements = []; } - var inheritance = definingLibrary.inheritanceManager; - var cmap = inheritance.getInheritedConcreteMap2(element); - var imap = inheritance.getInheritedMap2(element); + var inheritance = definingLibrary.inheritanceManager!; + var cmap = inheritance.getInheritedConcreteMap2(element!); + var imap = inheritance.getInheritedMap2(element!); - List inheritanceChainElements; + List? inheritanceChainElements; - var combinedMap = {}; + var combinedMap = {}; for (var nameObj in cmap.keys) { combinedMap[nameObj.name] = cmap[nameObj]; } @@ -431,13 +432,13 @@ abstract class InheritingContainer extends Container // Elements in the inheritance chain starting from [this.element] // down to, but not including, [Object]. inheritanceChainElements ??= - inheritanceChain.map((c) => c.element).toList(); + inheritanceChain.map((c) => c!.element).toList(); // [packageGraph.specialClasses] is not available yet. bool _isDartCoreObject(ClassElement e) => e.name == 'Object' && e.library.name == 'dart.core'; assert(inheritanceChainElements - .contains(imap[nameObj].enclosingElement) || - _isDartCoreObject(imap[nameObj].enclosingElement)); + .contains(imap[nameObj]!.enclosingElement) || + _isDartCoreObject(imap[nameObj]!.enclosingElement as ClassElement)); // If the concrete object from [InheritanceManager3.getInheritedConcreteMap2] // is farther from this class in the inheritance chain than the one @@ -445,9 +446,9 @@ abstract class InheritingContainer extends Container // correctly accounts for intermediate abstract classes that have // method/field implementations. if (inheritanceChainElements - .indexOf(combinedMap[nameObj.name].enclosingElement) < + .indexOf(combinedMap[nameObj.name]!.enclosingElement as ClassElement?) < inheritanceChainElements - .indexOf(imap[nameObj].enclosingElement)) { + .indexOf(imap[nameObj]!.enclosingElement as ClassElement?)) { combinedMap[nameObj.name] = imap[nameObj]; } } else { @@ -460,13 +461,13 @@ abstract class InheritingContainer extends Container return __inheritedElements; } - List _allFields; + List? _allFields; - List get allFields { + List? get allFields { if (_allFields == null) { _allFields = []; var inheritedAccessorElements = {} - ..addAll(_inheritedElements.whereType()); + ..addAll(_inheritedElements!.whereType()); // This structure keeps track of inherited accessors, allowing lookup // by field name (stripping the '=' from setters). @@ -479,16 +480,16 @@ abstract class InheritingContainer extends Container // For half-inherited fields, the analyzer only links the non-inherited // to the [FieldElement]. Compose our [Field] class by hand by looking up // inherited accessors that may be related. - for (var f in element.fields) { + for (var f in element!.fields) { var getterElement = f.getter; if (getterElement == null && accessorMap.containsKey(f.name)) { - getterElement = accessorMap[f.name] - .firstWhere((e) => e.isGetter, orElse: () => null); + getterElement = accessorMap[f.name]! + .firstWhereOrNull((e) => e.isGetter); } var setterElement = f.setter; if (setterElement == null && accessorMap.containsKey(f.name)) { - setterElement = accessorMap[f.name] - .firstWhere((e) => e.isSetter, orElse: () => null); + setterElement = accessorMap[f.name]! + .firstWhereOrNull((e) => e.isSetter); } _addSingleField( getterElement, setterElement, inheritedAccessorElements, f); @@ -498,11 +499,11 @@ abstract class InheritingContainer extends Container // Now we only have inherited accessors who aren't associated with // anything in cls._fields. for (var fieldName in accessorMap.keys) { - var elements = accessorMap[fieldName].toList(); + var elements = accessorMap[fieldName]!.toList(); var getterElement = - elements.firstWhere((e) => e.isGetter, orElse: () => null); + elements.firstWhereOrNull((e) => e.isGetter); var setterElement = - elements.firstWhere((e) => e.isSetter, orElse: () => null); + elements.firstWhereOrNull((e) => e.isSetter); _addSingleField( getterElement, setterElement, inheritedAccessorElements); } @@ -511,7 +512,7 @@ abstract class InheritingContainer extends Container } @override - Iterable get declaredFields => allFields.where((f) => !f.isInherited); + Iterable get declaredFields => allFields!.where((f) => !f.isInherited); /// Add a single Field to _fields. /// @@ -519,23 +520,23 @@ abstract class InheritingContainer extends Container /// whose enclosing class inherits from the other (defaulting to the getter) /// and construct a Field using that. void _addSingleField( - PropertyAccessorElement getterElement, - PropertyAccessorElement setterElement, + PropertyAccessorElement? getterElement, + PropertyAccessorElement? setterElement, Set inheritedAccessors, - [FieldElement f]) { + [FieldElement? f]) { /// Return an [ContainerAccessor] with isInherited = true /// if [element] is in [inheritedAccessors]. - ContainerAccessor containerAccessorFrom( - PropertyAccessorElement element, + ContainerAccessor? containerAccessorFrom( + PropertyAccessorElement? element, Set inheritedAccessors, Container enclosingContainer) { ContainerAccessor accessor; if (element == null) return null; if (inheritedAccessors.contains(element)) { - accessor = modelBuilder.from(element, enclosingContainer.library, - enclosingContainer: enclosingContainer); + accessor = modelBuilder.from(element, enclosingContainer.library!, + enclosingContainer: enclosingContainer) as ContainerAccessor; } else { - accessor = modelBuilder.from(element, enclosingContainer.library); + accessor = modelBuilder.from(element, enclosingContainer.library!) as ContainerAccessor; } return accessor; } @@ -551,21 +552,21 @@ abstract class InheritingContainer extends Container // Pick an appropriate FieldElement to represent this element. // Only hard when dealing with a synthetic Field. if (getter != null && setter == null) { - f = getterElement.variable; + f = getterElement!.variable as FieldElement?; } else if (getter == null && setter != null) { - f = setterElement.variable; + f = setterElement!.variable as FieldElement?; } else { /* getter != null && setter != null */ // In cases where a Field is composed of two Accessors defined in // different places in the inheritance chain, there are two FieldElements // for this single Field we're trying to compose. Pick the one closest // to this class on the inheritance chain. - if (setter.enclosingElement is Class && + if (setter!.enclosingElement is Class && (setter.enclosingElement as Class) - ._isInheritingFrom(getter.enclosingElement)) { - f = setterElement.variable; + ._isInheritingFrom(getter!.enclosingElement as InheritingContainer?)) { + f = setterElement!.variable as FieldElement?; } else { - f = getterElement.variable; + f = getterElement!.variable as FieldElement?; } } } @@ -573,48 +574,48 @@ abstract class InheritingContainer extends Container if ((getter == null || getter.isInherited) && (setter == null || setter.isInherited)) { // Field is 100% inherited. - field = modelBuilder.fromPropertyInducingElement(f, library, - enclosingContainer: this, getter: getter, setter: setter); + field = modelBuilder.fromPropertyInducingElement(f!, library!, + enclosingContainer: this, getter: getter!, setter: setter!) as Field; } else { // Field is <100% inherited (could be half-inherited). // TODO(jcollins-g): Navigation is probably still confusing for // half-inherited fields when traversing the inheritance tree. Make // this better, somehow. - field = modelBuilder.fromPropertyInducingElement(f, library, - getter: getter, setter: setter); + field = modelBuilder.fromPropertyInducingElement(f!, library!, + getter: getter!, setter: setter!) as Field; } - _allFields.add(field); + _allFields!.add(field); } - Iterable _declaredMethods; + Iterable? _declaredMethods; @override Iterable get declaredMethods => - _declaredMethods ??= element.methods.map((e) { - return modelBuilder.from(e, library) as Method; + _declaredMethods ??= element!.methods.map((e) { + return modelBuilder.from(e, library!) as Method; }); - List _typeParameters; + List? _typeParameters; @override - List get typeParameters { - _typeParameters ??= element.typeParameters.map((f) { - var lib = modelBuilder.fromElement(f.enclosingElement.library); - return modelBuilder.from(f, lib) as TypeParameter; + List? get typeParameters { + _typeParameters ??= element!.typeParameters.map((f) { + var lib = modelBuilder.fromElement(f.enclosingElement!.library!); + return modelBuilder.from(f, lib as Library) as TypeParameter; }).toList(); return _typeParameters; } - Iterable _instanceFields; + Iterable? _instanceFields; @override Iterable get instanceFields => - _instanceFields ??= allFields.where((f) => !f.isStatic); + _instanceFields ??= allFields!.where((f) => !f.isStatic); @override bool get publicInheritedInstanceFields => publicInstanceFields.every((f) => f.isInherited); @override - Iterable get constantFields => allFields.where((f) => f.isConst); + Iterable get constantFields => allFields!.where((f) => f.isConst); } diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index f5bc68d8aa..268d1c09a5 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -2,7 +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. -// @dart=2.9 + import 'dart:collection'; @@ -17,6 +17,7 @@ import 'package:analyzer/src/dart/element/inheritance_manager3.dart' show InheritanceManager3; // ignore: implementation_imports import 'package:analyzer/src/generated/sdk.dart' show SdkLibrary; +import 'package:collection/collection.dart' show IterableExtension; import 'package:dartdoc/src/io_utils.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -64,7 +65,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @Deprecated('Use [modelBuilder.fromElement] instead of this factory.') factory Library(LibraryElement element, PackageGraph packageGraph) { - return packageGraph.modelBuilder.fromElement(element); + return packageGraph.modelBuilder.fromElement(element) as Library; } Library._(LibraryElement element, PackageGraph packageGraph, this.package, @@ -116,21 +117,21 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// Allow scope for Libraries. @override - Scope get scope => element.scope; + Scope get scope => element!.scope; - List __allOriginalModelElementNames; + List? __allOriginalModelElementNames; /// Return true if this library is in a package configured to be treated as /// as using Null safety and itself uses Null safety. - bool get _allowsNullSafety => element.isNonNullableByDefault; + bool get _allowsNullSafety => element!.isNonNullableByDefault; /// Return true if this library should be documented as using Null safety. /// A library may use Null safety but not documented that way. @override bool get isNullSafety => - config.enableExperiment.contains('non-nullable') && _allowsNullSafety; + config!.enableExperiment.contains('non-nullable') && _allowsNullSafety; - bool get isInSdk => element.isInSdk; + bool get isInSdk => element!.isInSdk; /// [allModelElements] resolved to their original names. /// @@ -138,31 +139,31 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// documented with this library, but these ModelElements and names correspond /// to the defining library where each originally came from with respect /// to inheritance and reexporting. Most useful for error reporting. - Iterable get _allOriginalModelElementNames { + Iterable? get _allOriginalModelElementNames { __allOriginalModelElementNames ??= allModelElements.map((e) { if (e is GetterSetterCombo) { - Accessor getter; - Accessor setter; + late Accessor getter; + late Accessor setter; if (e.hasGetter) { - getter = modelBuilder.fromElement(e.getter.element); + getter = modelBuilder.fromElement(e.getter!.element!) as Accessor; } if (e.hasSetter) { - setter = modelBuilder.fromElement(e.setter.element); + setter = modelBuilder.fromElement(e.setter!.element!) as Accessor; } return modelBuilder .fromPropertyInducingElement( - e.element, modelBuilder.fromElement(e.element.library), + e.element!, modelBuilder.fromElement(e.element!.library!) as Library, getter: getter, setter: setter) .fullyQualifiedName; } - return modelBuilder.fromElement(e.element).fullyQualifiedName; + return modelBuilder.fromElement(e.element!).fullyQualifiedName; }).toList(); return __allOriginalModelElementNames; } @override - CharacterLocation get characterLocation { - if (element.nameOffset == -1) { + CharacterLocation? get characterLocation { + if (element!.nameOffset == -1) { assert(isAnonymous, 'Only anonymous libraries are allowed to have no declared location'); return CharacterLocation(1, 1); @@ -172,15 +173,15 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override CompilationUnitElement get compilationUnitElement => - element.definingCompilationUnit; + element!.definingCompilationUnit; @override - Iterable get classes => allClasses.where((c) => !c.isErrorOrException); + Iterable get classes => allClasses!.where((c) => !c.isErrorOrException); @override - LibraryElement get element => super.element; + LibraryElement get element => super.element as LibraryElement; - /*late final*/ List _extensions; + late final List _extensions; @override Iterable get extensions { @@ -191,28 +192,28 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _extensions; } - SdkLibrary get sdkLib { - if (packageGraph.sdkLibrarySources.containsKey(element.librarySource)) { - return packageGraph.sdkLibrarySources[element.librarySource]; + SdkLibrary? get sdkLib { + if (packageGraph.sdkLibrarySources!.containsKey(element!.librarySource)) { + return packageGraph.sdkLibrarySources![element!.librarySource]; } return null; } @override bool get isPublic { - if (!super.isPublic) return false; + if (!super.isPublic!) return false; if (sdkLib != null && - (sdkLib.isInternal || !isSdkLibraryDocumented(sdkLib))) { + (sdkLib!.isInternal || !isSdkLibraryDocumented(sdkLib!))) { return false; } - if (config.isLibraryExcluded(name) || - config.isLibraryExcluded(element.librarySource.uri.toString())) { + if (config!.isLibraryExcluded(name) || + config!.isLibraryExcluded(element!.librarySource.uri.toString())) { return false; } return true; } - /*late final*/ List _constants; + late final List _constants; @override Iterable get constants { @@ -221,7 +222,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _constants; } - /*late final*/ Set _packageImportedExportedLibraries; + late final Set _packageImportedExportedLibraries; /// Returns all libraries either imported by or exported by any public library /// this library's package. (Not [PackageGraph], but sharing a package name). @@ -233,7 +234,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { Set get packageImportedExportedLibraries { if (_packageImportedExportedLibraries == null) { _packageImportedExportedLibraries = {}; - packageGraph.publicLibraries + packageGraph.publicLibraries! .where((l) => l.packageName == packageName) .forEach((l) { _packageImportedExportedLibraries.addAll(l.importedExportedLibraries); @@ -242,7 +243,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _packageImportedExportedLibraries; } - /*late final*/ Set _importedExportedLibraries; + late final Set _importedExportedLibraries; /// Returns all libraries either imported by or exported by this library, /// recursively. @@ -250,8 +251,8 @@ class Library extends ModelElement with Categorization, TopLevelContainer { if (_importedExportedLibraries == null) { _importedExportedLibraries = {}; var importedExportedLibraryElements = {}; - importedExportedLibraryElements.addAll(element.importedLibraries); - importedExportedLibraryElements.addAll(element.exportedLibraries); + importedExportedLibraryElements.addAll(element!.importedLibraries); + importedExportedLibraryElements.addAll(element!.exportedLibraries); for (var l in importedExportedLibraryElements) { var lib = modelBuilder.fromElement(l) as Library; _importedExportedLibraries.add(lib); @@ -261,26 +262,26 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _importedExportedLibraries; } - /*late final*/ Map> _prefixToLibrary; + late final Map> _prefixToLibrary; /// Map of import prefixes ('import "foo" as prefix;') to [Library]. Map> get prefixToLibrary { if (_prefixToLibrary == null) { _prefixToLibrary = {}; // It is possible to have overlapping prefixes. - for (var i in element.imports) { + for (var i in element!.imports) { // Ignore invalid imports. if (i.prefix?.name != null && i.importedLibrary != null) { _prefixToLibrary .putIfAbsent(i.prefix?.name, () => {}) - .add(modelBuilder.from(i.importedLibrary, library)); + .add(modelBuilder.from(i.importedLibrary!, library) as Library); } } } return _prefixToLibrary; } - /*late final*/ String _dirName; + late final String _dirName; String get dirName { if (_dirName == null) { @@ -293,7 +294,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _dirName; } - /*late final*/ Set _canonicalFor; + late final Set _canonicalFor; Set get canonicalFor { if (_canonicalFor == null) { @@ -311,32 +312,32 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// Example: /// {@canonicalFor libname.ClassName} @override - String buildDocumentationAddition(String rawDocs) { + String buildDocumentationAddition(String? rawDocs) { rawDocs = super.buildDocumentationAddition(rawDocs); - var newCanonicalFor = {}; - var notFoundInAllModelElements = {}; + var newCanonicalFor = {}; + var notFoundInAllModelElements = {}; rawDocs = rawDocs.replaceAllMapped(_canonicalRegExp, (Match match) { newCanonicalFor.add(match.group(1)); notFoundInAllModelElements.add(match.group(1)); return ''; }); if (notFoundInAllModelElements.isNotEmpty) { - notFoundInAllModelElements.removeAll(_allOriginalModelElementNames); + notFoundInAllModelElements.removeAll(_allOriginalModelElementNames!); } for (var notFound in notFoundInAllModelElements) { warn(PackageWarning.ignoredCanonicalFor, message: notFound); } // TODO(jcollins-g): warn if a macro/tool _does_ generate an unexpected // canonicalFor? - _canonicalFor ??= newCanonicalFor; + _canonicalFor ??= newCanonicalFor as Set; return rawDocs; } /// Libraries are not enclosed by anything. @override - ModelElement get enclosingElement => null; + ModelElement? get enclosingElement => null; - /*late final*/ List _enums; + late final List _enums; @override List get enums { @@ -348,7 +349,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _enums; } - /*late final*/ List _mixins; + late final List _mixins; @override List get mixins { @@ -360,12 +361,12 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _mixins; } - /*late final*/ List _exceptions; + late final List _exceptions; @override List get exceptions { _exceptions ??= - allClasses.where((c) => c.isErrorOrException).toList(growable: false); + allClasses!.where((c) => c.isErrorOrException).toList(growable: false); return _exceptions; } @@ -375,34 +376,29 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override String get filePath => '${library.dirName}/$fileName'; - List _functions; - @override - List get functions { - _functions ??= + late final List functions = _exportedAndLocalElements.whereType().map((e) { return modelBuilder.from(e, this) as ModelFunction; }).toList(growable: false); - return _functions; - } @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } return '${package.baseHref}$filePath'; } - InheritanceManager3 _inheritanceManager; + InheritanceManager3? _inheritanceManager; // TODO(srawlins): Make a static field, likely on [Class]. - InheritanceManager3 get inheritanceManager { + InheritanceManager3? get inheritanceManager { _inheritanceManager ??= InheritanceManager3(); return _inheritanceManager; } - bool get isAnonymous => element.name == null || element.name.isEmpty; + bool get isAnonymous => element!.name == null || element!.name.isEmpty; @override String get kind => 'library'; @@ -410,23 +406,23 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override Library get library => this; - /*late final*/ String _name; + late final String _name; @override String get name { if (_name == null) { - var source = element.source; + var source = element!.source; if (source.uri.isScheme('dart')) { // There are inconsistencies in library naming + URIs for the dart // internal libraries; rationalize them here. if (source.uri.toString().contains('/')) { - _name = element.name.replaceFirst('dart.', 'dart:'); + _name = element!.name.replaceFirst('dart.', 'dart:'); } else { _name = source.uri.toString(); } - } else if (element.name != null && element.name.isNotEmpty) { - _name = element.name; + } else if (element!.name != null && element!.name.isNotEmpty) { + _name = element!.name; } else { _name = pathContext.basename(source.fullName); if (_name.endsWith('.dart')) { @@ -438,7 +434,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _name; } - /*late final*/ String _nameFromPath; + late final String _nameFromPath; /// Generate a name for this library based on its location. /// @@ -448,7 +444,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// 'lib') are the same, but this will include slashes and possibly colons /// for anonymous libraries in subdirectories or other packages. String get nameFromPath { - _nameFromPath ??= _getNameFromPath(element, package, _restoredUri); + _nameFromPath ??= _getNameFromPath(element!, package, _restoredUri); return _nameFromPath; } @@ -456,17 +452,17 @@ class Library extends ModelElement with Categorization, TopLevelContainer { String get packageName => packageMeta?.name ?? ''; /// The real packageMeta, as opposed to the package we are documenting with. - PackageMeta _packageMeta; + PackageMeta? _packageMeta; - PackageMeta get packageMeta { + PackageMeta? get packageMeta { _packageMeta ??= packageGraph.packageMetaProvider.fromElement( - element, - config.sdkDir, + element!, + config!.sdkDir, ); return _packageMeta; } - /*late final*/ List _properties; + late final List _properties; /// All variables ("properties") except constants. @override @@ -476,7 +472,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _properties; } - /*late final*/ List _typedefs; + late final List _typedefs; @override List get typedefs { @@ -487,24 +483,20 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _typedefs; } - TypeSystem get typeSystem => element.typeSystem; + TypeSystem get typeSystem => element!.typeSystem; - List _classes; - List get allClasses { - _classes ??= _exportedAndLocalElements + late final List allClasses = _exportedAndLocalElements .whereType() .where((e) => !e.isMixin && !e.isEnum) .map((e) => modelBuilder.from(e, this) as Class) .toList(growable: false); - return _classes; - } - Class getClassByName(String name) { - return allClasses.firstWhere((it) => it.name == name, orElse: () => null); + Class? getClassByName(String name) { + return allClasses!.firstWhereOrNull((it) => it.name == name); } - /*late final*/ List _variables; + late final List _variables; List _getVariables() { if (_variables == null) { @@ -513,20 +505,20 @@ class Library extends ModelElement with Categorization, TopLevelContainer { .toSet(); elements.addAll(_exportedAndLocalElements .whereType() - .map((a) => a.variable)); + .map((a) => a.variable as TopLevelVariableElement)); _variables = []; for (var element in elements) { - Accessor getter; + late Accessor getter; if (element.getter != null) { - getter = modelBuilder.from(element.getter, this); + getter = modelBuilder.from(element.getter!, this) as Accessor; } - Accessor setter; + late Accessor setter; if (element.setter != null) { - setter = modelBuilder.from(element.setter, this); + setter = modelBuilder.from(element.setter!, this) as Accessor; } var me = modelBuilder.fromPropertyInducingElement(element, this, getter: getter, setter: setter); - _variables.add(me); + _variables.add(me as TopLevelVariable); } } return _variables; @@ -561,52 +553,52 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return name; } - /*late final*/ HashMap> _modelElementsMap; + late final HashMap> _modelElementsMap; HashMap> get modelElementsMap { if (_modelElementsMap == null) { var results = quiver.concat(>[ library.constants, - library.functions, + library.functions!, library.properties, library.typedefs, library.extensions.expand((e) { return quiver.concat([ [e], - e.allModelElements + e.allModelElements! ]); }), - library.allClasses.expand((c) { + library.allClasses!.expand((c) { return quiver.concat([ [c], - c.allModelElements + c.allModelElements! ]); }), library.enums.expand((e) { return quiver.concat([ [e], - e.allModelElements + e.allModelElements! ]); }), library.mixins.expand((m) { return quiver.concat([ [m], - m.allModelElements + m.allModelElements! ]); }), ]); _modelElementsMap = HashMap>(); for (var modelElement in results) { _modelElementsMap - .putIfAbsent(modelElement.element, () => {}) + .putIfAbsent(modelElement.element!, () => {}) .add(modelElement); } - _modelElementsMap.putIfAbsent(element, () => {}).add(this); + _modelElementsMap.putIfAbsent(element!, () => {}).add(this); } return _modelElementsMap; } - /*late final*/ List _allModelElements; + late final List _allModelElements; Iterable get allModelElements { return _allModelElements ??= [ @@ -614,22 +606,22 @@ class Library extends ModelElement with Categorization, TopLevelContainer { ]; } - /*late final*/ List _allCanonicalModelElements; + late final List _allCanonicalModelElements; Iterable get allCanonicalModelElements { return (_allCanonicalModelElements ??= allModelElements.where((e) => e.isCanonical).toList()); } - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; - var definedNamesModelElements = element + var definedNamesModelElements = element! .exportNamespace.definedNames.values .map((v) => modelBuilder.fromElement(v)); - _referenceChildren.addEntries( + _referenceChildren!.addEntries( definedNamesModelElements.whereNotType().generateEntries()); /* Map.fromEntries( @@ -646,12 +638,12 @@ class Library extends ModelElement with Categorization, TopLevelContainer { // refer to hidden members via the prefix, because that can be // ambiguous. dart-lang/dartdoc#2683. for (var prefixEntry in prefixToLibrary.entries) { - if (!_referenceChildren.containsKey(prefixEntry.key)) { - _referenceChildren[prefixEntry.key] = prefixEntry.value.first; + if (!_referenceChildren!.containsKey(prefixEntry.key)) { + _referenceChildren![prefixEntry.key] = prefixEntry.value.first; } } } - return _referenceChildren; + return _referenceChildren!; } @override diff --git a/lib/src/model/library_container.dart b/lib/src/model/library_container.dart index 46c94593d5..4d3ee50689 100644 --- a/lib/src/model/library_container.dart +++ b/lib/src/model/library_container.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:collection/collection.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -21,7 +21,7 @@ abstract class LibraryContainer Iterable get publicLibraries => model_utils.filterNonPublic(libraries); - List _publicLibrariesSorted; + List? _publicLibrariesSorted; Iterable get publicLibrariesSorted => _publicLibrariesSorted ??= publicLibraries.toList()..sort(byName); @@ -32,10 +32,10 @@ abstract class LibraryContainer String get enclosingName; /// Order by which this container should be sorted. - List get containerOrder; + List get containerOrder; /// Sorting key. [containerOrder] should contain these. - String get sortKey => name; + String? get sortKey => name; /// Does this container represent the SDK? This can be false for containers /// that only represent a part of the SDK. @@ -49,9 +49,9 @@ abstract class LibraryContainer /// * 3 otherwise. int get _group { if (containerOrder.contains(sortKey)) return -1; - if (equalsIgnoreAsciiCase(sortKey, enclosingName)) return 0; + if (equalsIgnoreAsciiCase(sortKey!, enclosingName)) return 0; if (isSdk) return 1; - if (sortKey.toLowerCase().contains(enclosingName.toLowerCase())) return 2; + if (sortKey!.toLowerCase().contains(enclosingName.toLowerCase())) return 2; return 3; } @@ -62,7 +62,7 @@ abstract class LibraryContainer return Comparable.compare(containerOrder.indexOf(sortKey), containerOrder.indexOf(other.sortKey)); } else { - return sortKey.toLowerCase().compareTo(other.sortKey.toLowerCase()); + return sortKey!.toLowerCase().compareTo(other.sortKey!.toLowerCase()); } } return Comparable.compare(_group, other._group); diff --git a/lib/src/model/locatable.dart b/lib/src/model/locatable.dart index 94d03d1ae0..f7aea47f38 100644 --- a/lib/src/model/locatable.dart +++ b/lib/src/model/locatable.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart' show Element; @@ -12,11 +12,11 @@ abstract class Locatable { /// True if documentationFrom contains only one item, [this]. bool get documentationIsLocal => - documentationFrom.length == 1 && identical(documentationFrom.first, this); + documentationFrom!.length == 1 && identical(documentationFrom!.first, this); String get fullyQualifiedName; - String get href; + String? get href; /// A string indicating the URI of this Locatable, usually derived from /// [Element.location]. diff --git a/lib/src/model/method.dart b/lib/src/model/method.dart index 29a5757559..a461cc2839 100644 --- a/lib/src/model/method.dart +++ b/lib/src/model/method.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/source/line_info.dart'; @@ -17,60 +17,60 @@ class Method extends ModelElement with ContainerMember, Inheritable, TypeParameters implements EnclosedElement { bool _isInherited = false; - Container _enclosingContainer; + Container? _enclosingContainer; @override List typeParameters = []; - Method(MethodElement element, Library library, PackageGraph packageGraph) + Method(MethodElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph) { _calcTypeParameters(); } Method.inherited(MethodElement element, this._enclosingContainer, - Library library, PackageGraph packageGraph, - {ExecutableMember originalMember}) + Library? library, PackageGraph packageGraph, + {ExecutableMember? originalMember}) : super(element, library, packageGraph, originalMember) { _isInherited = true; _calcTypeParameters(); } void _calcTypeParameters() { - typeParameters = element.typeParameters.map((f) { - return modelBuilder.from(f, library) as TypeParameter; + typeParameters = element!.typeParameters.map((f) { + return modelBuilder.from(f, library!) as TypeParameter; }).toList(); } @override - CharacterLocation get characterLocation { + CharacterLocation? get characterLocation { if (enclosingElement is Enum && name == 'toString') { // The toString() method on Enums is special, treated as not having // a definition location by the analyzer yet not being inherited, either. // Just directly override our location with the Enum definition -- // this is OK because Enums can not inherit from each other nor // have their definitions split between files. - return enclosingElement.characterLocation; + return enclosingElement!.characterLocation; } return super.characterLocation; } @override - ModelElement get enclosingElement { + ModelElement? get enclosingElement { _enclosingContainer ??= - modelBuilder.from(element.enclosingElement, library); + modelBuilder.from(element!.enclosingElement, library!) as Container?; return _enclosingContainer; } @override String get filePath => - '${enclosingElement.library.dirName}/${enclosingElement.name}/$fileName'; + '${enclosingElement!.library!.dirName}/${enclosingElement!.name}/$fileName'; String get fullkind { - if (element.isAbstract) return 'abstract $kind'; + if (element!.isAbstract) return 'abstract $kind'; return kind; } @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -92,57 +92,57 @@ class Method extends ModelElement }; @override - bool get isStatic => element.isStatic; + bool get isStatic => element!.isStatic; @override String get kind => 'method'; @override - ExecutableMember get originalMember => super.originalMember; + ExecutableMember? get originalMember => super.originalMember as ExecutableMember?; - Callable _modelType; - Callable get modelType => _modelType ??= - modelBuilder.typeFrom((originalMember ?? element).type, library); + Callable? _modelType; + Callable get modelType => (_modelType ??= + modelBuilder.typeFrom((originalMember ?? element)!.type, library!) as Callable?)!; @override - Method get overriddenElement { + Method? get overriddenElement { if (_enclosingContainer is Extension) { return null; } - ClassElement parent = element.enclosingElement; + ClassElement parent = element!.enclosingElement as ClassElement; for (var t in parent.allSupertypes) { - Element e = t.getMethod(element.name); + Element? e = t.getMethod(element!.name); if (e != null) { assert(e.enclosingElement is ClassElement); - return modelBuilder.fromElement(e); + return modelBuilder.fromElement(e) as Method?; } } return null; } @override - MethodElement get element => super.element; + MethodElement? get element => super.element as MethodElement?; /// Methods can not be covariant; always returns false. @override bool get isCovariant => false; - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { - var from = documentationFrom.first as Method; + var from = documentationFrom!.first as Method; if (!identical(this, from)) { return from.referenceChildren; } if (_referenceChildren == null) { _referenceChildren = {}; - _referenceChildren.addEntriesIfAbsent([ + _referenceChildren!.addEntriesIfAbsent([ ...typeParameters.explicitOnCollisionWith(this), - ...allParameters.explicitOnCollisionWith(this), + ...allParameters!.explicitOnCollisionWith(this), ...modelType.typeArguments.explicitOnCollisionWith(this), ...modelType.returnType.typeArguments.explicitOnCollisionWith(this), ]); } - return _referenceChildren; + return _referenceChildren!; } } diff --git a/lib/src/model/mixin.dart b/lib/src/model/mixin.dart index b5252753dd..6ec530bcdd 100644 --- a/lib/src/model/mixin.dart +++ b/lib/src/model/mixin.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; @@ -13,17 +13,17 @@ import 'package:dartdoc/src/special_elements.dart'; /// Implements the Dart 2.1 "mixin" style of mixin declarations. class Mixin extends InheritingContainer with TypeImplementing { - Mixin(ClassElement element, Library library, PackageGraph packageGraph) + Mixin(ClassElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); - List _superclassConstraints; + List? _superclassConstraints; /// Returns a list of superclass constraints for this mixin. - Iterable get superclassConstraints { + Iterable? get superclassConstraints { _superclassConstraints ??= [ - ...element.superclassConstraints + ...element!.superclassConstraints .map( - (InterfaceType i) => modelBuilder.typeFrom(i, library)) + (InterfaceType i) => modelBuilder.typeFrom(i, library!) as ParameterizedElementType) .where((t) => t.modelElement != packageGraph.specialClasses[SpecialClass.object]) @@ -35,7 +35,7 @@ class Mixin extends InheritingContainer with TypeImplementing { publicSuperclassConstraints.isNotEmpty; Iterable get publicSuperclassConstraints => - model_utils.filterNonPublic(superclassConstraints); + model_utils.filterNonPublic(superclassConstraints!); @override bool get hasModifiers => super.hasModifiers || hasPublicSuperclassConstraints; @@ -46,29 +46,29 @@ class Mixin extends InheritingContainer with TypeImplementing { @override String get kind => 'mixin'; - List _inheritanceChain; + List? _inheritanceChain; @override - List get inheritanceChain { + List get inheritanceChain { if (_inheritanceChain == null) { _inheritanceChain = []; - _inheritanceChain.add(this); + _inheritanceChain!.add(this); // Mix-in interfaces come before other interfaces. - _inheritanceChain.addAll(superclassConstraints.expand( + _inheritanceChain!.addAll(superclassConstraints!.expand( (ParameterizedElementType i) => (i.modelElement as InheritingContainer).inheritanceChain)); for (var c in superChain.map((e) => (e.modelElement as InheritingContainer))) { - _inheritanceChain.addAll(c.inheritanceChain); + _inheritanceChain!.addAll(c.inheritanceChain); } /// Interfaces need to come last, because classes in the superChain might /// implement them even when they aren't mentioned. - _inheritanceChain.addAll(interfaces.expand( + _inheritanceChain!.addAll(interfaces.expand( (e) => (e.modelElement as InheritingContainer).inheritanceChain)); } - return _inheritanceChain.toList(growable: false); + return _inheritanceChain!.toList(growable: false); } } diff --git a/lib/src/model/model.dart b/lib/src/model/model.dart index c4507e8ddb..e84c726640 100644 --- a/lib/src/model/model.dart +++ b/lib/src/model/model.dart @@ -2,7 +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. -// @dart=2.9 + export 'accessor.dart'; export 'canonicalization.dart'; diff --git a/lib/src/model/model_element.dart b/lib/src/model/model_element.dart index b9e9b9a07d..fec684dc3c 100644 --- a/lib/src/model/model_element.dart +++ b/lib/src/model/model_element.dart @@ -2,7 +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. -// @dart=2.9 + /// The models used to represent Dart code. library dartdoc.models; @@ -42,22 +42,22 @@ import 'package:path/path.dart' as path show Context; /// the inheritance and interface chains from the analyzer. ModelElement resolveMultiplyInheritedElement( MultiplyInheritedExecutableElement e, - Library library, + Library? library, PackageGraph packageGraph, Class enclosingClass) { var inheritables = e.inheritedElements .map((ee) => ModelElement._fromElement(ee, packageGraph) as Inheritable); - Inheritable foundInheritable; + late Inheritable foundInheritable; var lowIndex = enclosingClass.inheritanceChain.length; for (var inheritable in inheritables) { var index = - enclosingClass.inheritanceChain.indexOf(inheritable.enclosingElement); + enclosingClass.inheritanceChain.indexOf(inheritable.enclosingElement as InheritingContainer?); if (index < lowIndex) { foundInheritable = inheritable; lowIndex = index; } } - return ModelElement._from(foundInheritable.element, library, packageGraph, + return ModelElement._from(foundInheritable.element!, library, packageGraph, enclosingContainer: enclosingClass); } @@ -66,7 +66,7 @@ mixin ModelElementBuilderImpl implements ModelElementBuilder { @override ModelElement from(Element e, Library library, - {Container enclosingContainer}) => + {Container? enclosingContainer}) => ModelElement._from(e, library, packageGraph, enclosingContainer: enclosingContainer); @@ -76,8 +76,8 @@ mixin ModelElementBuilderImpl implements ModelElementBuilder { @override ModelElement fromPropertyInducingElement(Element e, Library l, - {Container enclosingContainer, Accessor getter, Accessor setter}) => - ModelElement._fromPropertyInducingElement(e, l, packageGraph, + {Container? enclosingContainer, Accessor? getter, Accessor? setter}) => + ModelElement._fromPropertyInducingElement(e as PropertyInducingElement, l, packageGraph, enclosingContainer: enclosingContainer, getter: getter, setter: setter); @@ -124,14 +124,14 @@ abstract class ModelElement extends Canonicalization DocumentationComment, ModelBuilder implements Comparable, Documentable { - final Element _element; + final Element? _element; // TODO(jcollins-g): This really wants a "member that has a type" class. - final Member /*?*/ _originalMember; - final Library /*?*/ _library; + final Member? _originalMember; + final Library? _library; + - UnmodifiableListView _parameters; - String _linkedName; + String? _linkedName; ModelElement(this._element, this._library, this._packageGraph, [this._originalMember]); @@ -141,11 +141,11 @@ abstract class ModelElement extends Canonicalization var lib = p.findButDoNotCreateLibraryFor(e); if (e is PropertyInducingElement) { var getter = - e.getter != null ? ModelElement._from(e.getter, lib, p) : null; + e.getter != null ? ModelElement._from(e.getter!, lib, p) : null; var setter = - e.setter != null ? ModelElement._from(e.setter, lib, p) : null; - return ModelElement._fromPropertyInducingElement(e, lib, p, - getter: getter, setter: setter); + e.setter != null ? ModelElement._from(e.setter!, lib, p) : null; + return ModelElement._fromPropertyInducingElement(e, lib!, p, + getter: getter as Accessor?, setter: setter as Accessor?); } return ModelElement._from(e, lib, p); } @@ -157,9 +157,9 @@ abstract class ModelElement extends Canonicalization /// if and only if this is to be an inherited or extended object. factory ModelElement._fromPropertyInducingElement( PropertyInducingElement e, Library library, PackageGraph packageGraph, - {Container enclosingContainer, - @required Accessor getter, - @required Accessor setter}) { + {Container? enclosingContainer, + required Accessor? getter, + required Accessor? setter}) { assert(packageGraph != null); assert(e != null); assert(library != null); @@ -167,30 +167,30 @@ abstract class ModelElement extends Canonicalization // TODO(jcollins-g): Refactor object model to instantiate 'ModelMembers' // for members? if (e is Member) { - e = e.declaration; + e = e.declaration as PropertyInducingElement; } // Return the cached ModelElement if it exists. var key = - Tuple3(e, library, enclosingContainer); + Tuple3(e, library, enclosingContainer); if (packageGraph.allConstructedModelElements.containsKey(key)) { - return packageGraph.allConstructedModelElements[key]; + return packageGraph.allConstructedModelElements[key]!; } - ModelElement newModelElement; + ModelElement? newModelElement; if (e is FieldElement) { if (enclosingContainer == null) { if (e.isEnumConstant) { - var index = e.computeConstantValue().getField(e.name).toIntValue(); + var index = e.computeConstantValue()!.getField(e.name)!.toIntValue(); newModelElement = EnumField.forConstant(index, e, library, packageGraph, getter); } else if (e.enclosingElement is ExtensionElement) { - newModelElement = Field(e, library, packageGraph, getter, setter); + newModelElement = Field(e, library, packageGraph, getter as ContainerAccessor?, setter as ContainerAccessor?); } else if (e.enclosingElement is ClassElement && (e.enclosingElement as ClassElement).isEnum) { newModelElement = EnumField(e, library, packageGraph, getter, setter); } else { - newModelElement = Field(e, library, packageGraph, getter, setter); + newModelElement = Field(e, library, packageGraph, getter as ContainerAccessor?, setter as ContainerAccessor?); } } else { // EnumFields can't be inherited, so this case is simpler. @@ -208,8 +208,8 @@ abstract class ModelElement extends Canonicalization _cacheNewModelElement(e, newModelElement, library, enclosingContainer: enclosingContainer); - assert(newModelElement.element is! MultiplyInheritedExecutableElement); - return newModelElement; + assert(newModelElement!.element is! MultiplyInheritedExecutableElement); + return newModelElement!; } /// Creates a [ModelElement] from a non-property-inducing [e]. @@ -224,8 +224,8 @@ abstract class ModelElement extends Canonicalization // TODO(jcollins-g): Auto-vivify element's defining library for library // parameter when given a null. factory ModelElement._from( - Element e, Library library, PackageGraph packageGraph, - {Container enclosingContainer}) { + Element e, Library? library, PackageGraph packageGraph, + {Container? enclosingContainer}) { assert(packageGraph != null); assert(e != null); assert(library != null || @@ -242,7 +242,7 @@ abstract class ModelElement extends Canonicalization return NeverType(e, packageGraph); } - Member originalMember; + Member? originalMember; // TODO(jcollins-g): Refactor object model to instantiate 'ModelMembers' // for members? if (e is Member) { @@ -252,13 +252,13 @@ abstract class ModelElement extends Canonicalization // Return the cached ModelElement if it exists. var key = - Tuple3(e, library, enclosingContainer); + Tuple3(e, library, enclosingContainer); if (packageGraph.allConstructedModelElements.containsKey(key)) { - return packageGraph.allConstructedModelElements[key]; + return packageGraph.allConstructedModelElements[key as Tuple3]!; } var newModelElement = ModelElement._fromParameters(e, library, packageGraph, - enclosingContainer: enclosingContainer, originalMember: originalMember); + enclosingContainer: enclosingContainer, originalMember: originalMember)!; if (enclosingContainer != null) assert(newModelElement is Inheritable); _cacheNewModelElement(e, newModelElement, library, @@ -271,13 +271,13 @@ abstract class ModelElement extends Canonicalization /// Caches a newly-created [ModelElement] from [ModelElement._from] or /// [ModelElement._fromPropertyInducingElement]. static void _cacheNewModelElement( - Element e, ModelElement newModelElement, Library library, - {Container enclosingContainer}) { + Element e, ModelElement? newModelElement, Library? library, + {Container? enclosingContainer}) { // TODO(jcollins-g): Reenable Parameter caching when dart-lang/sdk#30146 // is fixed? if (library != null && newModelElement is! Parameter) { var key = - Tuple3(e, library, enclosingContainer); + Tuple3(e, library, enclosingContainer); library.packageGraph.allConstructedModelElements[key] = newModelElement; if (newModelElement is Inheritable) { var iKey = Tuple2(e, library); @@ -288,12 +288,12 @@ abstract class ModelElement extends Canonicalization } } - static ModelElement _fromParameters( - Element e, Library library, PackageGraph packageGraph, - {Container enclosingContainer, Member originalMember}) { + static ModelElement? _fromParameters( + Element e, Library? library, PackageGraph packageGraph, + {Container? enclosingContainer, Member? originalMember}) { if (e is MultiplyInheritedExecutableElement) { return resolveMultiplyInheritedElement( - e, library, packageGraph, enclosingContainer); + e, library, packageGraph, enclosingContainer as Class); } assert(e is! MultiplyDefinedElement); if (e is LibraryElement) { @@ -312,13 +312,13 @@ abstract class ModelElement extends Canonicalization } } if (e is ExtensionElement) { - return Extension(e, library, packageGraph); + return Extension(e, library!, packageGraph); } if (e is FunctionElement) { return ModelFunction(e, library, packageGraph); } else if (e is GenericFunctionTypeElement) { assert(e.enclosingElement is TypeAliasElement); - assert(e.enclosingElement.name != ''); + assert(e.enclosingElement!.name != ''); return ModelFunctionTypedef(e, library, packageGraph); } if (e is TypeAliasElement) { @@ -346,7 +346,7 @@ abstract class ModelElement extends Canonicalization return Method(e, library, packageGraph); } else { return Method.inherited(e, enclosingContainer, library, packageGraph, - originalMember: originalMember); + originalMember: originalMember as ExecutableMember?); } } if (e is PropertyAccessorElement) { @@ -360,7 +360,7 @@ abstract class ModelElement extends Canonicalization assert(e.enclosingElement is! ExtensionElement); return ContainerAccessor.inherited( e, library, packageGraph, enclosingContainer, - originalMember: originalMember); + originalMember: originalMember as ExecutableMember?); } } else { return Accessor(e, library, packageGraph); @@ -371,7 +371,7 @@ abstract class ModelElement extends Canonicalization } if (e is ParameterElement) { return Parameter(e, library, packageGraph, - originalMember: originalMember); + originalMember: originalMember as ParameterMember?); } throw 'Unknown type ${e.runtimeType}'; } @@ -381,67 +381,65 @@ abstract class ModelElement extends Canonicalization bool get hasCategoryNames => false; // Stub for mustache. - Iterable get displayedCategories => []; + Iterable? get displayedCategories => []; - Set get exportedInLibraries { - return library.packageGraph.libraryElementReexportedBy[element.library]; + Set? get exportedInLibraries { + return library!.packageGraph.libraryElementReexportedBy[element!.library!]; } - ModelNode _modelNode; + ModelNode? _modelNode; @override - ModelNode get modelNode => + ModelNode? get modelNode => _modelNode ??= packageGraph.getModelNodeFor(element); - Iterable _annotations; + Iterable? _annotations; // Skips over annotations with null elements or that are otherwise // supposed to be invisible (@pragma). While technically, null elements // indicate invalid code from analyzer's perspective they are present in // sky_engine (@Native) so we don't want to crash here. - Iterable get annotations => _annotations ??= element.metadata + Iterable get annotations => _annotations ??= element!.metadata .whereNot((m) => m.element == null || - packageGraph.specialClasses[SpecialClass.pragma].element.constructors + packageGraph.specialClasses[SpecialClass.pragma]!.element!.constructors .contains(m.element)) .map((m) => Annotation(m, library, packageGraph)); - bool _isPublic; @override - bool get isPublic { - if (_isPublic == null) { + late final bool isPublic = () { if (name == '') { - _isPublic = false; - } else if (this is! Library && (library == null || !library.isPublic)) { - _isPublic = false; - } else if (enclosingElement is Class && - !(enclosingElement as Class).isPublic) { - _isPublic = false; - } else if (enclosingElement is Extension && - !(enclosingElement as Extension).isPublic) { - _isPublic = false; - } else { - _isPublic = utils.hasPublicName(element) && !hasNodoc; + return false; } - } - return _isPublic; - } + if (this is! Library && (library == null || !library!.isPublic)) { + return false; + } + if (enclosingElement is Class && + !(enclosingElement as Class).isPublic!) { + return false; + } + if (enclosingElement is Extension && + !(enclosingElement as Extension).isPublic!) { + return false; + } + return utils.hasPublicName(element!) && !hasNodoc!; + } (); - Map _commentRefs; + Map? _commentRefs; @override - Map get commentRefs { + Map? get commentRefs { if (_commentRefs == null) { _commentRefs = {}; - for (var from in documentationFrom) { - var checkReferences = [from]; + for (var from in documentationFrom!) { + var checkReferences = [from as ModelElement?]; if (from is Accessor) { checkReferences.add(from.enclosingCombo); } for (var e in checkReferences) { // Some elements don't have modelNodes or aren't traversed by // the element visitor, or both. - assert(e is Parameter || e.modelNode != null); - _commentRefs.addAll({ - for (var r in e.modelNode?.commentRefs ?? []) + assert(e is Parameter || e!.modelNode != null); + _commentRefs!.addAll({ + for (var r in e!.modelNode?.commentRefs ?? []) r.codeRef: r }); } @@ -450,20 +448,20 @@ abstract class ModelElement extends Canonicalization return _commentRefs; } - DartdocOptionContext _config; + DartdocOptionContext? _config; @override - DartdocOptionContext get config { + DartdocOptionContext? get config { _config ??= DartdocOptionContext.fromContextElement( - packageGraph.config, library.element, packageGraph.resourceProvider); + packageGraph.config, library!.element!, packageGraph.resourceProvider); return _config; } - Set _locationPieces; + Set? _locationPieces; @override Set get locationPieces => - _locationPieces ??= Set.from(element.location + _locationPieces ??= Set.from(element!.location .toString() .split(locationSplitter) .where((s) => s.isNotEmpty)); @@ -501,63 +499,63 @@ abstract class ModelElement extends Canonicalization (element is TypeAliasElement && (element as TypeAliasElement).aliasedElement is FunctionTypedElement); - ModelElement buildCanonicalModelElement() { - Container preferredClass; + ModelElement? buildCanonicalModelElement() { + Container? preferredClass; if (enclosingElement is Class || enclosingElement is Extension) { - preferredClass = enclosingElement; + preferredClass = enclosingElement as Container?; } return packageGraph.findCanonicalModelElementFor(element, preferredClass: preferredClass); } - ModelElement _canonicalModelElement; + ModelElement? _canonicalModelElement; // Returns the canonical ModelElement for this ModelElement, or null // if there isn't one. - ModelElement get canonicalModelElement => + ModelElement? get canonicalModelElement => _canonicalModelElement ??= buildCanonicalModelElement(); - bool get hasSourceHref => sourceHref.isNotEmpty; - String _sourceHref; + bool get hasSourceHref => sourceHref!.isNotEmpty; + String? _sourceHref; - String get sourceHref { + String? get sourceHref { _sourceHref ??= SourceLinker.fromElement(this).href(); return _sourceHref; } Library get definingLibrary { - Library library = modelBuilder.fromElement(element.library); + Library library = modelBuilder.fromElement(element!.library!) as Library; if (library == null) { warn(PackageWarning.noDefiningLibraryFound); } return library; } - Library _canonicalLibrary; + Library? _canonicalLibrary; // [_canonicalLibrary] can be null so we can't check against null to see // whether we tried to compute it before. bool _canonicalLibraryIsSet = false; @override - Library get canonicalLibrary { + Library? get canonicalLibrary { if (!_canonicalLibraryIsSet) { // This is not accurate if we are constructing the Package. assert(packageGraph.allLibrariesAdded); // Privately named elements can never have a canonical library, so // just shortcut them out. - if (!utils.hasPublicName(element)) { + if (!utils.hasPublicName(element!)) { _canonicalLibrary = null; - } else if (!packageGraph.localPublicLibraries.contains(definingLibrary)) { + } else if (!packageGraph.localPublicLibraries!.contains(definingLibrary)) { _canonicalLibrary = _searchForCanonicalLibrary(); } else { _canonicalLibrary = definingLibrary; } // Only pretend when not linking to remote packages. - if (this is Inheritable && !config.linkToRemote) { + if (this is Inheritable && !config!.linkToRemote) { if ((this as Inheritable).isInherited && _canonicalLibrary == null && - packageGraph.publicLibraries.contains(library)) { + packageGraph.publicLibraries!.contains(library)) { // In the event we've inherited a field from an object that isn't // directly reexported, we may need to pretend we are canonical for // this. @@ -567,11 +565,11 @@ abstract class ModelElement extends Canonicalization _canonicalLibraryIsSet = true; } assert(_canonicalLibrary == null || - packageGraph.publicLibraries.contains(_canonicalLibrary)); + packageGraph.publicLibraries!.contains(_canonicalLibrary)); return _canonicalLibrary; } - Library _searchForCanonicalLibrary() { + Library? _searchForCanonicalLibrary() { if (definingLibrary == null) { return null; } @@ -596,9 +594,9 @@ abstract class ModelElement extends Canonicalization l.isPublic && l.package.documentedWhere != DocumentLocation.missing) .where((l) { var lookup = - l.element.exportNamespace.definedNames[topLevelElement?.name]; + l.element!.exportNamespace.definedNames[topLevelElement?.name!]; if (lookup is PropertyAccessorElement) { - lookup = (lookup as PropertyAccessorElement).variable; + lookup = lookup.variable; } return topLevelElement == lookup; }).toList(); @@ -624,7 +622,7 @@ abstract class ModelElement extends Canonicalization } // Start with our top-level element. - var warnable = ModelElement._fromElement(topLevelElement, packageGraph); + var warnable = ModelElement._fromElement(topLevelElement!, packageGraph); // Heuristic scoring to determine which library a human likely // considers this element to be primarily 'from', and therefore, // canonical. Still warn if the heuristic isn't that confident. @@ -636,7 +634,7 @@ abstract class ModelElement extends Canonicalization var highestScore = scoredCandidates.last.score; var confidence = highestScore - secondHighestScore; - if (confidence < config.ambiguousReexportScorerMinConfidence) { + if (confidence < config!.ambiguousReexportScorerMinConfidence) { var libraryNames = candidateLibraries.map((l) => l.name); var message = '$libraryNames -> ${candidateLibraries.last.name} ' '(confidence ${confidence.toStringAsPrecision(4)})'; @@ -649,7 +647,7 @@ abstract class ModelElement extends Canonicalization @override bool get isCanonical { - if (!isPublic) return false; + if (!isPublic!) return false; if (library != canonicalLibrary) return false; // If there's no inheritance to deal with, we're done. if (this is! Inheritable) return true; @@ -664,11 +662,11 @@ abstract class ModelElement extends Canonicalization @override String get documentation { return injectMacros( - documentationFrom.map((e) => e.documentationLocal).join('

')); + documentationFrom!.map((e) => e.documentationLocal).join('

')); } @override - Element get element => _element; + Element? get element => _element; @override String get location { @@ -694,9 +692,9 @@ abstract class ModelElement extends Canonicalization String get fileType => package.fileType; - String get filePath; + String? get filePath; - String _fullyQualifiedName; + String? _fullyQualifiedName; /// Returns the fully qualified name. /// @@ -706,39 +704,39 @@ abstract class ModelElement extends Canonicalization return (_fullyQualifiedName ??= _buildFullyQualifiedName()); } - String _fullyQualifiedNameWithoutLibrary; + String? _fullyQualifiedNameWithoutLibrary; @override - String get fullyQualifiedNameWithoutLibrary { + String? get fullyQualifiedNameWithoutLibrary { // Remember, periods are legal in library names. _fullyQualifiedNameWithoutLibrary ??= - fullyQualifiedName.replaceFirst('${library.fullyQualifiedName}.', ''); + fullyQualifiedName.replaceFirst('${library!.fullyQualifiedName}.', ''); return _fullyQualifiedNameWithoutLibrary; } @override - String get sourceFileName => element.source.fullName; + String get sourceFileName => element!.source!.fullName; - CharacterLocation _characterLocation; + CharacterLocation? _characterLocation; bool _characterLocationIsSet = false; @override - CharacterLocation get characterLocation { + CharacterLocation? get characterLocation { if (!_characterLocationIsSet) { - var lineInfo = compilationUnitElement.lineInfo; + var lineInfo = compilationUnitElement!.lineInfo!; _characterLocationIsSet = true; - assert(element.nameOffset >= 0, + assert(element!.nameOffset >= 0, 'Invalid location data for element: $fullyQualifiedName'); assert(lineInfo != null, 'No lineInfo data available for element: $fullyQualifiedName'); - if (element.nameOffset >= 0) { - _characterLocation = lineInfo?.getLocation(element.nameOffset); + if (element!.nameOffset >= 0) { + _characterLocation = lineInfo?.getLocation(element!.nameOffset); } } return _characterLocation; } - CompilationUnitElement get compilationUnitElement => - element.thisOrAncestorOfType(); + CompilationUnitElement? get compilationUnitElement => + element!.thisOrAncestorOfType(); bool get hasAnnotations => annotations.isNotEmpty; @@ -747,16 +745,16 @@ abstract class ModelElement extends Canonicalization @override bool get hasExtendedDocumentation => - href != null && elementDocumentation.hasExtendedDocs; + href != null && elementDocumentation.hasExtendedDocs!; - bool get hasParameters => parameters.isNotEmpty; + bool get hasParameters => parameters!.isNotEmpty; /// If canonicalLibrary (or canonicalEnclosingElement, for Inheritable /// subclasses) is null, href should be null. @override - String get href; + String? get href; - String get htmlId => name; + String? get htmlId => name; bool get isAsynchronous => isExecutable && (element as ExecutableElement).isAsynchronous; @@ -766,7 +764,7 @@ abstract class ModelElement extends Canonicalization bool get isDeprecated { // If element.metadata is empty, it might be because this is a property // where the metadata belongs to the individual getter/setter - if (element.metadata.isEmpty && element is PropertyInducingElement) { + if (element!.metadata.isEmpty && element is PropertyInducingElement) { var pie = element as PropertyInducingElement; // The getter or the setter might be null – so the stored value may be @@ -782,13 +780,13 @@ abstract class ModelElement extends Canonicalization // If there are both a setter and getter, only show the property as // deprecated if both are deprecated. - return deprecatedValues.every((d) => d); + return deprecatedValues.every((d) => d!); } - return element.metadata.any((a) => a.isDeprecated); + return element!.metadata.any((a) => a.isDeprecated); } @override - bool get isDocumented => isCanonical && isPublic; + bool get isDocumented => isCanonical && isPublic!; bool get isExecutable => element is ExecutableElement; @@ -816,7 +814,7 @@ abstract class ModelElement extends Canonicalization @override Library get library => _library; - String get linkedName { + String? get linkedName { _linkedName ??= _calculateLinkedName(); return _linkedName; } @@ -835,26 +833,24 @@ abstract class ModelElement extends Canonicalization SourceCodeRenderer get _sourceCodeRenderer => packageGraph.rendererFactory.sourceCodeRenderer; - String get linkedParams => _parameterRenderer.renderLinkedParams(parameters); + String get linkedParams => _parameterRenderer.renderLinkedParams(parameters!); String get linkedParamsLines => - _parameterRendererDetailed.renderLinkedParams(parameters).trim(); + _parameterRendererDetailed.renderLinkedParams(parameters!).trim(); - String get linkedParamsNoMetadata => - _parameterRenderer.renderLinkedParams(parameters, showMetadata: false); + String? get linkedParamsNoMetadata => + _parameterRenderer.renderLinkedParams(parameters!, showMetadata: false); String get linkedParamsNoMetadataOrNames => _parameterRenderer - .renderLinkedParams(parameters, showMetadata: false, showNames: false); - - String _name; + .renderLinkedParams(parameters!, showMetadata: false, showNames: false); @override - String get name => _name ??= element.name; + String get name => element!.name!; @override - String get oneLineDoc => elementDocumentation.asOneLiner; + String? get oneLineDoc => elementDocumentation.asOneLiner; - Member get originalMember => _originalMember; + Member? get originalMember => _originalMember; final PackageGraph _packageGraph; @@ -864,21 +860,21 @@ abstract class ModelElement extends Canonicalization @override Package get package => library?.package; - bool get isPublicAndPackageDocumented => isPublic && package.isDocumented; + bool get isPublicAndPackageDocumented => isPublic! && package.isDocumented; - List _allParameters; + List? _allParameters; // TODO(jcollins-g): This is in the wrong place. Move parts to // [GetterSetterCombo], elsewhere as appropriate? - List get allParameters { + List? get allParameters { if (_allParameters == null) { var recursedParameters = {}; var newParameters = {}; if (this is GetterSetterCombo && (this as GetterSetterCombo).setter != null) { - newParameters.addAll((this as GetterSetterCombo).setter.parameters); + newParameters.addAll((this as GetterSetterCombo).setter!.parameters!); } else { - if (isCallable) newParameters.addAll(parameters); + if (isCallable) newParameters.addAll(parameters!); } // TODO(jcollins-g): This part probably belongs in [ElementType]. while (newParameters.isNotEmpty) { @@ -904,61 +900,58 @@ abstract class ModelElement extends Canonicalization @override path.Context get pathContext => packageGraph.resourceProvider.pathContext; - List get parameters { + late final List parameters = () { if (!isCallable) { throw StateError( '$element (${element.runtimeType}) cannot have parameters'); } - if (_parameters == null) { - List params; - - if (element is TypeAliasElement) { - _parameters = ModelElement._fromElement( - (element as TypeAliasElement).aliasedElement, packageGraph) - .parameters; + if (element is TypeAliasElement) { + return ModelElement._fromElement( + (element as TypeAliasElement).aliasedElement!, packageGraph) + .parameters; + } + List? params; + if (element is ExecutableElement) { + if (_originalMember != null) { + assert(_originalMember is ExecutableMember); + params = (_originalMember as ExecutableMember).parameters; } else { - if (element is ExecutableElement) { - if (_originalMember != null) { - assert(_originalMember is ExecutableMember); - params = (_originalMember as ExecutableMember).parameters; - } else { - params = (element as ExecutableElement).parameters; - } - } - if (params == null && element is FunctionTypedElement) { - if (_originalMember != null) { - params = (_originalMember as FunctionTypedElement).parameters; - } else { - params = (element as FunctionTypedElement).parameters; - } - } - _parameters = UnmodifiableListView(params - .map((p) => - ModelElement._from(p, library, packageGraph) as Parameter) - .toList(growable: false)); + params = (element as ExecutableElement).parameters; } } - return _parameters; - } + if (params == null && element is FunctionTypedElement) { + if (_originalMember != null) { + params = (_originalMember as FunctionTypedElement).parameters; + } else { + params = (element as FunctionTypedElement).parameters; + } + } + + return [ + ...params! + .map((p) => + ModelElement._from(p, library, packageGraph) as Parameter) + ]; + } (); @override - String /*!*/ get documentationComment => element.documentationComment ?? ''; + String get documentationComment => element!.documentationComment ?? ''; @override - bool get hasDocumentationComment => element.documentationComment != null; + bool get hasDocumentationComment => element!.documentationComment != null; - String _sourceCode; + String? _sourceCode; @override - String get sourceCode { + String? get sourceCode { return _sourceCode ??= - _sourceCodeRenderer.renderSourceCode(super.sourceCode); + _sourceCodeRenderer.renderSourceCode(super.sourceCode!); } @override int compareTo(dynamic other) { if (other is ModelElement) { - return name.toLowerCase().compareTo(other.name.toLowerCase()); + return name!.toLowerCase().compareTo(other.name!.toLowerCase()); } else { return 0; } @@ -967,22 +960,22 @@ abstract class ModelElement extends Canonicalization @override String toString() => '$runtimeType $name'; - String _buildFullyQualifiedName([ModelElement e, String fqName]) { + String _buildFullyQualifiedName([ModelElement? e, String? fqName]) { e ??= this; fqName ??= e.name; if (e is! EnclosedElement || e.enclosingElement == null) { - return fqName; + return fqName!; } return _buildFullyQualifiedName( - e.enclosingElement, '${e.enclosingElement.name}.$fqName'); + e.enclosingElement as ModelElement?, '${e.enclosingElement!.name}.$fqName'); } String _calculateLinkedName() { // If we're calling this with an empty name, we probably have the wrong // element associated with a ModelElement or there's an analysis bug. - assert(name.isNotEmpty || + assert(name!.isNotEmpty || element?.kind == ElementKind.DYNAMIC || element?.kind == ElementKind.NEVER || this is ModelFunction); @@ -991,7 +984,7 @@ abstract class ModelElement extends Canonicalization if (isPublicAndPackageDocumented) { warn(PackageWarning.noCanonicalFound); } - return htmlEscape.convert(name); + return htmlEscape.convert(name!); } return modelElementRenderer.renderLinkedName(this); @@ -1001,5 +994,5 @@ abstract class ModelElement extends Canonicalization @override CommentReferable get definingCommentReferable => element == null ? super.definingCommentReferable - : modelBuilder.fromElement(element); + : modelBuilder.fromElement(element!); } diff --git a/lib/src/model/model_function.dart b/lib/src/model/model_function.dart index c614c72b26..d53931f43a 100644 --- a/lib/src/model/model_function.dart +++ b/lib/src/model/model_function.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; @@ -12,51 +12,51 @@ import 'package:dartdoc/src/model/model.dart'; /// A [ModelElement] for a [FunctionElement] that isn't part of a type definition. class ModelFunction extends ModelFunctionTyped with Categorization { ModelFunction( - FunctionElement element, Library library, PackageGraph packageGraph) + FunctionElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); @override - bool get isStatic => element.isStatic; + bool get isStatic => element!.isStatic; @override - String get name => element.name ?? ''; + String get name => element!.name ?? ''; @override - FunctionElement get element => super.element; + FunctionElement? get element => super.element as FunctionElement?; } /// A [ModelElement] for a [FunctionTypedElement] that is part of an /// explicit typedef. class ModelFunctionTypedef extends ModelFunctionTyped { ModelFunctionTypedef( - FunctionTypedElement element, Library library, PackageGraph packageGraph) + FunctionTypedElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); @override - String get name => element.enclosingElement.name; + String? get name => element!.enclosingElement!.name; } class ModelFunctionTyped extends ModelElement with TypeParameters implements EnclosedElement { - List _typeParameters; + List? _typeParameters; @override List get typeParameters => _typeParameters ??= [ - for (var p in element.typeParameters) modelBuilder.from(p, library), + for (var p in element!.typeParameters) modelBuilder.from(p, library!) as TypeParameter, ]; ModelFunctionTyped( - FunctionTypedElement element, Library library, PackageGraph packageGraph) + FunctionTypedElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); @override - ModelElement get enclosingElement => library; + ModelElement? get enclosingElement => library; @override - String get filePath => '${library.dirName}/$fileName'; + String get filePath => '${library!.dirName}/$fileName'; @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -71,26 +71,26 @@ class ModelFunctionTyped extends ModelElement // Food for mustache. TODO(jcollins-g): what about enclosing elements? bool get isInherited => false; - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; - _referenceChildren + _referenceChildren! .addEntriesIfAbsent(typeParameters.explicitOnCollisionWith(this)); - _referenceChildren - .addEntriesIfAbsent(parameters.explicitOnCollisionWith(this)); + _referenceChildren! + .addEntriesIfAbsent(parameters!.explicitOnCollisionWith(this)); } - return _referenceChildren; + return _referenceChildren!; } @override Iterable get referenceParents => [definingLibrary]; @override - FunctionTypedElement get element => super.element; + FunctionTypedElement? get element => super.element as FunctionTypedElement?; - Callable _modelType; + Callable? _modelType; Callable get modelType => - _modelType ??= modelBuilder.typeFrom(element.type, library); + (_modelType ??= modelBuilder.typeFrom(element!.type, library!) as Callable?)!; } diff --git a/lib/src/model/model_node.dart b/lib/src/model/model_node.dart index dbd48274b1..3c0cbb86c7 100644 --- a/lib/src/model/model_node.dart +++ b/lib/src/model/model_node.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; @@ -17,27 +17,27 @@ class ModelNode { final Element element; final ResourceProvider resourceProvider; - final AstNode _sourceNode; + final AstNode? _sourceNode; - ModelNode(AstNode sourceNode, this.element, this.resourceProvider) + ModelNode(AstNode? sourceNode, this.element, this.resourceProvider) : _sourceNode = sourceNode, commentRefs = _commentRefsFor(sourceNode, resourceProvider); static List _commentRefsFor( - AstNode node, ResourceProvider resourceProvider) { + AstNode? node, ResourceProvider resourceProvider) { if (node is AnnotatedNode && node?.documentationComment?.references != null) { return [ - for (var m in node.documentationComment.references) + for (var m in node.documentationComment!.references) ModelCommentReference(m, resourceProvider), ]; } return []; } - String _sourceCode; + String? _sourceCode; - String get sourceCode { + String? get sourceCode { if (_sourceCode == null) { if (_sourceNode?.offset != null) { var enclosingSourceNode = _sourceNode; @@ -46,12 +46,12 @@ class ModelNode { /// In this case, it is either a [FieldDeclaration] or /// [TopLevelVariableDeclaration]. (#2401) if (_sourceNode is VariableDeclaration) { - enclosingSourceNode = _sourceNode.parent.parent; + enclosingSourceNode = _sourceNode!.parent!.parent; assert(enclosingSourceNode is FieldDeclaration || enclosingSourceNode is TopLevelVariableDeclaration); } - var sourceEnd = enclosingSourceNode.end; + var sourceEnd = enclosingSourceNode!.end; var sourceOffset = enclosingSourceNode.offset; var contents = @@ -60,7 +60,7 @@ class ModelNode { var i = sourceOffset; while (i > 0) { i -= 1; - if (contents[i] == '\n' || contents[i] == '\r') { + if (contents![i] == '\n' || contents[i] == '\r') { i += 1; break; } @@ -68,7 +68,7 @@ class ModelNode { // Trim the common indent from the source snippet. var start = sourceOffset - (sourceOffset - i); - var source = contents.substring(start, sourceEnd); + var source = contents!.substring(start, sourceEnd); source = model_utils.stripIndentFromSource(source); source = model_utils.stripDartdocCommentsFromSource(source); diff --git a/lib/src/model/nameable.dart b/lib/src/model/nameable.dart index 8843244534..e513b35a16 100644 --- a/lib/src/model/nameable.dart +++ b/lib/src/model/nameable.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:collection/collection.dart'; @@ -15,30 +15,30 @@ abstract class Nameable { String get fullyQualifiedName => name; - Set _namePieces; - Set get namePieces { + Set? _namePieces; + Set? get namePieces { _namePieces ??= { - ...name.split(locationSplitter).where((s) => s.isNotEmpty) + ...name!.split(locationSplitter).where((s) => s.isNotEmpty) }; return _namePieces; } - String _namePart; + String? _namePart; /// Utility getter/cache for `_MarkdownCommentReference._getResultsForClass`. - String get namePart { + String? get namePart { // TODO(jcollins-g): This should really be the same as 'name', but isn't // because of accessors and operators. - _namePart ??= fullyQualifiedName.split('.').last; + _namePart ??= fullyQualifiedName!.split('.').last; return _namePart; } @override - String toString() => name; + String toString() => name!; } int byName(Nameable a, Nameable b) { - var stringCompare = compareAsciiLowerCaseNatural(a.name, b.name); + var stringCompare = compareAsciiLowerCaseNatural(a.name!, b.name!); if (stringCompare == 0) { return a.hashCode.compareTo(b.hashCode); } diff --git a/lib/src/model/never.dart b/lib/src/model/never.dart index ad67fa774e..9c6b2ba255 100644 --- a/lib/src/model/never.dart +++ b/lib/src/model/never.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; @@ -15,7 +15,7 @@ class NeverType extends ModelElement { /// `Never` is not a real object, and so we can't document it, so there /// can be nothing canonical for it. @override - ModelElement get canonicalModelElement => null; + ModelElement? get canonicalModelElement => null; @override ModelElement get enclosingElement => throw UnsupportedError(''); @@ -23,7 +23,7 @@ class NeverType extends ModelElement { /// And similarly, even if someone references it directly it can have /// no hyperlink. @override - String get href => null; + String? get href => null; @override String get kind => 'Never'; @@ -32,7 +32,7 @@ class NeverType extends ModelElement { String get linkedName => 'Never'; @override - String get filePath => null; + String? get filePath => null; @override Map get referenceChildren => {}; diff --git a/lib/src/model/operator.dart b/lib/src/model/operator.dart index 4b989a22d0..b0c5b940ed 100644 --- a/lib/src/model/operator.dart +++ b/lib/src/model/operator.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; // ignore: implementation_imports @@ -11,26 +11,26 @@ import 'package:dartdoc/src/comment_references/parser.dart'; import 'package:dartdoc/src/model/model.dart'; class Operator extends Method { - Operator(MethodElement element, Library library, PackageGraph packageGraph) + Operator(MethodElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); Operator.inherited(MethodElement element, Container enclosingContainer, - Library library, PackageGraph packageGraph, {Member originalMember}) + Library? library, PackageGraph packageGraph, {Member? originalMember}) : super.inherited(element, enclosingContainer, library, packageGraph, - originalMember: originalMember); + originalMember: originalMember as ExecutableMember?); @override String get fileName { var actualName = super.name; if (operatorNames.containsKey(actualName)) { - actualName = 'operator_${operatorNames[actualName]}'; + actualName = 'operator_${operatorNames[actualName!]}'; } return '$actualName.$fileType'; } @override String get fullyQualifiedName => - '${library.name}.${enclosingElement.name}.${super.name}'; + '${library!.name}.${enclosingElement!.name}.${super.name}'; @override bool get isOperator => true; @@ -44,5 +44,5 @@ class Operator extends Method { } @override - String get referenceName => super.name; + String get referenceName => super.name!; } diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index f472830407..34b3994b2b 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/file_system/file_system.dart'; @@ -44,7 +44,7 @@ class Package extends LibraryContainer String _name; PackageGraph _packageGraph; - final Map _nameToCategory = {}; + final Map _nameToCategory = {}; // Creates a package, if necessary, and adds it to the [packageGraph]. factory Package.fromPackageMeta( @@ -63,10 +63,10 @@ class Package extends LibraryContainer // before allLibrariesAdded is true. assert( !(expectNonLocal && - packageGraph.packageMap[packageName].documentedWhere == + packageGraph.packageMap[packageName]!.documentedWhere == DocumentLocation.local), 'Found more libraries to document after allLibrariesAdded was set to true'); - return packageGraph.packageMap[packageName]; + return packageGraph.packageMap[packageName]!; } Package._(this._name, this._packageGraph, this._packageMeta); @@ -75,14 +75,14 @@ class Package extends LibraryContainer bool get isCanonical => true; @override - Library get canonicalLibrary => null; + Library? get canonicalLibrary => null; /// Number of times we have invoked a tool for this package. int toolInvocationIndex = 0; // The animation IDs that have already been used, indexed by the [href] of the // object that contains them. - Map> usedAnimationIdsByHref = {}; + Map> usedAnimationIdsByHref = {}; /// Pieces of the location, split to remove 'package:' and slashes. @override @@ -106,24 +106,24 @@ class Package extends LibraryContainer /// Return true if the code has defined non-default categories for libraries /// in this package. - bool get hasCategories => categories.isNotEmpty; + bool get hasCategories => categories!.isNotEmpty; - LibraryContainer get defaultCategory => nameToCategory[null]; + LibraryContainer? get defaultCategory => nameToCategory[null]; - String _documentationAsHtml; + String? _documentationAsHtml; @override - String get documentationAsHtml { + String? get documentationAsHtml { if (_documentationAsHtml != null) return _documentationAsHtml; _documentationAsHtml = Documentation.forElement(this).asHtml; return _documentationAsHtml; } - String /*?*/ _documentation; + String? _documentation; @override - String get documentation { + String? get documentation { if (_documentation == null) { final docFile = documentationFile; if (docFile != null) { @@ -140,9 +140,9 @@ class Package extends LibraryContainer @override bool get hasExtendedDocumentation => hasDocumentation; - File /*?*/ _documentationFile; + File? _documentationFile; - File /*?*/ get documentationFile => + File? get documentationFile => _documentationFile ??= packageMeta.getReadmeContents(); @override @@ -153,22 +153,22 @@ class Package extends LibraryContainer isFirstPackage || documentedWhere != DocumentLocation.missing; @override - Warnable get enclosingElement => null; + Warnable? get enclosingElement => null; - bool _isPublic; + bool? _isPublic; @override - bool get isPublic { + bool? get isPublic { _isPublic ??= libraries.any((l) => l.isPublic); return _isPublic; } - bool _isLocal; + bool? _isLocal; /// Return true if this is the default package, this is part of an embedder /// SDK, or if [DartdocOptionContext.autoIncludeDependencies] is true -- but /// only if the package was not excluded on the command line. - bool get isLocal { + bool? get isLocal { _isLocal ??= ( // Document as local if this is the default package. packageMeta == packageGraph.packageMeta || @@ -180,7 +180,7 @@ class Package extends LibraryContainer packageMeta.isSdk && libraries.any((l) => _pathContext.isWithin( packageGraph.packageMeta.dir.path, - (l.element.source.fullName))) || + (l.element!.source.fullName))) || // autoIncludeDependencies means everything is local. packageGraph.config.autoIncludeDependencies) && // Regardless of the above rules, do not document as local if @@ -189,18 +189,18 @@ class Package extends LibraryContainer return _isLocal; } - /* late */ DocumentLocation _documentedWhere; + late DocumentLocation _documentedWhere; DocumentLocation get documentedWhere { if (_documentedWhere == null) { - if (isLocal) { - if (isPublic) { + if (isLocal!) { + if (isPublic!) { _documentedWhere = DocumentLocation.local; } } else { - if (config.linkToRemote && - config.linkToUrl.isNotEmpty && - isPublic && + if (config!.linkToRemote && + config!.linkToUrl.isNotEmpty && + isPublic! && !packageGraph.config.isPackageExcluded(name)) { _documentedWhere = DocumentLocation.remote; } else { @@ -216,7 +216,7 @@ class Package extends LibraryContainer String get filePath => 'index.$fileType'; - String _fileType; + String? _fileType; String get fileType { // TODO(jdkoren): Provide a way to determine file type of a remote package's @@ -226,31 +226,31 @@ class Package extends LibraryContainer // from pub.dev, and we know that all of those use html docs. return _fileType ??= (package.documentedWhere == DocumentLocation.remote) ? 'html' - : config.format; + : config!.format; } @override String get fullyQualifiedName => 'package:$name'; - String _baseHref; + String? _baseHref; - String get baseHref { + String? get baseHref { if (_baseHref != null) { return _baseHref; } if (documentedWhere == DocumentLocation.remote) { _baseHref = _remoteBaseHref; - if (!_baseHref.endsWith('/')) _baseHref = '$_baseHref/'; + if (!_baseHref!.endsWith('/')) _baseHref = '$_baseHref/'; } else { - _baseHref = config.useBaseHref ? '' : htmlBasePlaceholder; + _baseHref = config!.useBaseHref ? '' : htmlBasePlaceholder; } return _baseHref; } String get _remoteBaseHref { - return config.linkToUrl.replaceAllMapped(_substituteNameVersion, (m) { + return config!.linkToUrl.replaceAllMapped(_substituteNameVersion, (m) { switch (m.group(1)) { // Return the prerelease tag of the release if a prerelease, or 'stable' // otherwise. Mostly coded around the Dart SDK's use of dev/stable, but @@ -309,48 +309,44 @@ class Package extends LibraryContainer } /// A map of category name to the category itself. - Map get nameToCategory { + Map get nameToCategory { if (_nameToCategory.isEmpty) { - Category categoryFor(String category) { + Category? categoryFor(String? category) { _nameToCategory.putIfAbsent( - category, () => Category(category, this, config)); + category, () => Category(category!, this, config!)); return _nameToCategory[category]; } - _nameToCategory[null] = Category(null, this, config); + _nameToCategory[null] = Category(null, this, config!); for (var c in libraries.expand( (l) => l.allCanonicalModelElements.whereType())) { if (c.hasCategoryNames) { - for (var category in c.categoryNames) { - categoryFor(category).addItem(c); + for (var category in c.categoryNames!) { + categoryFor(category)!.addItem(c); } } else { // Add to the default category. - categoryFor(null).addItem(c); + categoryFor(null)!.addItem(c); } } } return _nameToCategory; } - List _categories; - - List get categories { - _categories ??= nameToCategory.values.where((c) => c.name != null).toList() - ..sort(); - return _categories; - } + late final List categories = () { + return nameToCategory.values.toList()..sort(); + } (); Iterable get categoriesWithPublicLibraries => - categories.where((c) => c.publicLibraries.isNotEmpty); + categories!.where((c) => c.publicLibraries.isNotEmpty); Iterable get documentedCategories => - categories.where((c) => c.isDocumented); + categories!.where((c) => c.isDocumented); Iterable get documentedCategoriesSorted { // Category display order is configurable; leave the category order // as defined if the order is specified. - if (config.categoryOrder.isEmpty) { + if (config!.categoryOrder.isEmpty) { return documentedCategories; } return documentedCategories.toList()..sort(byName); @@ -358,13 +354,13 @@ class Package extends LibraryContainer bool get hasDocumentedCategories => documentedCategories.isNotEmpty; - DartdocOptionContext _config; + DartdocOptionContext? _config; @override - DartdocOptionContext get config { + DartdocOptionContext? get config { _config ??= DartdocOptionContext.fromContext( packageGraph.config, - packageGraph.resourceProvider.getFolder(packagePath), + packageGraph.resourceProvider.getFolder(packagePath!), packageGraph.resourceProvider); return _config; } @@ -378,9 +374,9 @@ class Package extends LibraryContainer @override bool get isSdk => packageMeta.isSdk; - String _packagePath; + String? _packagePath; - String get packagePath { + String? get packagePath { _packagePath ??= _pathContext.canonicalize(packageMeta.dir.path); return _packagePath; } @@ -392,25 +388,25 @@ class Package extends LibraryContainer PackageMeta get packageMeta => _packageMeta; @override - Element get element => null; + Element? get element => null; @override - List get containerOrder => config.packageOrder; + List get containerOrder => config!.packageOrder; - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; - _referenceChildren.addEntries(publicLibrariesSorted.generateEntries()); + _referenceChildren!.addEntries(publicLibrariesSorted.generateEntries()); // Do not override any preexisting data, and insert based on the // public library sort order. // TODO(jcollins-g): warn when results require package-global // lookups like this. - _referenceChildren.addEntriesIfAbsent( + _referenceChildren!.addEntriesIfAbsent( publicLibrariesSorted.expand((l) => l.referenceChildren.entries)); } - return _referenceChildren; + return _referenceChildren!; } @override diff --git a/lib/src/model/package_builder.dart b/lib/src/model/package_builder.dart index c842c02c3e..2b44f91137 100644 --- a/lib/src/model/package_builder.dart +++ b/lib/src/model/package_builder.dart @@ -2,7 +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. -// @dart=2.9 + import 'dart:async'; @@ -24,6 +24,7 @@ import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl; import 'package:analyzer/src/generated/java_io.dart' show JavaFile; // ignore: implementation_imports import 'package:analyzer/src/generated/sdk.dart' show DartSdk; +import 'package:collection/collection.dart' show IterableExtension; import 'package:dartdoc/src/dartdoc_options.dart'; import 'package:dartdoc/src/logging.dart'; import 'package:dartdoc/src/model/model.dart' hide Package; @@ -61,7 +62,7 @@ class PubPackageBuilder implements PackageBuilder { 'Top level package requires Flutter but FLUTTER_ROOT environment variable not set'); } if (config.topLevelPackageMeta.needsPubGet) { - config.topLevelPackageMeta.runPubGet(config.flutterRoot); + config.topLevelPackageMeta.runPubGet(config.flutterRoot!); } } @@ -81,7 +82,7 @@ class PubPackageBuilder implements PackageBuilder { return newGraph; } - /*late final*/ DartSdk _sdk; + late final DartSdk _sdk; DartSdk get sdk { _sdk ??= packageMetaProvider.defaultSdk ?? @@ -91,9 +92,9 @@ class PubPackageBuilder implements PackageBuilder { return _sdk; } - EmbedderSdk _embedderSdk; + EmbedderSdk? _embedderSdk; - EmbedderSdk get embedderSdk { + EmbedderSdk? get embedderSdk { if (_embedderSdk == null && !config.topLevelPackageMeta.isSdk) { _embedderSdk = EmbedderSdk( resourceProvider, EmbedderYamlLocator(_packageMap).embedderYamls); @@ -106,7 +107,7 @@ class PubPackageBuilder implements PackageBuilder { Future _calculatePackageMap() async { assert(_packageMap == null); _packageMap = >{}; - Folder cwd = resourceProvider.getResource(config.inputDir); + Folder cwd = resourceProvider.getResource(config.inputDir) as Folder; var info = await packageConfigProvider .findPackageConfig(resourceProvider.getFolder(cwd.path)); if (info == null) return; @@ -121,11 +122,11 @@ class PubPackageBuilder implements PackageBuilder { } } - /*late final*/ Map> _packageMap; + late final Map> _packageMap; - AnalysisContextCollection _contextCollection; + AnalysisContextCollection? _contextCollection; - AnalysisContextCollection get contextCollection { + AnalysisContextCollection? get contextCollection { _contextCollection ??= AnalysisContextCollectionImpl( includedPaths: [config.inputDir], // TODO(jcollins-g): should we pass excluded directories here instead of @@ -142,14 +143,14 @@ class PubPackageBuilder implements PackageBuilder { /// Returns an Iterable with the SDK files we should parse. Iterable getSdkFilesToDocument() sync* { for (var sdkLib in sdk.sdkLibraries) { - var source = sdk.mapDartUri(sdkLib.shortName); + var source = sdk.mapDartUri(sdkLib.shortName)!; yield source.fullName; } } /// Parse a single library at [filePath] using the current analysis driver. /// If [filePath] is not a library, returns null. - Future processLibrary(String filePath) async { + Future processLibrary(String filePath) async { var name = filePath; var directoryCurrentPath = resourceProvider.pathContext.current; @@ -162,7 +163,7 @@ class PubPackageBuilder implements PackageBuilder { var javaFile = JavaFile(filePath).getAbsoluteFile(); filePath = javaFile.getPath(); - var analysisContext = contextCollection.contextFor(config.inputDir); + var analysisContext = contextCollection!.contextFor(config.inputDir); var session = analysisContext.currentSession; // Allow dart source files with inappropriate suffixes (#1897). final library = await session.getResolvedLibrary(filePath); @@ -174,11 +175,11 @@ class PubPackageBuilder implements PackageBuilder { return null; } - Set _packageMetasForFiles(Iterable files) => { + Set _packageMetasForFiles(Iterable files) => { for (var filename in files) packageMetaProvider.fromFilename(filename), }; - void _addKnownFiles(LibraryElement element) { + void _addKnownFiles(LibraryElement? element) { if (element != null) { var path = element.source.fullName; if (_knownFiles.add(path)) { @@ -204,10 +205,10 @@ class PubPackageBuilder implements PackageBuilder { void Function(DartDocResolvedLibrary) libraryAdder, Set libraries, Set files, - [bool Function(LibraryElement) isLibraryIncluded]) async { + [bool Function(LibraryElement)? isLibraryIncluded]) async { isLibraryIncluded ??= (_) => true; - var lastPass = {}; - var current = {}; + Set lastPass = {}; + Set current = {}; var knownParts = {}; do { lastPass = current; @@ -239,7 +240,7 @@ class PubPackageBuilder implements PackageBuilder { // discovers some files in a package we haven't seen yet, add files // for that package. for (var meta in current.difference(lastPass)) { - if (meta.isSdk) { + if (meta!.isSdk) { files.addAll(getSdkFilesToDocument()); } else { files.addAll(await findFilesToDocumentInPackage(meta.dir.path, @@ -253,17 +254,17 @@ class PubPackageBuilder implements PackageBuilder { /// Given a package name, explore the directory and pull out all top level /// library files in the "lib" directory to document. Stream findFilesToDocumentInPackage(String basePackageDir, - {@required bool autoIncludeDependencies, + {required bool autoIncludeDependencies, bool filterExcludes = true}) async* { var packageDirs = {basePackageDir}; if (autoIncludeDependencies) { - var info = await packageConfigProvider - .findPackageConfig(resourceProvider.getFolder(basePackageDir)); + var info = await (packageConfigProvider + .findPackageConfig(resourceProvider.getFolder(basePackageDir)) as FutureOr); for (var package in info.packages) { if (!filterExcludes || !config.exclude.contains(package.name)) { packageDirs.add(_pathContext.dirname( - _pathContext.fromUri(info[package.name].packageUriRoot))); + _pathContext.fromUri(info[package.name]!.packageUriRoot))); } } } @@ -307,7 +308,7 @@ class PubPackageBuilder implements PackageBuilder { /// The returned paths are guaranteed to begin with [dir]. Iterable _listDir(String dir, {bool recursive = false, - Iterable Function(Folder dir) listDir}) { + Iterable Function(Folder dir)? listDir}) { listDir ??= (Folder dir) => dir.getChildren(); return _doList(dir, {}, recursive, listDir); @@ -371,7 +372,7 @@ class PubPackageBuilder implements PackageBuilder { return [ for (var dartUri in _embedderSdkUris) resourceProvider.pathContext.absolute(resourceProvider - .getFile(embedderSdk.mapDartUri(dartUri).fullName) + .getFile(embedderSdk!.mapDartUri(dartUri)!.fullName) .path), ]; } @@ -385,12 +386,12 @@ class PubPackageBuilder implements PackageBuilder { } Future getLibraries(PackageGraph uninitializedPackageGraph) async { - var findSpecialsSdk = sdk; - if (embedderSdk != null && embedderSdk.urlMappings.isNotEmpty) { + DartSdk? findSpecialsSdk = sdk; + if (embedderSdk != null && embedderSdk!.urlMappings.isNotEmpty) { findSpecialsSdk = embedderSdk; } var files = await _getFiles(); - var specialFiles = specialLibraryFiles(findSpecialsSdk); + var specialFiles = specialLibraryFiles(findSpecialsSdk!); /// Returns true if this library element should be included according /// to the configuration. @@ -430,13 +431,11 @@ class PubPackageBuilder implements PackageBuilder { var resources = dir.getChildren(); var pathContext = dir.provider.pathContext; - var pubspec = resources.firstWhere( - (e) => e is File && pathContext.basename(e.path) == 'pubspec.yaml', - orElse: () => null); + var pubspec = resources.firstWhereOrNull( + (e) => e is File && pathContext.basename(e.path) == 'pubspec.yaml'); - var libDir = resources.firstWhere( - (e) => e is Folder && pathContext.basename(e.path) == 'lib', - orElse: () => null); + var libDir = resources.firstWhereOrNull( + (e) => e is Folder && pathContext.basename(e.path) == 'lib'); if (pubspec != null && libDir != null) { yield libDir; diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index cfc76e9d0c..695570afa2 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -2,7 +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. -// @dart=2.9 + import 'dart:collection'; @@ -37,7 +37,6 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { this.rendererFactory, this.packageMetaProvider, ) : packageMeta = config.topLevelPackageMeta { - _packageWarningCounter = PackageWarningCounter(this); // Make sure the default package exists, even if it has no libraries. // This can happen for packages that only contain embedder SDKs. Package.fromPackageMeta(packageMeta, this); @@ -52,7 +51,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { } @override - String get name => null; + String? get name => null; /// Call during initialization to add a library to this [PackageGraph]. /// @@ -70,7 +69,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { } var lib = Library.fromLibraryResult( resolvedLibrary, this, Package.fromPackageMeta(packageMeta, this)); - packageMap[packageMeta.name].libraries.add(lib); + packageMap[packageMeta.name]!.libraries.add(lib); allLibraries[libraryElement.source.fullName] = lib; } @@ -102,11 +101,11 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // are picked up. for (var package in documentedPackages) { for (var library in package.libraries) { - _addToImplementors(library.allClasses); + _addToImplementors(library.allClasses!); _addToImplementors(library.mixins); _extensions.addAll(library.extensions); } - if (package.isLocal && !package.hasPublicLibraries) { + if (package.isLocal! && !package.hasPublicLibraries) { package.warn(PackageWarning.noDocumentableLibrariesInPackage); } } @@ -124,23 +123,23 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { Iterable> precacheOneElement(ModelElement m) sync* { for (var d - in m.documentationFrom.where((d) => d.hasDocumentationComment)) { + in m.documentationFrom!.where((d) => d.hasDocumentationComment)) { if (d.needsPrecache && !precachedElements.contains(d)) { - precachedElements.add(d); + precachedElements.add(d as ModelElement); yield d.precacheLocalDocs(); - logProgress(d.name); + logProgress(d.name!); // TopLevelVariables get their documentation from getters and setters, // so should be precached if either has a template. if (m is TopLevelVariable && !precachedElements.contains(m)) { precachedElements.add(m); yield m.precacheLocalDocs(); - logProgress(d.name); + logProgress(d.name!); } } } } - for (var m in allModelElements) { + for (var m in allModelElements!) { // Skip if there is a canonicalModelElement somewhere else we can run this // for and we won't need a one line document that is precached. // Not the same as allCanonicalModelElements since we need to run @@ -151,7 +150,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { && !m.isCanonical // This element is not canonical && - !m.enclosingElement + !m.enclosingElement! .isCanonical // The enclosingElement won't need a oneLineDoc from this ) { continue; @@ -174,9 +173,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { resourceProvider)); } - ModelNode getModelNodeFor(Element element) => _modelNodes[element]; + ModelNode? getModelNodeFor(Element? element) => _modelNodes[element!]; - SpecialClasses specialClasses; + late SpecialClasses specialClasses; /// It is safe to cache values derived from the [_implementors] table if this /// is true. @@ -191,8 +190,8 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { return _implementors; } - List _documentedExtensions; - Iterable get documentedExtensions { + List? _documentedExtensions; + Iterable? get documentedExtensions { _documentedExtensions ??= utils.filterNonDocumented(extensions).toList(growable: false); return _documentedExtensions; @@ -212,12 +211,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // of differences in the [TimestampedData] timestamps. final allLibraries = {}; - /// Keep track of warnings - PackageWarningCounter _packageWarningCounter; - /// All ModelElements constructed for this package; a superset of [allModelElements]. - final allConstructedModelElements = - HashMap, ModelElement>(); + final HashMap, ModelElement?> allConstructedModelElements = + HashMap, ModelElement?>(); /// Anything that might be inheritable, place here for later lookup. final allInheritableElements = @@ -249,7 +245,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// PackageMeta Provider for building [PackageMeta]s. final PackageMetaProvider packageMetaProvider; - Package _defaultPackage; + Package? _defaultPackage; Package get defaultPackage => _defaultPackage ??= Package.fromPackageMeta(packageMeta, this); @@ -268,13 +264,13 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { final DartSdk sdk; - Map _sdkLibrarySources; + Map? _sdkLibrarySources; - Map get sdkLibrarySources { + Map? get sdkLibrarySources { if (_sdkLibrarySources == null) { _sdkLibrarySources = {}; for (var lib in sdk?.sdkLibraries) { - _sdkLibrarySources[sdk.mapDartUri(lib.shortName)] = lib; + _sdkLibrarySources![sdk.mapDartUri(lib.shortName)] = lib; } } return _sdkLibrarySources; @@ -285,14 +281,15 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { bool allLibrariesAdded = false; bool _localDocumentationBuilt = false; - PackageWarningCounter get packageWarningCounter => _packageWarningCounter; + /// Keep track of warnings. + late final PackageWarningCounter packageWarningCounter = PackageWarningCounter(this); - final Set> _warnAlreadySeen = {}; + final Set> _warnAlreadySeen = {}; - void warnOnElement(Warnable warnable, PackageWarning kind, - {String message, - Iterable referredFrom, - Iterable extendedDebug}) { + void warnOnElement(Warnable? warnable, PackageWarning kind, + {String? message, + Iterable? referredFrom, + Iterable? extendedDebug}) { var newEntry = Tuple3(warnable?.element, kind, message); if (_warnAlreadySeen.contains(newEntry)) { return; @@ -301,20 +298,20 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // don't allow warnings we're already working on to get in there. _warnAlreadySeen.add(newEntry); _warnOnElement(warnable, kind, - message: message, + message: message!, referredFrom: referredFrom, extendedDebug: extendedDebug); _warnAlreadySeen.remove(newEntry); } - void _warnOnElement(Warnable warnable, PackageWarning kind, - {String message, - Iterable referredFrom, - Iterable extendedDebug}) { + void _warnOnElement(Warnable? warnable, PackageWarning kind, + {required String message, + Iterable? referredFrom, + Iterable? extendedDebug}) { if (warnable != null) { // This sort of warning is only applicable to top level elements. if (kind == PackageWarning.ambiguousReexport) { - while (warnable.enclosingElement is! Library && + while (warnable!.enclosingElement is! Library && warnable.enclosingElement != null) { warnable = warnable.enclosingElement; } @@ -323,7 +320,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // If we don't have an element, we need a message to disambiguate. assert(message != null); } - if (_packageWarningCounter.hasWarning(warnable, kind, message)) { + if (packageWarningCounter!.hasWarning(warnable, kind, message)) { return; } // Some kinds of warnings it is OK to drop if we're not documenting them. @@ -344,7 +341,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { var warnablePrefix = 'from'; var referredFromPrefix = 'referred to by'; - String warningMessage; + String? warningMessage; switch (kind) { case PackageWarning.noCanonicalFound: // Fix these warnings by adding libraries with --include, or by using @@ -369,11 +366,11 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { break; case PackageWarning.noLibraryLevelDocs: warningMessage = - '${warnable.fullyQualifiedName} has no library level documentation comments'; + '${warnable!.fullyQualifiedName} has no library level documentation comments'; break; case PackageWarning.noDocumentableLibrariesInPackage: warningMessage = - '${warnable.fullyQualifiedName} has no documentable libraries'; + '${warnable!.fullyQualifiedName} has no documentable libraries'; break; case PackageWarning.ambiguousDocReference: warningMessage = 'ambiguous doc reference $message'; @@ -455,7 +452,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { break; } - var messageParts = [warningMessage]; + var messageParts = [warningMessage]; if (warnable != null) { messageParts.add('$warnablePrefix $warnableName: ${warnable.location}'); } @@ -473,10 +470,10 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { } var fullMessage = messageParts.join('\n '); - packageWarningCounter.addWarning(warnable, kind, message, fullMessage); + packageWarningCounter!.addWarning(warnable, kind, message, fullMessage); } - String _safeWarnableName(Locatable locatable) { + String _safeWarnableName(Locatable? locatable) { if (locatable == null) { return ''; } @@ -486,9 +483,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { List get packages => packageMap.values.toList(); - List _publicPackages; + List? _publicPackages; - List get publicPackages { + List? get publicPackages { if (_publicPackages == null) { assert(allLibrariesAdded); // Help the user if they pass us a package that doesn't exist. @@ -500,14 +497,14 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { "$packageName, packages: ${packages.map((p) => p.name).join(',')}"); } } - _publicPackages = packages.where((p) => p.isPublic).toList()..sort(); + _publicPackages = packages.where((p) => p.isPublic!).toList()..sort(); } return _publicPackages; } /// Local packages are to be documented locally vs. remote or not at all. List get localPackages => - publicPackages.where((p) => p.isLocal).toList(); + publicPackages!.where((p) => p.isLocal!).toList(); /// Documented packages are documented somewhere (local or remote). Iterable get documentedPackages => @@ -516,12 +513,12 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { Map> _libraryElementReexportedBy = {}; /// Prevent cycles from breaking our stack. - Set> _reexportsTagged = {}; + Set> _reexportsTagged = {}; void _tagReexportsFor( - final Library topLevelLibrary, final LibraryElement libraryElement, - [ExportElement lastExportedElement]) { - var key = Tuple2(topLevelLibrary, libraryElement); + final Library topLevelLibrary, final LibraryElement? libraryElement, + [ExportElement? lastExportedElement]) { + var key = Tuple2(topLevelLibrary, libraryElement); if (_reexportsTagged.contains(key)) { return; } @@ -530,7 +527,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // The first call to _tagReexportFor should not have a null libraryElement. assert(lastExportedElement != null); warnOnElement( - findButDoNotCreateLibraryFor(lastExportedElement.enclosingElement), + findButDoNotCreateLibraryFor(lastExportedElement!.enclosingElement!), PackageWarning.unresolvedExport, message: '"${lastExportedElement.uri}"', referredFrom: [topLevelLibrary]); @@ -553,7 +550,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { _lastSizeOfAllLibraries = allLibraries.keys.length; _libraryElementReexportedBy = >{}; _reexportsTagged = {}; - for (var library in publicLibraries) { + for (var library in publicLibraries!) { _tagReexportsFor(library, library.element); } } @@ -577,7 +574,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { if (modelElement is Dynamic) continue; // TODO: see [Accessor.enclosingCombo] if (modelElement is Accessor) continue; - final href = modelElement.href; + final href = modelElement!.href; if (href == null) continue; hrefMap.putIfAbsent(href, () => {}).add(modelElement); @@ -601,12 +598,12 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { void checkAndAddContainer( InheritingContainer implemented, InheritingContainer implementor) { - if (!implemented.isPublic) { + if (!implemented.isPublic!) { privates.add(implemented); } - implemented = implemented.canonicalModelElement ?? implemented; + implemented = implemented.canonicalModelElement as InheritingContainer? ?? implemented; _implementors.putIfAbsent(implemented, () => []); - var list = _implementors[implemented]; + var list = _implementors[implemented]!; // TODO(srawlins): This would be more efficient if we created a // SplayTreeSet keyed off of `.element`. if (!list.any((l) => l.element == implementor.element)) { @@ -616,18 +613,18 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { void addImplementor(InheritingContainer clazz) { if (clazz.supertype != null) { - checkAndAddContainer(clazz.supertype.modelElement, clazz); + checkAndAddContainer(clazz.supertype!.modelElement as InheritingContainer, clazz); } if (clazz is Class) { for (var type in clazz.mixedInTypes) { - checkAndAddContainer(type.modelElement, clazz); + checkAndAddContainer(type.modelElement as InheritingContainer, clazz); } for (var type in clazz.interfaces) { - checkAndAddContainer(type.modelElement, clazz); + checkAndAddContainer(type.modelElement as InheritingContainer, clazz); } } for (var type in clazz.publicInterfaces) { - checkAndAddContainer(type.modelElement, clazz); + checkAndAddContainer(type.modelElement as InheritingContainer, clazz); } } @@ -643,9 +640,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { Iterable get libraries => packages.expand((p) => p.libraries).toList()..sort(); - List _publicLibraries; + List? _publicLibraries; - Iterable get publicLibraries { + Iterable? get publicLibraries { if (_publicLibraries == null) { assert(allLibrariesAdded); _publicLibraries = utils.filterNonPublic(libraries).toList(); @@ -653,9 +650,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { return _publicLibraries; } - List _localLibraries; + List? _localLibraries; - Iterable get localLibraries { + Iterable? get localLibraries { if (_localLibraries == null) { assert(allLibrariesAdded); _localLibraries = localPackages.expand((p) => p.libraries).toList() @@ -664,36 +661,31 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { return _localLibraries; } - List _localPublicLibraries; - - Iterable get localPublicLibraries { - if (_localPublicLibraries == null) { + late final Iterable localPublicLibraries = () { assert(allLibrariesAdded); - _localPublicLibraries = utils.filterNonPublic(localLibraries).toList(); - } - return _localPublicLibraries; - } + return utils.filterNonPublic(localLibraries!).toList(); + } (); - Set _inheritThrough; + Set? _inheritThrough; /// Return the set of [Class]es objects should inherit through if they /// show up in the inheritance chain. Do not call before interceptorElement is /// found. Add classes here if they are similar to Interceptor in that they /// are to be ignored even when they are the implementors of [Inheritable]s, /// and the class these inherit from should instead claim implementation. - Set get inheritThrough { + Set? get inheritThrough { if (_inheritThrough == null) { _inheritThrough = {}; - _inheritThrough.add(specialClasses[SpecialClass.interceptor]); + _inheritThrough!.add(specialClasses[SpecialClass.interceptor]); } return _inheritThrough; } - Set _invisibleAnnotations; + Set? _invisibleAnnotations; /// Returns the set of [Class] objects that are similar to pragma /// in that we should never count them as documentable annotations. - Set get invisibleAnnotations => + Set get invisibleAnnotations => _invisibleAnnotations ??= {specialClasses[SpecialClass.pragma]}; bool isAnnotationVisible(Class clazz) => @@ -707,7 +699,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { buffer.writeln(divider); buffer.writeln(); for (final name in packageMap.keys) { - final package = packageMap[name]; + final package = packageMap[name]!; buffer.write('Package $name documented at ${package.documentedWhere} ' 'with libraries: '); buffer.writeAll(package.allLibraries); @@ -717,10 +709,10 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { return buffer.toString(); } - final Map _canonicalLibraryFor = {}; + final Map _canonicalLibraryFor = {}; /// Tries to find a top level library that references this element. - Library findCanonicalLibraryFor(Element e) { + Library? findCanonicalLibraryFor(Element? e) { assert(allLibrariesAdded); var searchElement = e; if (e is PropertyAccessorElement) { @@ -734,9 +726,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { return _canonicalLibraryFor[e]; } _canonicalLibraryFor[e] = null; - for (var library in publicLibraries) { + for (var library in publicLibraries!) { if (library.modelElementsMap.containsKey(searchElement)) { - for (var modelElement in library.modelElementsMap[searchElement]) { + for (var modelElement in library.modelElementsMap[searchElement!]!) { if (modelElement.isCanonical) { return _canonicalLibraryFor[e] = library; } @@ -754,26 +746,26 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// shouldn't, so using it with [Inheritable]s without special casing is /// not advised. // FIXME(nnbd): remove null check ignore in model_utils after migration - ModelElement /*?*/ findCanonicalModelElementFor(Element e, - {Container preferredClass}) { + ModelElement? findCanonicalModelElementFor(Element? e, + {Container? preferredClass}) { assert(allLibrariesAdded); var lib = findCanonicalLibraryFor(e); if (preferredClass != null && preferredClass is Container) { - Container canonicalClass = - findCanonicalModelElementFor(preferredClass.element); + Container? canonicalClass = + findCanonicalModelElementFor(preferredClass.element) as Container?; if (canonicalClass != null) preferredClass = canonicalClass; } if (lib == null && preferredClass != null) { lib = findCanonicalLibraryFor(preferredClass.element); } - ModelElement modelElement; + ModelElement? modelElement; // For elements defined in extensions, they are canonical. if (e?.enclosingElement is ExtensionElement) { - lib ??= modelBuilder.fromElement(e.enclosingElement.library); + lib ??= modelBuilder.fromElement(e!.enclosingElement!.library!) as Library?; // (TODO:keertip) Find a better way to exclude members of extensions // when libraries are specified using the "--include" flag if (lib?.isDocumented == true) { - return modelBuilder.from(e, lib); + return modelBuilder.from(e!, lib!); } } // TODO(jcollins-g): Special cases are pretty large here. Refactor to split @@ -781,30 +773,30 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // TODO(jcollins-g): The data structures should be changed to eliminate guesswork // with member elements. if (e is ClassMemberElement || e is PropertyAccessorElement) { - e = e.declaration; - var candidates = {}; - var iKey = Tuple2(e, lib); + e = e!.declaration; + var candidates = {}; + var iKey = Tuple2(e, lib); var key = - Tuple4(e, lib, null, null); - var keyWithClass = Tuple4( - e, lib, preferredClass, null); + Tuple4(e, lib, null, null); + var keyWithClass = Tuple4( + e, lib, preferredClass as Class?, null); if (allConstructedModelElements.containsKey(key)) { - candidates.add(allConstructedModelElements[key]); + candidates.add(allConstructedModelElements[key as Tuple3]); } if (allConstructedModelElements.containsKey(keyWithClass)) { - candidates.add(allConstructedModelElements[keyWithClass]); + candidates.add(allConstructedModelElements[keyWithClass as Tuple3]); } if (candidates.isEmpty && allInheritableElements.containsKey(iKey)) { candidates - .addAll(allInheritableElements[iKey].where((me) => me.isCanonical)); + .addAll(allInheritableElements[iKey as Tuple2]!.where((me) => me.isCanonical)); } - Class canonicalClass = findCanonicalModelElementFor(e.enclosingElement); + Class? canonicalClass = findCanonicalModelElementFor(e!.enclosingElement) as Class?; if (canonicalClass != null) { candidates.addAll(canonicalClass.allCanonicalModelElements.where((m) { return m.element == e; })); } - var matches = {...candidates.where((me) => me.isCanonical)}; + var matches = {...candidates.where((me) => me!.isCanonical)}; // It's possible to find accessors but no combos. Be sure that if we // have Accessors, we find their combos too. @@ -812,7 +804,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { var combos = matches.whereType().map((a) => a.enclosingCombo).toList(); matches.addAll(combos); - assert(combos.every((c) => c.isCanonical)); + assert(combos.every((c) => c!.isCanonical)); } // This is for situations where multiple classes may actually be canonical @@ -832,7 +824,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // preferredClass. var enclosingElements = { ...matches - .map((me) => (me as EnclosedElement).enclosingElement as Class) + .map((me) => (me as EnclosedElement).enclosingElement as Class?) }; for (var c in superChain.reversed) { if (enclosingElements.contains(c)) { @@ -856,13 +848,13 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { if (lib != null) { if (e is PropertyInducingElement) { var getter = - e.getter != null ? modelBuilder.from(e.getter, lib) : null; + e.getter != null ? modelBuilder.from(e.getter!, lib) : null; var setter = - e.setter != null ? modelBuilder.from(e.setter, lib) : null; + e.setter != null ? modelBuilder.from(e.setter!, lib) : null; modelElement = modelBuilder.fromPropertyInducingElement(e, lib, - getter: getter, setter: setter); + getter: getter as Accessor, setter: setter as Accessor); } else { - modelElement = modelBuilder.from(e, lib); + modelElement = modelBuilder.from(e!, lib); } } assert(modelElement is! Inheritable); @@ -872,7 +864,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { } // Prefer Fields. if (e is PropertyAccessorElement && modelElement is Accessor) { - modelElement = (modelElement as Accessor).enclosingCombo; + modelElement = modelElement.enclosingCombo; } return modelElement; } @@ -880,7 +872,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// This is used when we might need a Library object that isn't actually /// a documentation entry point (for elements that have no Library within the /// set of canonical Libraries). - Library findButDoNotCreateLibraryFor(Element e) { + Library? findButDoNotCreateLibraryFor(Element e) { // This is just a cache to avoid creating lots of libraries over and over. return allLibraries[e.library?.source?.fullName]; } @@ -901,15 +893,15 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { resolvedLibrary, this, Package.fromPackageMeta( - packageMetaProvider.fromElement(libraryElement, config.sdkDir), + packageMetaProvider.fromElement(libraryElement, config.sdkDir)!, packageGraph)); allLibraries[libraryElement.source.fullName] = foundLibrary; return foundLibrary; } - List _allModelElements; + List? _allModelElements; - Iterable get allModelElements { + Iterable? get allModelElements { assert(allLibrariesAdded); if (_allModelElements == null) { _allModelElements = []; @@ -923,7 +915,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { librariesToDo .difference(completedLibraries) .forEach((Library library) { - _allModelElements.addAll(library.allModelElements); + _allModelElements!.addAll(library.allModelElements); completedLibraries.add(library); }); librariesToDo.addAll(p.allLibraries); @@ -936,24 +928,24 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { return _allModelElements; } - List _allLocalModelElements; + List? _allLocalModelElements; - Iterable get allLocalModelElements { + Iterable? get allLocalModelElements { assert(allLibrariesAdded); if (_allLocalModelElements == null) { _allLocalModelElements = []; - for (var library in localLibraries) { - _allLocalModelElements.addAll(library.allModelElements); + for (var library in localLibraries!) { + _allLocalModelElements!.addAll(library.allModelElements); } } return _allLocalModelElements; } - List _allCanonicalModelElements; + List? _allCanonicalModelElements; Iterable get allCanonicalModelElements { return _allCanonicalModelElements ??= - allLocalModelElements.where((e) => e.isCanonical).toList(); + allLocalModelElements!.where((e) => e.isCanonical).toList(); } /// Glob lookups can be expensive. Cache per filename. @@ -961,7 +953,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// Given an element's location, look up the nodoc configuration data and /// determine whether to unconditionally treat the element as "nodoc". - bool configSetsNodocFor(String fullName) { + bool? configSetsNodocFor(String fullName) { if (!_configSetsNodocFor.containsKey(fullName)) { var file = resourceProvider.getFile(fullName); // Direct lookup instead of generating a custom context will save some @@ -975,9 +967,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { return _configSetsNodocFor[fullName]; } - String getMacro(String name) { + String? getMacro(String? name) { assert(_localDocumentationBuilt); - return _macros[name]; + return _macros[name!]; } void addMacro(String name, String content) { @@ -989,9 +981,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { _macros[name] = content; } - String getHtmlFragment(String name) { + String? getHtmlFragment(String? name) { assert(_localDocumentationBuilt); - return _htmlFragments[name]; + return _htmlFragments[name!]; } void addHtmlFragment(String name, String content) { @@ -1003,7 +995,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { _htmlFragments[name] = content; } - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { if (_referenceChildren == null) { @@ -1014,20 +1006,20 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { var sortedPackages = packages.toList()..sort(byName); var sortedDocumentedPackages = documentedPackages.toList()..sort(byName); // Packages are the top priority. - _referenceChildren.addEntries(sortedPackages.generateEntries()); + _referenceChildren!.addEntries(sortedPackages.generateEntries()); // Libraries are next. // TODO(jcollins-g): Warn about directly referencing libraries out of // scope? Doing this is always going to be ambiguous and potentially // confusing. - _referenceChildren.addEntriesIfAbsent(sortedDocumentedPackages + _referenceChildren!.addEntriesIfAbsent(sortedDocumentedPackages .expand((p) => p.publicLibrariesSorted) .generateEntries()); // TODO(jcollins-g): Warn about directly referencing top level items // out of scope? Doing this will be even more ambiguous and // potentially confusing than doing so with libraries. - _referenceChildren.addEntriesIfAbsent(sortedDocumentedPackages + _referenceChildren!.addEntriesIfAbsent(sortedDocumentedPackages .expand((p) => p.publicLibrariesSorted) .expand((l) => [ ...l.publicConstants, @@ -1041,7 +1033,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { ]) .generateEntries()); } - return _referenceChildren; + return _referenceChildren!; } @override diff --git a/lib/src/model/parameter.dart b/lib/src/model/parameter.dart index 5e62402d51..ebab4ff88e 100644 --- a/lib/src/model/parameter.dart +++ b/lib/src/model/parameter.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; // ignore: implementation_imports @@ -13,22 +13,22 @@ import 'package:dartdoc/src/model/model.dart'; class Parameter extends ModelElement implements EnclosedElement { Parameter( - ParameterElement element, Library library, PackageGraph packageGraph, - {ParameterMember originalMember}) + ParameterElement element, Library? library, PackageGraph packageGraph, + {ParameterMember? originalMember}) : super(element, library, packageGraph, originalMember); - String get defaultValue { + String? get defaultValue { if (!hasDefaultValue) return null; - return element.defaultValueCode; + return element!.defaultValueCode; } @override - ModelElement get enclosingElement => (element.enclosingElement != null) - ? modelBuilder.from(element.enclosingElement, library) + ModelElement? get enclosingElement => (element!.enclosingElement != null) + ? modelBuilder.from(element!.enclosingElement!, library!) : null; bool get hasDefaultValue { - return element.defaultValueCode != null && - element.defaultValueCode.isNotEmpty; + return element!.defaultValueCode != null && + element!.defaultValueCode!.isNotEmpty; } @override @@ -37,19 +37,19 @@ class Parameter extends ModelElement implements EnclosedElement { } @override - String get href => null; + String? get href => null; @override String get htmlId { - if (element.enclosingElement != null) { - var enclosingName = element.enclosingElement.name; - if (element.enclosingElement is GenericFunctionTypeElement) { + if (element!.enclosingElement != null) { + var enclosingName = element!.enclosingElement!.name; + if (element!.enclosingElement is GenericFunctionTypeElement) { // TODO(jcollins-g): Drop when GenericFunctionTypeElement populates name. // Also, allowing null here is allowed as a workaround for // dart-lang/sdk#32005. - for (var e = element.enclosingElement; + for (var e = element!.enclosingElement!; e.enclosingElement != null; - e = e.enclosingElement) { + e = e.enclosingElement!) { enclosingName = e.name; if (enclosingName != null && enclosingName.isNotEmpty) break; } @@ -65,23 +65,23 @@ class Parameter extends ModelElement implements EnclosedElement { @override bool operator ==(Object other) => - other is Parameter && (element.type == other.element.type); + other is Parameter && (element!.type == other.element!.type); - bool get isCovariant => element.isCovariant; + bool get isCovariant => element!.isCovariant; - bool get isRequiredPositional => element.isRequiredPositional; + bool get isRequiredPositional => element!.isRequiredPositional; - bool get isNamed => element.isNamed; + bool get isNamed => element!.isNamed; - bool get isOptionalPositional => element.isOptionalPositional; + bool get isOptionalPositional => element!.isOptionalPositional; /// Only true if this is a required named parameter. - bool get isRequiredNamed => element.isRequiredNamed; + bool get isRequiredNamed => element!.isRequiredNamed; @override String get kind => 'parameter'; - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { @@ -89,28 +89,28 @@ class Parameter extends ModelElement implements EnclosedElement { _referenceChildren = {}; var _modelType = modelType; if (_modelType is Callable) { - _referenceChildren.addEntriesIfAbsent( + _referenceChildren!.addEntriesIfAbsent( _modelType.parameters.explicitOnCollisionWith(this)); } - _referenceChildren.addEntriesIfAbsent( + _referenceChildren!.addEntriesIfAbsent( modelType.typeArguments.explicitOnCollisionWith(this)); if (_modelType is Callable) { - _referenceChildren.addEntriesIfAbsent( + _referenceChildren!.addEntriesIfAbsent( _modelType.returnType.typeArguments.explicitOnCollisionWith(this)); } } - return _referenceChildren; + return _referenceChildren!; } @override - Iterable get referenceParents => [enclosingElement]; + Iterable get referenceParents => [enclosingElement]; @override - ParameterElement get element => super.element; + ParameterElement? get element => super.element as ParameterElement?; @override - ParameterMember get originalMember => super.originalMember; + ParameterMember? get originalMember => super.originalMember as ParameterMember?; - ElementType _modelType; + ElementType? _modelType; ElementType get modelType => _modelType ??= - modelBuilder.typeFrom((originalMember ?? element).type, library); + modelBuilder.typeFrom((originalMember ?? element)!.type, library!); } diff --git a/lib/src/model/prefix.dart b/lib/src/model/prefix.dart index 1b3a3f0bfd..f90a59e38e 100644 --- a/lib/src/model/prefix.dart +++ b/lib/src/model/prefix.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/scope.dart'; @@ -17,38 +17,38 @@ import '../../dartdoc.dart'; class Prefix extends ModelElement implements EnclosedElement { /// [library] is the library the prefix is defined in, not the [Library] /// referred to by the [PrefixElement]. - Prefix(PrefixElement element, Library library, PackageGraph packageGraph) + Prefix(PrefixElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); @override bool get isCanonical => false; - Library _associatedLibrary; + Library? _associatedLibrary; // TODO(jcollins-g): consider connecting PrefixElement to the imported library // in analyzer? Library get associatedLibrary => - _associatedLibrary ??= modelBuilder.fromElement(library.element.imports + (_associatedLibrary ??= modelBuilder.fromElement(library!.element!.imports .firstWhere((i) => i.prefix == element) - .importedLibrary); + .importedLibrary!) as Library?)!; @override - Library get canonicalModelElement => associatedLibrary.canonicalLibrary; + Library? get canonicalModelElement => associatedLibrary.canonicalLibrary; @override - Scope get scope => element.scope; + Scope get scope => element!.scope; @override - PrefixElement get element => super.element; + PrefixElement? get element => super.element as PrefixElement?; @override - ModelElement get enclosingElement => library; + ModelElement? get enclosingElement => library; @override String get filePath => throw UnimplementedError('prefixes have no generated files in dartdoc'); @override - String get href => canonicalModelElement?.href; + String? get href => canonicalModelElement?.href; @override String get kind => 'prefix'; diff --git a/lib/src/model/privacy.dart b/lib/src/model/privacy.dart index 0b00685aa7..ec1e9b3e82 100644 --- a/lib/src/model/privacy.dart +++ b/lib/src/model/privacy.dart @@ -2,9 +2,9 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 + /// Classes implementing this have a public/private distinction. abstract class Privacy { - bool get isPublic; + bool? get isPublic; } diff --git a/lib/src/model/source_code_mixin.dart b/lib/src/model/source_code_mixin.dart index c36b5cb244..68d14d47d9 100644 --- a/lib/src/model/source_code_mixin.dart +++ b/lib/src/model/source_code_mixin.dart @@ -2,22 +2,22 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/source/line_info.dart'; import 'package:dartdoc/src/model/model.dart'; abstract class SourceCodeMixin implements Documentable { - ModelNode get modelNode; + ModelNode? get modelNode; - CharacterLocation get characterLocation; + CharacterLocation? get characterLocation; - Element get element; + Element? get element; - bool get hasSourceCode => config.includeSource && sourceCode.isNotEmpty; + bool get hasSourceCode => config!.includeSource && sourceCode!.isNotEmpty; Library get library; - String get sourceCode => modelNode == null ? '' : modelNode.sourceCode; + String? get sourceCode => modelNode == null ? '' : modelNode!.sourceCode; } diff --git a/lib/src/model/top_level_container.dart b/lib/src/model/top_level_container.dart index 62fdee0511..174bbbd2d7 100644 --- a/lib/src/model/top_level_container.dart +++ b/lib/src/model/top_level_container.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:dartdoc/src/model/model.dart'; import 'package:dartdoc/src/model_utils.dart' as model_utils; @@ -28,7 +28,7 @@ abstract class TopLevelContainer implements Nameable { Iterable get properties; - Iterable get functions; + Iterable? get functions; Iterable get typedefs; @@ -52,7 +52,7 @@ abstract class TopLevelContainer implements Nameable { Iterable get publicClasses => model_utils.filterNonPublic(classes); - List _publicClassesSorted; + List? _publicClassesSorted; // TODO(jcollins-g): Setting this type parameter to `Container` magically // fixes a number of type problems in the AOT compiler, but I am mystified as // to why that should be the case. @@ -62,7 +62,7 @@ abstract class TopLevelContainer implements Nameable { Iterable get publicExtensions => model_utils.filterNonPublic(extensions); - List _publicExtensionsSorted; + List? _publicExtensionsSorted; Iterable get publicExtensionsSorted => _publicExtensionsSorted ??= publicExtensions.toList()..sort(byName); @@ -74,40 +74,40 @@ abstract class TopLevelContainer implements Nameable { Iterable get publicEnums => model_utils.filterNonPublic(enums); - List _publicEnumsSorted; + List? _publicEnumsSorted; Iterable get publicEnumsSorted => _publicEnumsSorted ??= publicEnums.toList()..sort(byName); Iterable get publicExceptions => model_utils.filterNonPublic(exceptions); - List _publicExceptionsSorted; + List? _publicExceptionsSorted; Iterable get publicExceptionsSorted => _publicExceptionsSorted ??= publicExceptions.toList()..sort(byName); Iterable get publicFunctions => - model_utils.filterNonPublic(functions); + model_utils.filterNonPublic(functions!); - List _publicFunctionsSorted; + List? _publicFunctionsSorted; Iterable get publicFunctionsSorted => _publicFunctionsSorted ??= publicFunctions.toList()..sort(byName); Iterable get publicMixins => model_utils.filterNonPublic(mixins); - List _publicMixinsSorted; + List? _publicMixinsSorted; Iterable get publicMixinsSorted => _publicMixinsSorted ??= publicMixins.toList()..sort(byName); Iterable get publicProperties => model_utils.filterNonPublic(properties); - List _publicPropertiesSorted; + List? _publicPropertiesSorted; Iterable get publicPropertiesSorted => _publicPropertiesSorted ??= publicProperties.toList()..sort(byName); Iterable get publicTypedefs => model_utils.filterNonPublic(typedefs); - List _publicTypedefsSorted; + List? _publicTypedefsSorted; Iterable get publicTypedefsSorted => _publicTypedefsSorted ??= publicTypedefs.toList()..sort(byName); } diff --git a/lib/src/model/top_level_variable.dart b/lib/src/model/top_level_variable.dart index b250db3ee0..c26e7f6c48 100644 --- a/lib/src/model/top_level_variable.dart +++ b/lib/src/model/top_level_variable.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; @@ -14,18 +14,18 @@ class TopLevelVariable extends ModelElement with GetterSetterCombo, Categorization implements EnclosedElement { @override - final Accessor getter; + final Accessor? getter; @override - final Accessor setter; + final Accessor? setter; TopLevelVariable(TopLevelVariableElement element, Library library, PackageGraph packageGraph, this.getter, this.setter) : super(element, library, packageGraph) { if (getter != null) { - getter.enclosingCombo = this; + getter!.enclosingCombo = this; } if (setter != null) { - setter.enclosingCombo = this; + setter!.enclosingCombo = this; } } @@ -44,13 +44,13 @@ class TopLevelVariable extends ModelElement } @override - ModelElement get enclosingElement => library; + ModelElement? get enclosingElement => library; @override - String get filePath => '${library.dirName}/$fileName'; + String get filePath => '${library!.dirName}/$fileName'; @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -60,18 +60,18 @@ class TopLevelVariable extends ModelElement } @override - bool get isConst => _variable.isConst; + bool get isConst => _variable!.isConst; @override bool get isFinal { /// isFinal returns true for the variable even if it has an explicit getter /// (which means we should not document it as "final"). if (hasExplicitGetter) return false; - return _variable.isFinal; + return _variable!.isFinal; } @override - bool get isLate => isFinal && _variable.isLate; + bool get isLate => isFinal && _variable!.isLate; @override String get kind => isConst ? 'top-level constant' : 'top-level property'; @@ -82,7 +82,7 @@ class TopLevelVariable extends ModelElement @override String get fileName => '${isConst ? '$name-constant' : name}.$fileType'; - TopLevelVariableElement get _variable => (element as TopLevelVariableElement); + TopLevelVariableElement? get _variable => (element as TopLevelVariableElement?); @override Iterable get referenceParents => [definingLibrary]; diff --git a/lib/src/model/type_parameter.dart b/lib/src/model/type_parameter.dart index 3713955c75..65654a4919 100644 --- a/lib/src/model/type_parameter.dart +++ b/lib/src/model/type_parameter.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; @@ -12,33 +12,33 @@ import 'package:dartdoc/src/render/type_parameters_renderer.dart'; class TypeParameter extends ModelElement { TypeParameter( - TypeParameterElement element, Library library, PackageGraph packageGraph) + TypeParameterElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); @override - ModelElement get enclosingElement => (element.enclosingElement != null) - ? modelBuilder.from(element.enclosingElement, library) + ModelElement? get enclosingElement => (element!.enclosingElement != null) + ? modelBuilder.from(element!.enclosingElement!, library!) : null; @override String get filePath => - '${enclosingElement.library.dirName}/${enclosingElement.name}/$name'; + '${enclosingElement!.library!.dirName}/${enclosingElement!.name}/$name'; @override /// [TypeParameter]s don't have documentation pages. - String get href => null; + String? get href => null; @override String get kind => 'type parameter'; - ElementType _boundType; + ElementType? _boundType; - ElementType get boundType { + ElementType? get boundType { if (_boundType == null) { - var bound = element.bound; + var bound = element!.bound; if (bound != null) { - _boundType = modelBuilder.typeFrom(bound, library); + _boundType = modelBuilder.typeFrom(bound, library!); } } return _boundType; @@ -47,46 +47,46 @@ class TypeParameter extends ModelElement { @override bool get hasParameters => false; - String _name; + String? _name; @override - String get name { - _name ??= element.bound != null - ? '${element.name} extends ${boundType.nameWithGenerics}' - : element.name; + String? get name { + _name ??= element!.bound != null + ? '${element!.name} extends ${boundType!.nameWithGenerics}' + : element!.name; return _name; } - String _linkedName; + String? _linkedName; @override - String get linkedName { - _linkedName ??= element.bound != null - ? '${element.name} extends ${boundType.linkedName}' - : element.name; + String? get linkedName { + _linkedName ??= element!.bound != null + ? '${element!.name} extends ${boundType!.linkedName}' + : element!.name; return _linkedName; } - Map _referenceChildren; + Map? _referenceChildren; @override - Map get referenceChildren { + Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; if (boundType != null) { - _referenceChildren[boundType.name] = boundType; + _referenceChildren![boundType!.name] = boundType; } } - return _referenceChildren; + return _referenceChildren!; } @override - Iterable get referenceParents => [enclosingElement]; + Iterable get referenceParents => [enclosingElement]; @override - TypeParameterElement get element => super.element; + TypeParameterElement? get element => super.element as TypeParameterElement?; @override - String get referenceName => element.name; + String get referenceName => element!.name; } mixin TypeParameters implements ModelElement { @@ -94,7 +94,7 @@ mixin TypeParameters implements ModelElement { String get nameWithLinkedGenerics => '$name$linkedGenericParameters'; - bool get hasGenericParameters => typeParameters.isNotEmpty; + bool get hasGenericParameters => typeParameters!.isNotEmpty; String get genericParameters => _typeParametersRenderer.renderGenericParameters(this); @@ -102,7 +102,7 @@ mixin TypeParameters implements ModelElement { String get linkedGenericParameters => _typeParametersRenderer.renderLinkedGenericParameters(this); - List get typeParameters; + List? get typeParameters; TypeParametersRenderer get _typeParametersRenderer => packageGraph.rendererFactory.typeParametersRenderer; diff --git a/lib/src/model/typedef.dart b/lib/src/model/typedef.dart index 6fbfd8c9bf..d2a84a7247 100644 --- a/lib/src/model/typedef.dart +++ b/lib/src/model/typedef.dart @@ -2,7 +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. -// @dart=2.9 + import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; @@ -14,20 +14,20 @@ import 'package:dartdoc/src/render/typedef_renderer.dart'; abstract class Typedef extends ModelElement with TypeParameters, Categorization implements EnclosedElement { - Typedef(TypeAliasElement element, Library library, PackageGraph packageGraph) + Typedef(TypeAliasElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); - DartType get aliasedType => element.aliasedType; + DartType get aliasedType => element!.aliasedType; @override - TypeAliasElement get element => super.element; + TypeAliasElement? get element => super.element as TypeAliasElement?; - ElementType _modelType; + ElementType? _modelType; ElementType get modelType => - _modelType ??= modelBuilder.typeFrom(element.aliasedType, library); + _modelType ??= modelBuilder.typeFrom(element!.aliasedType, library!); @override - Library get enclosingElement => library; + Library? get enclosingElement => library; @override String get nameWithGenerics => '$name${super.genericParameters}'; @@ -40,14 +40,14 @@ abstract class Typedef extends ModelElement _renderer.renderLinkedGenericParameters(this); @override - String get filePath => '${library.dirName}/$fileName'; + String get filePath => '${library!.dirName}/$fileName'; /// Helper for mustache templates, which can't do casting themselves /// without this. FunctionTypedef get asCallable => this as FunctionTypedef; @override - String get href { + String? get href { if (!identical(canonicalModelElement, this)) { return canonicalModelElement?.href; } @@ -63,8 +63,8 @@ abstract class Typedef extends ModelElement String get kind => 'typedef'; @override - List get typeParameters => element.typeParameters.map((f) { - return modelBuilder.from(f, library) as TypeParameter; + List get typeParameters => element!.typeParameters.map((f) { + return modelBuilder.from(f, library!) as TypeParameter; }).toList(); TypedefRenderer get _renderer => packageGraph.rendererFactory.typedefRenderer; @@ -72,15 +72,15 @@ abstract class Typedef extends ModelElement @override Iterable get referenceParents => [definingLibrary]; - Map _referenceChildren; + Map? _referenceChildren; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; - _referenceChildren + _referenceChildren! .addEntriesIfAbsent(typeParameters.explicitOnCollisionWith(this)); } - return _referenceChildren; + return _referenceChildren!; } } @@ -89,7 +89,7 @@ abstract class Typedef extends ModelElement /// for `Function` itself. class GeneralizedTypedef extends Typedef { GeneralizedTypedef( - TypeAliasElement element, Library library, PackageGraph packageGraph) + TypeAliasElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph) { assert(!isCallable); } @@ -98,44 +98,44 @@ class GeneralizedTypedef extends Typedef { /// A typedef referring to a non-function, defined type. class ClassTypedef extends Typedef { ClassTypedef( - TypeAliasElement element, Library library, PackageGraph packageGraph) + TypeAliasElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph) { assert(!isCallable); assert(modelType.modelElement is Class); } @override - DefinedElementType get modelType => super.modelType; + DefinedElementType get modelType => super.modelType as DefinedElementType; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = super.referenceChildren; - _referenceChildren + _referenceChildren! .addEntriesIfAbsent(modelType.modelElement.referenceChildren.entries); } - return _referenceChildren; + return _referenceChildren!; } } /// A typedef referring to a function type. class FunctionTypedef extends Typedef { FunctionTypedef( - TypeAliasElement element, Library library, PackageGraph packageGraph) + TypeAliasElement element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph) { assert(isCallable); } @override - Callable get modelType => super.modelType; + Callable get modelType => super.modelType as Callable; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = super.referenceChildren; - _referenceChildren - .addEntriesIfAbsent(parameters.explicitOnCollisionWith(this)); + _referenceChildren! + .addEntriesIfAbsent(parameters!.explicitOnCollisionWith(this)); } - return _referenceChildren; + return _referenceChildren!; } } From 922c7d87acfbc8cdfc05aba4035308e382fee41a Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 14 Oct 2021 16:06:44 -0700 Subject: [PATCH 07/21] partial 2 --- lib/src/dartdoc_options.dart | 6 +-- lib/src/generator/generator_utils.dart | 2 +- lib/src/model/categorization.dart | 2 +- lib/src/model/category.dart | 4 +- lib/src/model/class.dart | 6 ++- lib/src/model/constructor.dart | 10 ----- lib/src/model/container.dart | 4 ++ lib/src/model/documentable.dart | 7 ++-- lib/src/model/documentation.dart | 1 + lib/src/model/documentation_comment.dart | 33 +++++++++------- lib/src/model/enum.dart | 8 +++- lib/src/model/extension.dart | 12 +----- lib/src/model/field.dart | 9 +---- lib/src/model/getter_setter_combo.dart | 29 +++++++------- lib/src/model/inheritable.dart | 20 ++++------ lib/src/model/inheriting_container.dart | 10 ----- lib/src/model/library.dart | 5 ++- lib/src/model/method.dart | 9 +---- lib/src/model/model_element.dart | 49 ++++++++++++++---------- lib/src/model/model_function.dart | 5 ++- lib/src/model/model_object_builder.dart | 4 +- lib/src/model/operator.dart | 2 +- lib/src/model/package.dart | 2 +- lib/src/model/source_code_mixin.dart | 2 +- lib/src/warnings.dart | 2 +- 25 files changed, 114 insertions(+), 129 deletions(-) diff --git a/lib/src/dartdoc_options.dart b/lib/src/dartdoc_options.dart index 64ad5360c0..c4f8da93b7 100644 --- a/lib/src/dartdoc_options.dart +++ b/lib/src/dartdoc_options.dart @@ -58,8 +58,8 @@ class DartdocFileMissing extends DartdocOptionError { /// the 'categories' keyword in the options file, and populated by the /// [CategoryConfiguration] class. class CategoryDefinition { - /// Internal name of the category. - final String name; + /// Internal name of the category, or null for the default category. + final String? name; /// Displayed name of the category in docs, or null if there is none. final String? _displayName; @@ -71,7 +71,7 @@ class CategoryDefinition { CategoryDefinition(this.name, this._displayName, this.documentationMarkdown); /// Returns the [_displayName], if available, or else simply [name]. - String get displayName => _displayName ?? name; + String get displayName => _displayName ?? name ?? ''; } /// A configuration class that can interpret category definitions from a YAML diff --git a/lib/src/generator/generator_utils.dart b/lib/src/generator/generator_utils.dart index 6766aa7e34..1be0c621d2 100644 --- a/lib/src/generator/generator_utils.dart +++ b/lib/src/generator/generator_utils.dart @@ -57,7 +57,7 @@ String generateSearchIndexJson( 'overriddenDepth': indexable.overriddenDepth, }; if (indexable is ModelElement) { - data['packageName'] = indexable.package.name; + data['packageName'] = indexable.package?.name; } if (indexable is EnclosedElement) { final ee = indexable as EnclosedElement; diff --git a/lib/src/model/categorization.dart b/lib/src/model/categorization.dart index 2861fe092b..92a70644e0 100644 --- a/lib/src/model/categorization.dart +++ b/lib/src/model/categorization.dart @@ -101,7 +101,7 @@ abstract class Categorization implements ModelElement { Iterable? get categories { _categories ??= categoryNames! - .map((n) => package.nameToCategory[n]) + .map((n) => package?.nameToCategory[n]) .where((c) => c != null) .toList() ..sort(); diff --git a/lib/src/model/category.dart b/lib/src/model/category.dart index 65c5b38a10..9df98fa039 100644 --- a/lib/src/model/category.dart +++ b/lib/src/model/category.dart @@ -32,7 +32,7 @@ class Category extends Nameable @override Package get package => _package; - final String _name; + final String? _name; final DartdocOptionContext _config; @@ -95,7 +95,7 @@ class Category extends Nameable String get name => categoryDefinition.displayName; @override - String get sortKey => _name; + String get sortKey => _name ?? ''; @override List get containerOrder => config.categoryOrder; diff --git a/lib/src/model/class.dart b/lib/src/model/class.dart index b745783a13..313b05c297 100644 --- a/lib/src/model/class.dart +++ b/lib/src/model/class.dart @@ -57,7 +57,11 @@ class Class extends InheritingContainer } assert(canonicalLibrary != null); assert(canonicalLibrary == library); - return '${package.baseHref}$filePath'; + var packageBaseHref = package?.baseHref; + if (packageBaseHref != null) { + return '$packageBaseHref$filePath'; + } + return null; } bool get isAbstract => element!.isAbstract; diff --git a/lib/src/model/constructor.dart b/lib/src/model/constructor.dart index b65c5b7fc5..7dd75ec22b 100644 --- a/lib/src/model/constructor.dart +++ b/lib/src/model/constructor.dart @@ -56,16 +56,6 @@ class Constructor extends ModelElement return '${library!.name}.$name'; } - @override - String? get href { - if (!identical(canonicalModelElement, this)) { - return canonicalModelElement?.href; - } - assert(canonicalLibrary != null); - assert(canonicalLibrary == library); - return '${package.baseHref}$filePath'; - } - @override bool get isConst => element!.isConst; diff --git a/lib/src/model/container.dart b/lib/src/model/container.dart index 6bc1ecac03..8ef2a4df17 100644 --- a/lib/src/model/container.dart +++ b/lib/src/model/container.dart @@ -36,6 +36,10 @@ abstract class Container extends ModelElement Container(Element element, Library? library, PackageGraph packageGraph) : super(element, library, packageGraph); + /// Containers must have associated libraries. + @override + Library get library => super.library!; + // TODO(jcollins-g): Implement a ContainerScope that flattens supertypes? @override Scope? get scope => null; diff --git a/lib/src/model/documentable.dart b/lib/src/model/documentable.dart index a81203259b..619c18517c 100644 --- a/lib/src/model/documentable.dart +++ b/lib/src/model/documentable.dart @@ -62,7 +62,7 @@ mixin MarkdownFileDocumentation implements Documentable, Canonicalization { String get documentation { final docFile = documentationFile; return docFile == null - ? null + ? '' : packageGraph.resourceProvider .readAsMalformedAllowedStringSync(docFile); } @@ -71,8 +71,7 @@ mixin MarkdownFileDocumentation implements Documentable, Canonicalization { bool get hasDocumentation => documentation?.isNotEmpty == true; @override - bool get hasExtendedDocumentation => - documentation != null && documentation.isNotEmpty; + bool get hasExtendedDocumentation => documentation.isNotEmpty; @override bool get isDocumented; @@ -83,7 +82,7 @@ mixin MarkdownFileDocumentation implements Documentable, Canonicalization { File? get documentationFile; @override - String get location => '(${documentationFile.path})'; + String get location => '(${documentationFile?.path})'; @override Set get locationPieces => {location}; diff --git a/lib/src/model/documentation.dart b/lib/src/model/documentation.dart index a50d9acee9..f34df083d6 100644 --- a/lib/src/model/documentation.dart +++ b/lib/src/model/documentation.dart @@ -8,6 +8,7 @@ import 'package:dartdoc/src/comment_references/model_comment_reference.dart'; import 'package:dartdoc/src/markdown_processor.dart'; import 'package:dartdoc/src/model/model.dart'; import 'package:dartdoc/src/render/documentation_renderer.dart'; +import 'package:dartdoc/src/warnings.dart'; import 'package:markdown/markdown.dart' as md; class Documentation { diff --git a/lib/src/model/documentation_comment.dart b/lib/src/model/documentation_comment.dart index f6f723262d..d3ab133575 100644 --- a/lib/src/model/documentation_comment.dart +++ b/lib/src/model/documentation_comment.dart @@ -1,11 +1,14 @@ +import 'package:analyzer/file_system/file_system.dart'; import 'package:args/args.dart'; import 'package:crypto/crypto.dart' as crypto; import 'package:dartdoc/src/model/documentable.dart'; import 'package:dartdoc/src/model/documentation.dart'; import 'package:dartdoc/src/model/inheritable.dart'; +import 'package:dartdoc/src/model/library.dart'; import 'package:dartdoc/src/model/locatable.dart'; +import 'package:dartdoc/src/model/package.dart'; import 'package:dartdoc/src/model/source_code_mixin.dart'; import 'package:dartdoc/src/render/model_element_renderer.dart'; import 'package:dartdoc/src/utils.dart'; @@ -51,7 +54,7 @@ mixin DocumentationComment /// to find docs, if the current class doesn't have docs /// for this element. @override - List? get documentationFrom => + List get documentationFrom => _documentationFrom ??= () { if (!hasDocumentationComment && this is Inheritable && @@ -284,13 +287,13 @@ mixin DocumentationComment 'SOURCE_COLUMN': characterLocation?.columnNumber.toString(), if (sourceFileName != null && package?.packagePath != null) 'SOURCE_PATH': - pathContext.relative(sourceFileName, from: package.packagePath), + pathContext.relative(sourceFileName, from: package!.packagePath), 'PACKAGE_PATH': package?.packagePath, 'PACKAGE_NAME': package?.name, 'LIBRARY_NAME': library?.fullyQualifiedName, 'ELEMENT_NAME': fullyQualifiedNameWithoutLibrary, 'INVOCATION_INDEX': invocationIndex.toString(), - 'PACKAGE_INVOCATION_INDEX': (package.toolInvocationIndex++).toString(), + 'PACKAGE_INVOCATION_INDEX': (package?.toolInvocationIndex++).toString(), }..removeWhere((key, value) => value == null); } @@ -311,7 +314,7 @@ mixin DocumentationComment /// {@example abc/def/xyz_component.dart region=template lang=html} /// String _injectExamples(String rawdocs) { - final dirPath = package.packageMeta.dir.path; + final dirPath = package?.packageMeta.dir.path; return rawdocs.replaceAllMapped(_examplePattern, (match) { var args = _getExampleArgs(match[1]!); if (args == null) { @@ -323,20 +326,24 @@ mixin DocumentationComment var replacement = match[0]; // default to fully matched string. - var fragmentFile = packageGraph.resourceProvider.getFile( - pathContext.canonicalize(pathContext.join(dirPath, args['file']))); - if (fragmentFile.exists) { + File? fragmentFile; + + if (dirPath != null) { + fragmentFile = packageGraph.resourceProvider.getFile( + pathContext.canonicalize(pathContext.join(dirPath, args['file']))); + } + if (fragmentFile != null && fragmentFile.exists == true) { replacement = fragmentFile.readAsStringSync(); if (lang.isNotEmpty) { replacement = replacement.replaceFirst('```', '```$lang'); } } else { - var filePath = element!.source!.fullName.substring(dirPath.length + 1); + var filePath = element!.source!.fullName.substring(dirPath?.length ?? -1 + 1); // TODO(srawlins): If a file exists at the location without the // appended 'md' extension, note this. warn(PackageWarning.missingExampleFile, - message: '${fragmentFile.path}; path listed at $filePath'); + message: '${fragmentFile?.path}; path listed at $filePath'); } return replacement!; }); @@ -510,7 +517,7 @@ mixin DocumentationComment var id = '$base$animationIdCount'; // We check for duplicate IDs so that we make sure not to collide with // user-supplied ids on the same page. - while (package.usedAnimationIdsByHref[href]!.contains(id)) { + while (package!.usedAnimationIdsByHref[href]!.contains(id)) { animationIdCount++; id = '$base$animationIdCount'; } @@ -519,7 +526,7 @@ mixin DocumentationComment return rawDocs.replaceAllMapped(_basicAnimationPattern, (basicMatch) { // Make sure we have a set to keep track of used IDs for this href. - package.usedAnimationIdsByHref[href] ??= {}; + package!.usedAnimationIdsByHref[href] ??= {}; var args = _parseArgs(basicMatch[1]!, _animationArgParser, 'animation'); if (args == null) { @@ -551,13 +558,13 @@ mixin DocumentationComment 'and must not begin with a number.'); return ''; } - if (package.usedAnimationIdsByHref[href]!.contains(uniqueId)) { + if (package!.usedAnimationIdsByHref[href]!.contains(uniqueId)) { warn(PackageWarning.invalidParameter, message: 'An animation has a non-unique identifier, "$uniqueId". ' 'Animation identifiers must be unique.'); return ''; } - package.usedAnimationIdsByHref[href]!.add(uniqueId); + package!.usedAnimationIdsByHref[href]!.add(uniqueId); int width; try { diff --git a/lib/src/model/enum.dart b/lib/src/model/enum.dart index bc0b23fd89..3012a04a48 100644 --- a/lib/src/model/enum.dart +++ b/lib/src/model/enum.dart @@ -56,7 +56,7 @@ class EnumField extends Field { String get constantValueBase => _fieldRenderer.renderValue(this); @override - List? get documentationFrom { + List get documentationFrom { if (name == 'values' || name == 'index') return [this]; return super.documentationFrom; } @@ -114,6 +114,12 @@ class EnumField extends Field { @override Inheritable? get overriddenElement => null; + @override + Package get package => super.package!; + + @override + Library get library => super.library!; + EnumFieldRenderer get _fieldRenderer => packageGraph.rendererFactory.enumFieldRenderer; } diff --git a/lib/src/model/extension.dart b/lib/src/model/extension.dart index 5615637cfc..0e9d249efb 100644 --- a/lib/src/model/extension.dart +++ b/lib/src/model/extension.dart @@ -69,7 +69,7 @@ class Extension extends Container implements EnclosedElement { @override List? get declaredFields { _declaredFields ??= _extension!.fields.map((f) { - Accessor getter, setter; + Accessor? getter, setter; if (f.getter != null) { getter = ContainerAccessor(f.getter, library, packageGraph); } @@ -109,16 +109,6 @@ class Extension extends Container implements EnclosedElement { @override String get filePath => '${library!.dirName}/$fileName'; - @override - String? get href { - if (!identical(canonicalModelElement, this)) { - return canonicalModelElement?.href; - } - assert(canonicalLibrary != null); - assert(canonicalLibrary == library); - return '${package.baseHref}$filePath'; - } - Map? _referenceChildren; @override Map get referenceChildren { diff --git a/lib/src/model/field.dart b/lib/src/model/field.dart index acc801f11b..97b474fdad 100644 --- a/lib/src/model/field.dart +++ b/lib/src/model/field.dart @@ -68,13 +68,8 @@ class Field extends ModelElement @override String? get href { - if (!identical(canonicalModelElement, this)) { - return canonicalModelElement?.href; - } - assert(canonicalLibrary != null); - assert(canonicalEnclosingContainer == enclosingElement); - assert(canonicalLibrary == library); - return '${package.baseHref}$filePath'; + assert(!identical(canonicalModelElement, this) || canonicalEnclosingContainer == enclosingElement); + return super.href; } @override diff --git a/lib/src/model/getter_setter_combo.dart b/lib/src/model/getter_setter_combo.dart index 02be89585b..55e6b12903 100644 --- a/lib/src/model/getter_setter_combo.dart +++ b/lib/src/model/getter_setter_combo.dart @@ -113,24 +113,21 @@ mixin GetterSetterCombo on ModelElement { @override bool get isPublic => hasPublicGetter || hasPublicSetter; - List? _documentationFrom; @override - List? get documentationFrom { - if (_documentationFrom == null) { - _documentationFrom = []; - if (hasPublicGetter) { - _documentationFrom!.addAll(getter!.documentationFrom!); - } else if (hasPublicSetter) { - _documentationFrom!.addAll(setter!.documentationFrom!); - } - if (_documentationFrom!.isEmpty || - _documentationFrom!.every((e) => e.documentationComment == '')) { - _documentationFrom = super.documentationFrom; - } + late final List documentationFrom = () { + var toReturn = []; + if (hasPublicGetter) { + toReturn.addAll(getter!.documentationFrom!); + } else if (hasPublicSetter) { + toReturn.addAll(setter!.documentationFrom!); } - return _documentationFrom; - } + if (toReturn.isEmpty || + toReturn.every((e) => e.documentationComment == '')) { + toReturn = super.documentationFrom; + } + return toReturn; + } (); bool get hasAccessorsWithDocs => (hasPublicGetter && !getter!.isSynthetic && getter!.hasDocumentation || @@ -225,7 +222,7 @@ mixin GetterSetterCombo on ModelElement { bool get hasParameters => hasSetter; @override - List? get parameters => setter!.parameters; + List get parameters => setter!.parameters; @override String? get linkedParamsNoMetadata { diff --git a/lib/src/model/inheritable.dart b/lib/src/model/inheritable.dart index 27c8b70fd1..63ede70450 100644 --- a/lib/src/model/inheritable.dart +++ b/lib/src/model/inheritable.dart @@ -170,18 +170,14 @@ mixin Inheritable on ContainerMember { return _isOverride; } - int? _overriddenDepth; - @override - int? get overriddenDepth { - if (_overriddenDepth == null) { - _overriddenDepth = 0; - Inheritable e = this; - while (e.overriddenElement != null) { - _overriddenDepth += 1; - e = e.overriddenElement!; - } + late final int overriddenDepth = () { + var depth = 0; + Inheritable e = this; + while (e.overriddenElement != null) { + depth += 1; + e = e.overriddenElement!; } - return _overriddenDepth; - } + return depth; + } (); } diff --git a/lib/src/model/inheriting_container.dart b/lib/src/model/inheriting_container.dart index 750d10d908..10f91e47fd 100644 --- a/lib/src/model/inheriting_container.dart +++ b/lib/src/model/inheriting_container.dart @@ -285,16 +285,6 @@ abstract class InheritingContainer extends Container bool get hasPublicSuperChainReversed => publicSuperChainReversed.isNotEmpty; - @override - String? get href { - if (!identical(canonicalModelElement, this)) { - return canonicalModelElement?.href; - } - assert(canonicalLibrary != null); - assert(canonicalLibrary == library); - return '${package.baseHref}$filePath'; - } - /*lazy final*/ List? _inheritedMethods; diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index 268d1c09a5..06947b3fa8 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -270,10 +270,11 @@ class Library extends ModelElement with Categorization, TopLevelContainer { _prefixToLibrary = {}; // It is possible to have overlapping prefixes. for (var i in element!.imports) { + var prefixName = i.prefix?.name; // Ignore invalid imports. - if (i.prefix?.name != null && i.importedLibrary != null) { + if (prefixName != null && i.importedLibrary != null) { _prefixToLibrary - .putIfAbsent(i.prefix?.name, () => {}) + .putIfAbsent(prefixName, () => {}) .add(modelBuilder.from(i.importedLibrary!, library) as Library); } } diff --git a/lib/src/model/method.dart b/lib/src/model/method.dart index a461cc2839..fe07e795bd 100644 --- a/lib/src/model/method.dart +++ b/lib/src/model/method.dart @@ -71,13 +71,8 @@ class Method extends ModelElement @override String? get href { - if (!identical(canonicalModelElement, this)) { - return canonicalModelElement?.href; - } - assert(!(canonicalLibrary == null || canonicalEnclosingContainer == null)); - assert(canonicalLibrary == library); - assert(canonicalEnclosingContainer == enclosingElement); - return '${package.baseHref}$filePath'; + assert(!identical(canonicalModelElement, this) || canonicalEnclosingContainer == enclosingElement); + return super.href; } @override diff --git a/lib/src/model/model_element.dart b/lib/src/model/model_element.dart index fec684dc3c..1a9ea65200 100644 --- a/lib/src/model/model_element.dart +++ b/lib/src/model/model_element.dart @@ -14,7 +14,7 @@ import 'package:analyzer/dart/element/type.dart' show FunctionType; import 'package:analyzer/source/line_info.dart'; // ignore: implementation_imports import 'package:analyzer/src/dart/element/member.dart' - show ExecutableMember, Member; + show ExecutableMember, Member, ParameterMember; import 'package:collection/collection.dart'; import 'package:dartdoc/src/comment_references/model_comment_reference.dart'; import 'package:dartdoc/src/dartdoc_options.dart'; @@ -424,38 +424,34 @@ abstract class ModelElement extends Canonicalization return utils.hasPublicName(element!) && !hasNodoc!; } (); - Map? _commentRefs; @override - Map? get commentRefs { - if (_commentRefs == null) { - _commentRefs = {}; - for (var from in documentationFrom!) { - var checkReferences = [from as ModelElement?]; + late final Map commentRefs = () { + var _commentRefs = {}; + for (var from in documentationFrom) { + if (from is ModelElement) { + var checkReferences = [from]; if (from is Accessor) { checkReferences.add(from.enclosingCombo); } for (var e in checkReferences) { // Some elements don't have modelNodes or aren't traversed by // the element visitor, or both. - assert(e is Parameter || e!.modelNode != null); - _commentRefs!.addAll({ - for (var r in e!.modelNode?.commentRefs ?? []) + assert(e is Parameter || e.modelNode != null); + _commentRefs.addAll({ + for (var r in e.modelNode?.commentRefs ?? + []) r.codeRef: r }); } } } return _commentRefs; - } + } (); - DartdocOptionContext? _config; @override - DartdocOptionContext? get config { - _config ??= DartdocOptionContext.fromContextElement( + late final DartdocOptionContext config = DartdocOptionContext.fromContextElement( packageGraph.config, library!.element!, packageGraph.resourceProvider); - return _config; - } Set? _locationPieces; @@ -690,7 +686,7 @@ abstract class ModelElement extends Canonicalization String get fileName => '$name.$fileType'; - String get fileType => package.fileType; + String get fileType => package!.fileType; String? get filePath; @@ -752,7 +748,18 @@ abstract class ModelElement extends Canonicalization /// If canonicalLibrary (or canonicalEnclosingElement, for Inheritable /// subclasses) is null, href should be null. @override - String? get href; + String? get href { + if (!identical(canonicalModelElement, this)) { + return canonicalModelElement?.href; + } + assert(canonicalLibrary != null); + assert(canonicalLibrary == library); + var packageBaseHref = package?.baseHref; + if (packageBaseHref != null) { + return '$packageBaseHref$filePath'; + } + return null; + } String? get htmlId => name; @@ -812,7 +819,7 @@ abstract class ModelElement extends Canonicalization String get kind; @override - Library get library => _library; + Library? get library => _library; String? get linkedName { _linkedName ??= _calculateLinkedName(); @@ -858,9 +865,9 @@ abstract class ModelElement extends Canonicalization PackageGraph get packageGraph => _packageGraph; @override - Package get package => library?.package; + Package? get package => library?.package; - bool get isPublicAndPackageDocumented => isPublic! && package.isDocumented; + bool get isPublicAndPackageDocumented => isPublic! && package?.isDocumented == true; List? _allParameters; diff --git a/lib/src/model/model_function.dart b/lib/src/model/model_function.dart index d53931f43a..9c2da97775 100644 --- a/lib/src/model/model_function.dart +++ b/lib/src/model/model_function.dart @@ -33,7 +33,7 @@ class ModelFunctionTypedef extends ModelFunctionTyped { : super(element, library, packageGraph); @override - String? get name => element!.enclosingElement!.name; + String get name => element!.enclosingElement!.name!; } class ModelFunctionTyped extends ModelElement @@ -84,6 +84,9 @@ class ModelFunctionTyped extends ModelElement return _referenceChildren!; } + @override + Package get package => super.package!; + @override Iterable get referenceParents => [definingLibrary]; diff --git a/lib/src/model/model_object_builder.dart b/lib/src/model/model_object_builder.dart index 1a7a53a014..c57cf521fc 100644 --- a/lib/src/model/model_object_builder.dart +++ b/lib/src/model/model_object_builder.dart @@ -22,8 +22,8 @@ abstract class ModelElementBuilder { ModelElement fromPropertyInducingElement(Element e, Library l, {Container enclosingContainer, - @required Accessor getter, - @required Accessor setter}); + required Accessor? getter, + required Accessor? setter}); } abstract class ElementTypeBuilder { diff --git a/lib/src/model/operator.dart b/lib/src/model/operator.dart index b0c5b940ed..8555050bd5 100644 --- a/lib/src/model/operator.dart +++ b/lib/src/model/operator.dart @@ -6,7 +6,7 @@ import 'package:analyzer/dart/element/element.dart'; // ignore: implementation_imports -import 'package:analyzer/src/dart/element/member.dart' show Member; +import 'package:analyzer/src/dart/element/member.dart' show ExecutableMember, Member; import 'package:dartdoc/src/comment_references/parser.dart'; import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index 34b3994b2b..bca154a846 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -278,7 +278,7 @@ class Package extends LibraryContainer return packageMeta.version; default: assert(false, 'Unsupported case: ${m.group(1)}'); - return null; + return ''; } }); } diff --git a/lib/src/model/source_code_mixin.dart b/lib/src/model/source_code_mixin.dart index 68d14d47d9..a0904e097f 100644 --- a/lib/src/model/source_code_mixin.dart +++ b/lib/src/model/source_code_mixin.dart @@ -17,7 +17,7 @@ abstract class SourceCodeMixin implements Documentable { bool get hasSourceCode => config!.includeSource && sourceCode!.isNotEmpty; - Library get library; + Library? get library; String? get sourceCode => modelNode == null ? '' : modelNode!.sourceCode; } diff --git a/lib/src/warnings.dart b/lib/src/warnings.dart index 36cbe48661..12a6139a5a 100644 --- a/lib/src/warnings.dart +++ b/lib/src/warnings.dart @@ -286,7 +286,7 @@ mixin Warnable implements Canonicalization, CommentReferable { Warnable? get enclosingElement; - Package get package; + Package? get package; void warn( PackageWarning kind, { From 983e42c2a106049560bcbed126b6e9eb3f10cb63 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 14 Oct 2021 16:37:35 -0700 Subject: [PATCH 08/21] no errors, ship it --- lib/src/model/annotation.dart | 6 ++--- lib/src/model/constructor.dart | 2 +- lib/src/model/container.dart | 4 +++ lib/src/model/enum.dart | 2 +- lib/src/model/extension.dart | 4 +-- lib/src/model/field.dart | 9 ++++--- lib/src/model/inheriting_container.dart | 4 +-- lib/src/model/model_element.dart | 6 +++-- lib/src/model/package.dart | 14 ++-------- lib/src/model/package_builder.dart | 1 + lib/src/model/package_graph.dart | 8 ++---- lib/src/model/parameter.dart | 6 ++--- lib/src/model/privacy.dart | 2 +- lib/src/model/top_level_variable.dart | 6 +++++ lib/src/model/type_parameter.dart | 35 ++++++++----------------- lib/src/model/typedef.dart | 6 +++++ lib/src/render/parameter_renderer.dart | 2 +- lib/src/warnings.dart | 4 +-- 18 files changed, 56 insertions(+), 65 deletions(-) diff --git a/lib/src/model/annotation.dart b/lib/src/model/annotation.dart index 161b6905e0..98b6a3f0c4 100644 --- a/lib/src/model/annotation.dart +++ b/lib/src/model/annotation.dart @@ -30,7 +30,7 @@ class Annotation extends Feature with ModelBuilder { /// Return the linked name of the annotation. @override - String? get linkedName => annotation.element is PropertyAccessorElement + String get linkedName => annotation.element is PropertyAccessorElement ? modelBuilder.fromElement(annotation.element!).linkedName // TODO(jcollins-g): consider linking to constructor instead of type? : modelType!.linkedName; @@ -54,7 +54,7 @@ class Annotation extends Feature with ModelBuilder { } String? _parameterText; - String? get parameterText { + String get parameterText { // TODO(srawlins): Attempt to revive constructor arguments in an annotation, // akin to source_gen's Reviver, in order to link to inner components. For // example, in `@Foo(const Bar(), baz: [Baz.one, Baz.two])`, link to @@ -65,7 +65,7 @@ class Annotation extends Feature with ModelBuilder { _parameterText = source.substring(startIndex == -1 ? source.length : startIndex); } - return _parameterText; + return _parameterText!; } @override diff --git a/lib/src/model/constructor.dart b/lib/src/model/constructor.dart index 7dd75ec22b..a15ce5e41f 100644 --- a/lib/src/model/constructor.dart +++ b/lib/src/model/constructor.dart @@ -33,7 +33,7 @@ class Constructor extends ModelElement @override // TODO(jcollins-g): Revisit this when dart-lang/sdk#31517 is implemented. - List? get typeParameters => + List get typeParameters => (enclosingElement as Class).typeParameters; @override diff --git a/lib/src/model/container.dart b/lib/src/model/container.dart index 8ef2a4df17..18fef1d2c1 100644 --- a/lib/src/model/container.dart +++ b/lib/src/model/container.dart @@ -40,6 +40,10 @@ abstract class Container extends ModelElement @override Library get library => super.library!; + /// Containers must have associated packages. + @override + Package get package => super.package!; + // TODO(jcollins-g): Implement a ContainerScope that flattens supertypes? @override Scope? get scope => null; diff --git a/lib/src/model/enum.dart b/lib/src/model/enum.dart index 3012a04a48..732840d5b7 100644 --- a/lib/src/model/enum.dart +++ b/lib/src/model/enum.dart @@ -92,7 +92,7 @@ class EnumField extends Field { } @override - String? get linkedName => name; + String get linkedName => name; @override bool get isCanonical { diff --git a/lib/src/model/extension.dart b/lib/src/model/extension.dart index 0e9d249efb..b2b4763eca 100644 --- a/lib/src/model/extension.dart +++ b/lib/src/model/extension.dart @@ -86,12 +86,12 @@ class Extension extends Container implements EnclosedElement { // a stronger hash? @override - List? get typeParameters { + List get typeParameters { _typeParameters ??= _extension!.typeParameters.map((f) { var lib = modelBuilder.fromElement(f.enclosingElement!.library!); return modelBuilder.from(f, lib as Library) as TypeParameter; }).toList(); - return _typeParameters; + return _typeParameters!; } List? _allModelElements; diff --git a/lib/src/model/field.dart b/lib/src/model/field.dart index 97b474fdad..3264fa67f4 100644 --- a/lib/src/model/field.dart +++ b/lib/src/model/field.dart @@ -57,10 +57,7 @@ class Field extends ModelElement } @override - Container? get enclosingElement { - _enclosingContainer ??= modelBuilder.from(field!.enclosingElement, library!) as Container?; - return _enclosingContainer; - } + Container get enclosingElement => modelBuilder.from(field!.enclosingElement, library) as Container; @override String get filePath => @@ -167,6 +164,10 @@ class Field extends ModelElement return _sourceCode; } + Library get library => super.library!; + + Package get package => super.package!; + @override Inheritable? get overriddenElement => null; } diff --git a/lib/src/model/inheriting_container.dart b/lib/src/model/inheriting_container.dart index 10f91e47fd..48a11b3412 100644 --- a/lib/src/model/inheriting_container.dart +++ b/lib/src/model/inheriting_container.dart @@ -588,12 +588,12 @@ abstract class InheritingContainer extends Container List? _typeParameters; @override - List? get typeParameters { + List get typeParameters { _typeParameters ??= element!.typeParameters.map((f) { var lib = modelBuilder.fromElement(f.enclosingElement!.library!); return modelBuilder.from(f, lib as Library) as TypeParameter; }).toList(); - return _typeParameters; + return _typeParameters!; } Iterable? _instanceFields; diff --git a/lib/src/model/model_element.dart b/lib/src/model/model_element.dart index 1a9ea65200..39dbb4aba3 100644 --- a/lib/src/model/model_element.dart +++ b/lib/src/model/model_element.dart @@ -819,11 +819,12 @@ abstract class ModelElement extends Canonicalization String get kind; @override + // FIXME(nnbd): library should not have to be nullable just because of dynamic Library? get library => _library; - String? get linkedName { + String get linkedName { _linkedName ??= _calculateLinkedName(); - return _linkedName; + return _linkedName!; } @visibleForTesting @@ -865,6 +866,7 @@ abstract class ModelElement extends Canonicalization PackageGraph get packageGraph => _packageGraph; @override + // FIXME(nnbd): package should not have to be nullable just because of dynamic Package? get package => library?.package; bool get isPublicAndPackageDocumented => isPublic! && package?.isDocumented == true; diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index bca154a846..2041817f5f 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -155,13 +155,8 @@ class Package extends LibraryContainer @override Warnable? get enclosingElement => null; - bool? _isPublic; - @override - bool? get isPublic { - _isPublic ??= libraries.any((l) => l.isPublic); - return _isPublic; - } + late final bool isPublic = libraries.any((l) => l.isPublic); bool? _isLocal; @@ -354,16 +349,11 @@ class Package extends LibraryContainer bool get hasDocumentedCategories => documentedCategories.isNotEmpty; - DartdocOptionContext? _config; - @override - DartdocOptionContext? get config { - _config ??= DartdocOptionContext.fromContext( + late final DartdocOptionContext config = DartdocOptionContext.fromContext( packageGraph.config, packageGraph.resourceProvider.getFolder(packagePath!), packageGraph.resourceProvider); - return _config; - } /// Is this the package at the top of the list? We display the first /// package specially (with "Libraries" rather than the package name). diff --git a/lib/src/model/package_builder.dart b/lib/src/model/package_builder.dart index 2b44f91137..75754f43fa 100644 --- a/lib/src/model/package_builder.dart +++ b/lib/src/model/package_builder.dart @@ -35,6 +35,7 @@ import 'package:dartdoc/src/quiver.dart' as quiver; import 'package:dartdoc/src/render/renderer_factory.dart'; import 'package:dartdoc/src/special_elements.dart'; import 'package:meta/meta.dart'; +import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as path show Context; /// Everything you need to instantiate a PackageGraph object for documenting. diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index 695570afa2..acf782c44f 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -51,7 +51,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { } @override - String? get name => null; + String get name => ''; /// Call during initialization to add a library to this [PackageGraph]. /// @@ -269,7 +269,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { Map? get sdkLibrarySources { if (_sdkLibrarySources == null) { _sdkLibrarySources = {}; - for (var lib in sdk?.sdkLibraries) { + for (var lib in sdk.sdkLibraries) { _sdkLibrarySources![sdk.mapDartUri(lib.shortName)] = lib; } } @@ -882,10 +882,6 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// set of canonical Libraries). Library findOrCreateLibraryFor(DartDocResolvedLibrary resolvedLibrary) { final libraryElement = resolvedLibrary.library; - // can be null if e is for dynamic - if (libraryElement == null) { - return null; - } var foundLibrary = findButDoNotCreateLibraryFor(libraryElement); if (foundLibrary != null) return foundLibrary; diff --git a/lib/src/model/parameter.dart b/lib/src/model/parameter.dart index ebab4ff88e..62e4a0b714 100644 --- a/lib/src/model/parameter.dart +++ b/lib/src/model/parameter.dart @@ -22,9 +22,7 @@ class Parameter extends ModelElement implements EnclosedElement { } @override - ModelElement? get enclosingElement => (element!.enclosingElement != null) - ? modelBuilder.from(element!.enclosingElement!, library!) - : null; + ModelElement get enclosingElement => modelBuilder.from(element!.enclosingElement!, library!); bool get hasDefaultValue { return element!.defaultValueCode != null && @@ -103,7 +101,7 @@ class Parameter extends ModelElement implements EnclosedElement { } @override - Iterable get referenceParents => [enclosingElement]; + Iterable get referenceParents => [enclosingElement]; @override ParameterElement? get element => super.element as ParameterElement?; diff --git a/lib/src/model/privacy.dart b/lib/src/model/privacy.dart index ec1e9b3e82..af4ee55725 100644 --- a/lib/src/model/privacy.dart +++ b/lib/src/model/privacy.dart @@ -6,5 +6,5 @@ /// Classes implementing this have a public/private distinction. abstract class Privacy { - bool? get isPublic; + bool get isPublic; } diff --git a/lib/src/model/top_level_variable.dart b/lib/src/model/top_level_variable.dart index c26e7f6c48..d86b6cb514 100644 --- a/lib/src/model/top_level_variable.dart +++ b/lib/src/model/top_level_variable.dart @@ -84,6 +84,12 @@ class TopLevelVariable extends ModelElement TopLevelVariableElement? get _variable => (element as TopLevelVariableElement?); + @override + Package get package => super.package!; + + @override + Library get library => super.library!; + @override Iterable get referenceParents => [definingLibrary]; } diff --git a/lib/src/model/type_parameter.dart b/lib/src/model/type_parameter.dart index 65654a4919..f33405e145 100644 --- a/lib/src/model/type_parameter.dart +++ b/lib/src/model/type_parameter.dart @@ -16,9 +16,7 @@ class TypeParameter extends ModelElement { : super(element, library, packageGraph); @override - ModelElement? get enclosingElement => (element!.enclosingElement != null) - ? modelBuilder.from(element!.enclosingElement!, library!) - : null; + ModelElement get enclosingElement => modelBuilder.from(element!.enclosingElement!, library!); @override String get filePath => @@ -47,41 +45,30 @@ class TypeParameter extends ModelElement { @override bool get hasParameters => false; - String? _name; - @override - String? get name { - _name ??= element!.bound != null + late final String name = element!.bound != null ? '${element!.name} extends ${boundType!.nameWithGenerics}' : element!.name; - return _name; - } String? _linkedName; @override - String? get linkedName { + String get linkedName { _linkedName ??= element!.bound != null ? '${element!.name} extends ${boundType!.linkedName}' : element!.name; - return _linkedName; + return _linkedName!; } - Map? _referenceChildren; - @override - Map get referenceChildren { - if (_referenceChildren == null) { - _referenceChildren = {}; - if (boundType != null) { - _referenceChildren![boundType!.name] = boundType; - } - } - return _referenceChildren!; - } + late final Map referenceChildren = () { + var boundType = this.boundType; + if (boundType == null) return {}; + return {boundType.name: boundType}; + } (); @override - Iterable get referenceParents => [enclosingElement]; + Iterable get referenceParents => [enclosingElement]; @override TypeParameterElement? get element => super.element as TypeParameterElement?; @@ -102,7 +89,7 @@ mixin TypeParameters implements ModelElement { String get linkedGenericParameters => _typeParametersRenderer.renderLinkedGenericParameters(this); - List? get typeParameters; + List get typeParameters; TypeParametersRenderer get _typeParametersRenderer => packageGraph.rendererFactory.typeParametersRenderer; diff --git a/lib/src/model/typedef.dart b/lib/src/model/typedef.dart index d2a84a7247..f1f87990b3 100644 --- a/lib/src/model/typedef.dart +++ b/lib/src/model/typedef.dart @@ -62,6 +62,12 @@ abstract class Typedef extends ModelElement @override String get kind => 'typedef'; + @override + Library get library => super.library!; + + @override + Package get package => super.package!; + @override List get typeParameters => element!.typeParameters.map((f) { return modelBuilder.from(f, library!) as TypeParameter; diff --git a/lib/src/render/parameter_renderer.dart b/lib/src/render/parameter_renderer.dart index d12d0d0c66..aad9feea19 100644 --- a/lib/src/render/parameter_renderer.dart +++ b/lib/src/render/parameter_renderer.dart @@ -225,7 +225,7 @@ abstract class ParameterRenderer { if (param.hasDefaultValue) { buf.write(' = '); - buf.write(defaultValue(param.defaultValue)); + buf.write(defaultValue(param.defaultValue!)); } buf.write(suffix); diff --git a/lib/src/warnings.dart b/lib/src/warnings.dart index 12a6139a5a..f591a2c85f 100644 --- a/lib/src/warnings.dart +++ b/lib/src/warnings.dart @@ -503,7 +503,7 @@ class PackageWarningCounter { _items.add(_JsonWarning(type, kind, fullMessage, entry)); } for (var item in _items) { - logWarning(item); + logWarning(item.toString()); } _items.clear(); } @@ -534,7 +534,7 @@ class PackageWarningCounter { PackageWarningOptionContext config = element?.config ?? packageGraph.defaultPackage.config; PackageWarningMode? warningMode; - var isLocal = element?.package.isLocal ?? true; + var isLocal = element?.package?.isLocal ?? true; if (!config.allowNonLocalWarnings && !isLocal) { warningMode = PackageWarningMode.ignore; } else { From 5672bde88610c094fb5272dcc186991d8f39104d Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 14 Oct 2021 16:51:38 -0700 Subject: [PATCH 09/21] clean up a lot of warnings --- lib/src/model/accessor.dart | 22 ++++---- lib/src/model/annotation.dart | 2 +- lib/src/model/categorization.dart | 2 +- lib/src/model/class.dart | 6 +-- lib/src/model/constructor.dart | 8 +-- lib/src/model/container.dart | 6 +-- lib/src/model/container_member.dart | 4 +- lib/src/model/documentable.dart | 2 +- lib/src/model/documentation_comment.dart | 28 +++++----- lib/src/model/enum.dart | 6 +-- lib/src/model/extension.dart | 10 ++-- lib/src/model/field.dart | 2 +- lib/src/model/getter_setter_combo.dart | 30 +++++------ lib/src/model/inheritable.dart | 4 +- lib/src/model/inheriting_container.dart | 40 +++++++------- lib/src/model/library.dart | 68 +++++++++++------------- lib/src/model/locatable.dart | 2 +- lib/src/model/method.dart | 2 +- lib/src/model/mixin.dart | 2 +- lib/src/model/model_element.dart | 44 +++++++-------- lib/src/model/model_function.dart | 2 +- lib/src/model/nameable.dart | 8 +-- lib/src/model/operator.dart | 4 +- lib/src/model/package.dart | 30 +++++------ lib/src/model/package_graph.dart | 18 +++---- lib/src/model/prefix.dart | 2 +- lib/src/model/source_code_mixin.dart | 2 +- lib/src/model/top_level_variable.dart | 2 +- lib/src/model/type_parameter.dart | 4 +- lib/src/model/typedef.dart | 8 +-- 30 files changed, 181 insertions(+), 189 deletions(-) diff --git a/lib/src/model/accessor.dart b/lib/src/model/accessor.dart index cfa80af228..6a13baa87b 100644 --- a/lib/src/model/accessor.dart +++ b/lib/src/model/accessor.dart @@ -32,7 +32,7 @@ class Accessor extends ModelElement implements EnclosedElement { if (element!.nameOffset < 0) { assert(element!.isSynthetic, 'Invalid offset for non-synthetic element'); // TODO(jcollins-g): switch to [element.nonSynthetic] after analyzer 1.8 - return enclosingCombo!.characterLocation; + return enclosingCombo.characterLocation; } return super.characterLocation; } @@ -95,7 +95,7 @@ class Accessor extends ModelElement implements EnclosedElement { /// Value here is not useful if [isSynthetic] is false. late final String _syntheticDocumentationComment = () { if (_hasSyntheticDocumentationComment) { - return definingCombo!.documentationComment ?? ''; + return definingCombo!.documentationComment; } return ''; } (); @@ -114,7 +114,7 @@ class Accessor extends ModelElement implements EnclosedElement { bool _comboDocsAreIndependent() { if (isSetter && definingCombo!.hasGetter) { if (definingCombo!.getter!.isSynthetic || - !definingCombo!.documentationFrom!.contains(this)) { + !definingCombo!.documentationFrom.contains(this)) { return true; } } @@ -133,7 +133,7 @@ class Accessor extends ModelElement implements EnclosedElement { Iterable referredFrom = const [], Iterable extendedDebug = const [], }) { - enclosingCombo!.warn(kind, + enclosingCombo.warn(kind, message: message, referredFrom: referredFrom, extendedDebug: extendedDebug); @@ -150,14 +150,14 @@ class Accessor extends ModelElement implements EnclosedElement { } @override - String? get filePath => enclosingCombo!.filePath; + String? get filePath => enclosingCombo.filePath; @override - bool get isCanonical => enclosingCombo!.isCanonical; + bool get isCanonical => enclosingCombo.isCanonical; @override String? get href { - return enclosingCombo!.href; + return enclosingCombo.href; } bool get isGetter => element!.isGetter; @@ -180,14 +180,14 @@ class Accessor extends ModelElement implements EnclosedElement { /// Accessors should never be participating directly in comment reference /// lookups. Map get referenceChildren => - enclosingCombo!.referenceChildren; + enclosingCombo.referenceChildren; @override /// Accessors should never be participating directly in comment reference /// lookups. Iterable get referenceParents => - enclosingCombo!.referenceParents; + enclosingCombo.referenceParents; } /// A getter or setter that is a member of a [Container]. @@ -201,7 +201,7 @@ class ContainerAccessor extends Accessor with ContainerMember, Inheritable { if (_isEnumSynthetic) return enclosingElement!.characterLocation; // TODO(jcollins-g): Remove the enclosingCombo case below once // https://github.com/dart-lang/sdk/issues/46154 is fixed. - if (enclosingCombo is EnumField) return enclosingCombo!.characterLocation; + if (enclosingCombo is EnumField) return enclosingCombo.characterLocation; return super.characterLocation; } @@ -209,7 +209,7 @@ class ContainerAccessor extends Accessor with ContainerMember, Inheritable { bool _isInherited = false; @override - bool get isCovariant => isSetter && parameters!.first.isCovariant; + bool get isCovariant => isSetter && parameters.first.isCovariant; ContainerAccessor(PropertyAccessorElement? element, Library? library, PackageGraph packageGraph) diff --git a/lib/src/model/annotation.dart b/lib/src/model/annotation.dart index 98b6a3f0c4..233efcb903 100644 --- a/lib/src/model/annotation.dart +++ b/lib/src/model/annotation.dart @@ -70,7 +70,7 @@ class Annotation extends Feature with ModelBuilder { @override bool get isPublic => - modelType!.isPublic! && + modelType!.isPublic&& modelType is DefinedElementType && !packageGraph.invisibleAnnotations .contains((modelType as DefinedElementType).modelElement); diff --git a/lib/src/model/categorization.dart b/lib/src/model/categorization.dart index 92a70644e0..11c1d6c032 100644 --- a/lib/src/model/categorization.dart +++ b/lib/src/model/categorization.dart @@ -110,7 +110,7 @@ abstract class Categorization implements ModelElement { @override Iterable? get displayedCategories { - if (config!.showUndocumentedCategories) return categories; + if (config.showUndocumentedCategories) return categories; return categories!.where((c) => c!.isDocumented); } diff --git a/lib/src/model/class.dart b/lib/src/model/class.dart index 313b05c297..93d0bcd845 100644 --- a/lib/src/model/class.dart +++ b/lib/src/model/class.dart @@ -42,7 +42,7 @@ class Class extends InheritingContainer String get fileName => '$name-class.$fileType'; @override - String get filePath => '${library!.dirName}/$fileName'; + String get filePath => '${library.dirName}/$fileName'; @override String get fullkind { @@ -57,7 +57,7 @@ class Class extends InheritingContainer } assert(canonicalLibrary != null); assert(canonicalLibrary == library); - var packageBaseHref = package?.baseHref; + var packageBaseHref = package.baseHref; if (packageBaseHref != null) { return '$packageBaseHref$filePath'; } @@ -67,7 +67,7 @@ class Class extends InheritingContainer bool get isAbstract => element!.isAbstract; @override - bool get isCanonical => super.isCanonical && isPublic!; + bool get isCanonical => super.isCanonical && isPublic; bool get isErrorOrException { bool _doCheck(ClassElement element) { diff --git a/lib/src/model/constructor.dart b/lib/src/model/constructor.dart index a15ce5e41f..53d3505078 100644 --- a/lib/src/model/constructor.dart +++ b/lib/src/model/constructor.dart @@ -97,8 +97,8 @@ class Constructor extends ModelElement } (); String? get shortName { - if (name!.contains('.')) { - return name!.substring(element!.enclosingElement.name.length + 1); + if (name.contains('.')) { + return name.substring(element!.enclosingElement.name.length + 1); } else { return name; } @@ -116,12 +116,12 @@ class Constructor extends ModelElement } return param; }).generateEntries()); - _referenceChildren!.addEntries(typeParameters!.generateEntries()); + _referenceChildren!.addEntries(typeParameters.generateEntries()); } return _referenceChildren!; } @override String get referenceName => - isUnnamedConstructor ? enclosingElement.name! : element!.name; + isUnnamedConstructor ? enclosingElement.name: element!.name; } diff --git a/lib/src/model/container.dart b/lib/src/model/container.dart index 18fef1d2c1..5181486adb 100644 --- a/lib/src/model/container.dart +++ b/lib/src/model/container.dart @@ -69,7 +69,7 @@ abstract class Container extends ModelElement Iterable? get allModelElements => quiver.concat([ instanceMethods, instanceFields, - instanceOperators!, + instanceOperators, instanceAccessors, staticFields, staticAccessors, @@ -133,7 +133,7 @@ abstract class Container extends ModelElement @nonVirtual Iterable get publicInstanceOperators => - model_utils.filterNonPublic(instanceOperators!); + model_utils.filterNonPublic(instanceOperators); List? _publicInstanceOperatorsSorted; List get publicInstanceOperatorsSorted => @@ -280,7 +280,7 @@ abstract class Container extends ModelElement // here to wean people off the habit of unscoped parameter references. if (modelElement.hasParameters) { _referenceChildren! - .addEntriesIfAbsent(modelElement.parameters!.generateEntries()); + .addEntriesIfAbsent(modelElement.parameters.generateEntries()); } } _referenceChildren!['this'] = this; diff --git a/lib/src/model/container_member.dart b/lib/src/model/container_member.dart index db00cfd08a..4cf3b00f38 100644 --- a/lib/src/model/container_member.dart +++ b/lib/src/model/container_member.dart @@ -68,14 +68,14 @@ mixin ContainerMember on ModelElement implements EnclosedElement { // references are resolved wrt documentation inheritance, // that has to be resolved in the source by not inheriting // documentation. - [enclosingElement as Container, documentationFrom!.first.enclosingElement as Container]; + [enclosingElement as Container, documentationFrom.first.enclosingElement as Container]; @override Iterable get referenceGrandparentOverrides sync* { // TODO(jcollins-g): split Field documentation up between accessors // and resolve the pieces with different scopes. dart-lang/dartdoc#2693. // Until then, just pretend we're handling this correctly. - yield (documentationFrom!.first as ModelElement).definingLibrary; + yield (documentationFrom.first as ModelElement).definingLibrary; // TODO(jcollins-g): Wean users off of depending on canonical library // resolution. dart-lang/dartdoc#2696 if (canonicalLibrary != null) yield canonicalLibrary!; diff --git a/lib/src/model/documentable.dart b/lib/src/model/documentable.dart index 619c18517c..7fec6286f3 100644 --- a/lib/src/model/documentable.dart +++ b/lib/src/model/documentable.dart @@ -68,7 +68,7 @@ mixin MarkdownFileDocumentation implements Documentable, Canonicalization { } @override - bool get hasDocumentation => documentation?.isNotEmpty == true; + bool get hasDocumentation => documentation.isNotEmpty == true; @override bool get hasExtendedDocumentation => documentation.isNotEmpty; diff --git a/lib/src/model/documentation_comment.dart b/lib/src/model/documentation_comment.dart index d3ab133575..6c75ddeaad 100644 --- a/lib/src/model/documentation_comment.dart +++ b/lib/src/model/documentation_comment.dart @@ -6,9 +6,7 @@ import 'package:crypto/crypto.dart' as crypto; import 'package:dartdoc/src/model/documentable.dart'; import 'package:dartdoc/src/model/documentation.dart'; import 'package:dartdoc/src/model/inheritable.dart'; -import 'package:dartdoc/src/model/library.dart'; import 'package:dartdoc/src/model/locatable.dart'; -import 'package:dartdoc/src/model/package.dart'; import 'package:dartdoc/src/model/source_code_mixin.dart'; import 'package:dartdoc/src/render/model_element_renderer.dart'; import 'package:dartdoc/src/utils.dart'; @@ -142,7 +140,7 @@ mixin DocumentationComment return docs; } - String get sourceFileName; + String? get sourceFileName; String? get fullyQualifiedNameWithoutLibrary; @@ -257,7 +255,7 @@ mixin DocumentationComment /// ## Content to send to tool. /// 2018-09-18T21:15+00:00 Future _evaluateTools(String rawDocs) async { - if (!config!.allowTools) { + if (!config.allowTools) { return rawDocs; } var invocationIndex = 0; @@ -273,7 +271,7 @@ mixin DocumentationComment // Count the number of invocations of tools in this dartdoc block, // so that tools can differentiate different blocks from each other. invocationIndex++; - return await config!.tools.runner.run(args, content: basicMatch[2]!, + return await config.tools.runner.run(args, content: basicMatch[2]!, toolErrorCallback: (String message) async { warn(PackageWarning.toolError, message: message); }, environment: _toolsEnvironment(invocationIndex: invocationIndex) as Map); @@ -287,7 +285,7 @@ mixin DocumentationComment 'SOURCE_COLUMN': characterLocation?.columnNumber.toString(), if (sourceFileName != null && package?.packagePath != null) 'SOURCE_PATH': - pathContext.relative(sourceFileName, from: package!.packagePath), + pathContext.relative(sourceFileName!, from: package!.packagePath), 'PACKAGE_PATH': package?.packagePath, 'PACKAGE_NAME': package?.name, 'LIBRARY_NAME': library?.fullyQualifiedName, @@ -386,9 +384,9 @@ mixin DocumentationComment var ext = pathContext.extension(src); file = pathContext.join(dir, '$basename-$region$ext$fragExtension'); } - args['file'] = config!.examplePathPrefix == null + args['file'] = config.examplePathPrefix == null ? file - : pathContext.join(config!.examplePathPrefix, file); + : pathContext.join(config.examplePathPrefix, file); return args; } @@ -643,7 +641,7 @@ mixin DocumentationComment /// {@end-inject-html} /// String _stripHtmlAndAddToIndex(String rawDocs) { - if (!config!.injectHtml) return rawDocs; + if (!config.injectHtml) return rawDocs; return rawDocs.replaceAllMapped(_htmlPattern, (match) { var fragment = match[1]!; var digest = crypto.sha1.convert(fragment.codeUnits).toString(); @@ -770,7 +768,7 @@ mixin DocumentationComment bool? _needsPrecache; bool get needsPrecache => _needsPrecache ??= - _needsPrecacheRegExp.hasMatch(documentationComment ?? ''); + _needsPrecacheRegExp.hasMatch(documentationComment); String? _rawDocs; @@ -786,10 +784,10 @@ mixin DocumentationComment 'reentrant calls to _buildDocumentation* not allowed'); // Do not use the sync method if we need to evaluate tools or templates. assert(!isCanonical || !needsPrecache); - if (config!.dropTextFrom.contains(element!.library!.name)) { + if (config.dropTextFrom.contains(element!.library!.name)) { _rawDocs = ''; } else { - _rawDocs = _processCommentWithoutTools(documentationComment ?? ''); + _rawDocs = _processCommentWithoutTools(documentationComment); } _rawDocs = buildDocumentationAddition(_rawDocs); return _rawDocs; @@ -801,10 +799,10 @@ mixin DocumentationComment assert(_rawDocs == null, 'reentrant calls to _buildDocumentation* not allowed'); // Do not use the sync method if we need to evaluate tools or templates. - if (config!.dropTextFrom.contains(element!.library!.name)) { + if (config.dropTextFrom.contains(element!.library!.name)) { _rawDocs = ''; } else { - _rawDocs = await processComment(documentationComment ?? ''); + _rawDocs = await processComment(documentationComment); } _rawDocs = buildDocumentationAddition(_rawDocs); return _rawDocs; @@ -845,7 +843,7 @@ mixin DocumentationComment /// And the HTML fragment will not have been processed or changed by Markdown, /// but just injected verbatim. String? _injectHtmlFragments(String? rawDocs) { - if (!config!.injectHtml) return rawDocs; + if (!config.injectHtml) return rawDocs; return rawDocs!.replaceAllMapped(_htmlInjectRegExp, (match) { var fragment = packageGraph.getHtmlFragment(match[1])!; diff --git a/lib/src/model/enum.dart b/lib/src/model/enum.dart index 732840d5b7..f21203dc52 100644 --- a/lib/src/model/enum.dart +++ b/lib/src/model/enum.dart @@ -88,7 +88,7 @@ class EnumField extends Field { assert(!(canonicalLibrary == null || canonicalEnclosingContainer == null)); assert(canonicalLibrary == library); assert(canonicalEnclosingContainer == enclosingElement); - return '${package.baseHref}${enclosingElement!.library!.dirName}/${enclosingElement!.fileName}'; + return '${package.baseHref}${enclosingElement.library.dirName}/${enclosingElement.fileName}'; } @override @@ -115,10 +115,10 @@ class EnumField extends Field { Inheritable? get overriddenElement => null; @override - Package get package => super.package!; + Package get package => super.package; @override - Library get library => super.library!; + Library get library => super.library; EnumFieldRenderer get _fieldRenderer => packageGraph.rendererFactory.enumFieldRenderer; diff --git a/lib/src/model/extension.dart b/lib/src/model/extension.dart index b2b4763eca..e643b263f4 100644 --- a/lib/src/model/extension.dart +++ b/lib/src/model/extension.dart @@ -56,13 +56,13 @@ class Extension extends Container implements EnclosedElement { @override List? get declaredMethods { _methods ??= _extension!.methods.map((e) { - return modelBuilder.from(e, library!) as Method; + return modelBuilder.from(e, library) as Method; }).toList(growable: false); return _methods; } @override - String get name => super.name ?? ''; + String get name => super.name; List? _declaredFields; @@ -76,7 +76,7 @@ class Extension extends Container implements EnclosedElement { if (f.setter != null) { setter = ContainerAccessor(f.setter, library, packageGraph); } - return modelBuilder.fromPropertyInducingElement(f, library!, + return modelBuilder.fromPropertyInducingElement(f, library, getter: getter, setter: setter) as Field; }).toList(growable: false); return _declaredFields; @@ -100,14 +100,14 @@ class Extension extends Container implements EnclosedElement { _allModelElements ??= List.from( quiver.concat([ super.allModelElements!, - typeParameters!, + typeParameters, ]), growable: false); return _allModelElements; } @override - String get filePath => '${library!.dirName}/$fileName'; + String get filePath => '${library.dirName}/$fileName'; Map? _referenceChildren; @override diff --git a/lib/src/model/field.dart b/lib/src/model/field.dart index 3264fa67f4..f239ef3d29 100644 --- a/lib/src/model/field.dart +++ b/lib/src/model/field.dart @@ -61,7 +61,7 @@ class Field extends ModelElement @override String get filePath => - '${enclosingElement!.library!.dirName}/${enclosingElement!.name}/$fileName'; + '${enclosingElement.library.dirName}/${enclosingElement.name}/$fileName'; @override String? get href { diff --git a/lib/src/model/getter_setter_combo.dart b/lib/src/model/getter_setter_combo.dart index 55e6b12903..8a7845f44f 100644 --- a/lib/src/model/getter_setter_combo.dart +++ b/lib/src/model/getter_setter_combo.dart @@ -72,7 +72,7 @@ mixin GetterSetterCombo on ModelElement { // TODO(jcollins-g): this logic really should be integrated into Constructor, // but that's not trivial because of linkedName's usage. if (targetClass.name == target.name) { - return original.replaceAll(constructorName, target.linkedName!); + return original.replaceAll(constructorName, target.linkedName); } return original.replaceAll('${targetClass.name}.${target.name}', '${targetClass.linkedName}.${target.linkedName}'); @@ -106,9 +106,9 @@ mixin GetterSetterCombo on ModelElement { String get constantValueBase => _constantValueBase ??= _buildConstantValueBase(); - bool get hasPublicGetter => hasGetter && getter!.isPublic!; + bool get hasPublicGetter => hasGetter && getter!.isPublic; - bool get hasPublicSetter => hasSetter && setter!.isPublic!; + bool get hasPublicSetter => hasSetter && setter!.isPublic; @override bool get isPublic => hasPublicGetter || hasPublicSetter; @@ -118,9 +118,9 @@ mixin GetterSetterCombo on ModelElement { late final List documentationFrom = () { var toReturn = []; if (hasPublicGetter) { - toReturn.addAll(getter!.documentationFrom!); + toReturn.addAll(getter!.documentationFrom); } else if (hasPublicSetter) { - toReturn.addAll(setter!.documentationFrom!); + toReturn.addAll(setter!.documentationFrom); } if (toReturn.isEmpty || toReturn.every((e) => e.documentationComment == '')) { @@ -185,22 +185,22 @@ mixin GetterSetterCombo on ModelElement { var buffer = StringBuffer(); // Check for synthetic before public, always, or stack overflow. - if (hasGetter && !getter!.isSynthetic && getter!.isPublic!) { - assert(getter!.documentationFrom!.length == 1); - var fromGetter = getter!.documentationFrom!.first; + if (hasGetter && !getter!.isSynthetic && getter!.isPublic) { + assert(getter!.documentationFrom.length == 1); + var fromGetter = getter!.documentationFrom.first; // We have to check against dropTextFrom here since documentationFrom // doesn't yield the real elements for GetterSetterCombos. - if (!config!.dropTextFrom.contains(fromGetter.element!.library!.name)) { + if (!config.dropTextFrom.contains(fromGetter.element!.library!.name)) { if (fromGetter.hasDocumentationComment) { buffer.write(fromGetter.documentationComment); } } } - if (hasSetter && !setter!.isSynthetic && setter!.isPublic!) { - assert(setter!.documentationFrom!.length == 1); - var fromSetter = setter!.documentationFrom!.first; - if (!config!.dropTextFrom.contains(fromSetter.element!.library!.name)) { + if (hasSetter && !setter!.isSynthetic && setter!.isPublic) { + assert(setter!.documentationFrom.length == 1); + var fromSetter = setter!.documentationFrom.first; + if (!config.dropTextFrom.contains(fromSetter.element!.library!.name)) { if (fromSetter.hasDocumentationComment) { if (buffer.isNotEmpty) buffer.write('\n\n'); buffer.write(fromSetter.documentationComment); @@ -212,7 +212,7 @@ mixin GetterSetterCombo on ModelElement { ElementType get modelType { if (hasGetter) return getter!.modelType.returnType; - return setter!.parameters!.first.modelType; + return setter!.parameters.first.modelType; } @override @@ -267,7 +267,7 @@ mixin GetterSetterCombo on ModelElement { if (_referenceChildren == null) { _referenceChildren = {}; if (hasParameters) { - _referenceChildren!.addEntries(parameters!.explicitOnCollisionWith(this)); + _referenceChildren!.addEntries(parameters.explicitOnCollisionWith(this)); } _referenceChildren! .addEntries(modelType.typeArguments.explicitOnCollisionWith(this)); diff --git a/lib/src/model/inheritable.dart b/lib/src/model/inheritable.dart index 63ede70450..a86ec10b42 100644 --- a/lib/src/model/inheritable.dart +++ b/lib/src/model/inheritable.dart @@ -97,7 +97,7 @@ mixin Inheritable on ContainerMember { // This is still OK because we're never supposed to cloak public // classes. if (definingEnclosingContainer!.isCanonical && - definingEnclosingContainer!.isPublic!) { + definingEnclosingContainer!.isPublic) { assert(definingEnclosingContainer == found); } if (found != null) { @@ -164,7 +164,7 @@ mixin Inheritable on ContainerMember { enclosingCanonical == definingCanonical && // If the overridden element isn't public, we shouldn't be an // override in most cases. Approximation until #1623 is fixed. - overriddenCanonical!.isPublic!; + overriddenCanonical!.isPublic; assert(!(_isOverride! && isInherited)); } return _isOverride; diff --git a/lib/src/model/inheriting_container.dart b/lib/src/model/inheriting_container.dart index 48a11b3412..d40327d910 100644 --- a/lib/src/model/inheriting_container.dart +++ b/lib/src/model/inheriting_container.dart @@ -24,7 +24,7 @@ mixin Constructable on InheritingContainer { List? _constructors; Iterable get constructors => _constructors ??= [ ...element!.constructors - .map((e) => modelBuilder.from(e, library!) as Constructor) + .map((e) => modelBuilder.from(e, library) as Constructor) ]; @override @@ -99,7 +99,7 @@ mixin MixedInTypes on InheritingContainer { _mixedInTypes ?? [ ...element!.mixins - .map((f) => modelBuilder.typeFrom(f, library!) as DefinedElementType) + .map((f) => modelBuilder.typeFrom(f, library) as DefinedElementType) .where((mixin) => mixin != null) ]; @@ -120,7 +120,7 @@ mixin TypeImplementing on InheritingContainer { _directInterfaces ?? [ ...element!.interfaces - .map((f) => modelBuilder.typeFrom(f, library!) as DefinedElementType) + .map((f) => modelBuilder.typeFrom(f, library) as DefinedElementType) .toList(growable: false) ]; @@ -227,9 +227,9 @@ abstract class InheritingContainer extends Container DefinedElementType? _supertype; DefinedElementType? get supertype => - _supertype ??= element!.supertype?.element?.supertype == null + _supertype ??= element!.supertype?.element.supertype == null ? null - : modelBuilder.typeFrom(element!.supertype!, library!) as DefinedElementType?; + : modelBuilder.typeFrom(element!.supertype!, library) as DefinedElementType?; InheritingContainer( ClassElement element, Library? library, PackageGraph packageGraph) @@ -245,7 +245,7 @@ abstract class InheritingContainer extends Container @override Iterable get instanceOperators => - quiver.concat([super.instanceOperators!, inheritedOperators!]); + quiver.concat([super.instanceOperators, inheritedOperators!]); @override bool get publicInheritedInstanceOperators => @@ -258,7 +258,7 @@ abstract class InheritingContainer extends Container _allModelElements ??= List.from( quiver.concat([ super.allModelElements!, - typeParameters!, + typeParameters, ]), growable: false); return _allModelElements; @@ -273,7 +273,7 @@ abstract class InheritingContainer extends Container ModelElement? get enclosingElement => library; @override - String get filePath => '${library!.dirName}/$fileName'; + String get filePath => '${library.dirName}/$fileName'; String get fullkind => kind; @@ -301,7 +301,7 @@ abstract class InheritingContainer extends Container }).toSet(); for (var e in inheritedMethodElements) { - Method m = modelBuilder.from(e!, library!, enclosingContainer: this) as Method; + Method m = modelBuilder.from(e!, library, enclosingContainer: this) as Method; _inheritedMethods!.add(m); } } @@ -319,7 +319,7 @@ abstract class InheritingContainer extends Container Iterable? get inheritedOperators { if (_inheritedOperators == null) { _inheritedOperators = []; - var operatorNames = declaredOperators!.map((o) => o.element!.name).toSet(); + var operatorNames = declaredOperators.map((o) => o.element!.name).toSet(); var inheritedOperatorElements = _inheritedElements!.where((e) { return (e is MethodElement && @@ -327,7 +327,7 @@ abstract class InheritingContainer extends Container !operatorNames.contains(e.name)); }).toSet(); for (var e in inheritedOperatorElements) { - Operator o = modelBuilder.from(e!, library!, enclosingContainer: this) as Operator; + Operator o = modelBuilder.from(e!, library, enclosingContainer: this) as Operator; _inheritedOperators!.add(o); } } @@ -342,7 +342,7 @@ abstract class InheritingContainer extends Container model_utils.filterNonPublic(inheritedFields); @override - bool get isCanonical => super.isCanonical && isPublic!; + bool get isCanonical => super.isCanonical && isPublic; /// Returns true if [other] is a parent class for this class. bool _isInheritingFrom(InheritingContainer? other) => superChain @@ -353,7 +353,7 @@ abstract class InheritingContainer extends Container @override DefinedElementType get modelType => - (_modelType ??= modelBuilder.typeFrom(element!.thisType, library!) as DefinedElementType?)!; + (_modelType ??= modelBuilder.typeFrom(element!.thisType, library) as DefinedElementType?)!; /// Not the same as superChain as it may include mixins. /// It's really not even the same as ordinary Dart inheritance, either, @@ -370,11 +370,11 @@ abstract class InheritingContainer extends Container if (parent.type is InterfaceType) { // Avoid adding [Object] to the superChain (_supertype already has this // check) - if ((parent.type as InterfaceType)?.superclass?.superclass == null) { + if ((parent.type as InterfaceType).superclass?.superclass == null) { parent = null; } else { parent = modelBuilder.typeFrom( - (parent.type as InterfaceType).superclass!, library!) as DefinedElementType?; + (parent.type as InterfaceType).superclass!, library) as DefinedElementType?; } } else { parent = (parent.modelElement as Class).supertype; @@ -523,10 +523,10 @@ abstract class InheritingContainer extends Container ContainerAccessor accessor; if (element == null) return null; if (inheritedAccessors.contains(element)) { - accessor = modelBuilder.from(element, enclosingContainer.library!, + accessor = modelBuilder.from(element, enclosingContainer.library, enclosingContainer: enclosingContainer) as ContainerAccessor; } else { - accessor = modelBuilder.from(element, enclosingContainer.library!) as ContainerAccessor; + accessor = modelBuilder.from(element, enclosingContainer.library) as ContainerAccessor; } return accessor; } @@ -564,14 +564,14 @@ abstract class InheritingContainer extends Container if ((getter == null || getter.isInherited) && (setter == null || setter.isInherited)) { // Field is 100% inherited. - field = modelBuilder.fromPropertyInducingElement(f!, library!, + field = modelBuilder.fromPropertyInducingElement(f!, library, enclosingContainer: this, getter: getter!, setter: setter!) as Field; } else { // Field is <100% inherited (could be half-inherited). // TODO(jcollins-g): Navigation is probably still confusing for // half-inherited fields when traversing the inheritance tree. Make // this better, somehow. - field = modelBuilder.fromPropertyInducingElement(f!, library!, + field = modelBuilder.fromPropertyInducingElement(f!, library, getter: getter!, setter: setter!) as Field; } _allFields!.add(field); @@ -582,7 +582,7 @@ abstract class InheritingContainer extends Container @override Iterable get declaredMethods => _declaredMethods ??= element!.methods.map((e) { - return modelBuilder.from(e, library!) as Method; + return modelBuilder.from(e, library) as Method; }); List? _typeParameters; diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index 06947b3fa8..78cab8b23e 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -117,21 +117,21 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// Allow scope for Libraries. @override - Scope get scope => element!.scope; + Scope get scope => element.scope; List? __allOriginalModelElementNames; /// Return true if this library is in a package configured to be treated as /// as using Null safety and itself uses Null safety. - bool get _allowsNullSafety => element!.isNonNullableByDefault; + bool get _allowsNullSafety => element.isNonNullableByDefault; /// Return true if this library should be documented as using Null safety. /// A library may use Null safety but not documented that way. @override bool get isNullSafety => - config!.enableExperiment.contains('non-nullable') && _allowsNullSafety; + config.enableExperiment.contains('non-nullable') && _allowsNullSafety; - bool get isInSdk => element!.isInSdk; + bool get isInSdk => element.isInSdk; /// [allModelElements] resolved to their original names. /// @@ -163,7 +163,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override CharacterLocation? get characterLocation { - if (element!.nameOffset == -1) { + if (element.nameOffset == -1) { assert(isAnonymous, 'Only anonymous libraries are allowed to have no declared location'); return CharacterLocation(1, 1); @@ -173,41 +173,36 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override CompilationUnitElement get compilationUnitElement => - element!.definingCompilationUnit; + element.definingCompilationUnit; @override - Iterable get classes => allClasses!.where((c) => !c.isErrorOrException); + Iterable get classes => allClasses.where((c) => !c.isErrorOrException); @override LibraryElement get element => super.element as LibraryElement; - late final List _extensions; - @override - Iterable get extensions { - _extensions ??= _exportedAndLocalElements + late final Iterable extensions = _exportedAndLocalElements .whereType() .map((e) => modelBuilder.from(e, this) as Extension) .toList(growable: false); - return _extensions; - } SdkLibrary? get sdkLib { - if (packageGraph.sdkLibrarySources!.containsKey(element!.librarySource)) { - return packageGraph.sdkLibrarySources![element!.librarySource]; + if (packageGraph.sdkLibrarySources!.containsKey(element.librarySource)) { + return packageGraph.sdkLibrarySources![element.librarySource]; } return null; } @override bool get isPublic { - if (!super.isPublic!) return false; + if (!super.isPublic) return false; if (sdkLib != null && (sdkLib!.isInternal || !isSdkLibraryDocumented(sdkLib!))) { return false; } - if (config!.isLibraryExcluded(name) || - config!.isLibraryExcluded(element!.librarySource.uri.toString())) { + if (config.isLibraryExcluded(name) || + config.isLibraryExcluded(element.librarySource.uri.toString())) { return false; } return true; @@ -251,8 +246,8 @@ class Library extends ModelElement with Categorization, TopLevelContainer { if (_importedExportedLibraries == null) { _importedExportedLibraries = {}; var importedExportedLibraryElements = {}; - importedExportedLibraryElements.addAll(element!.importedLibraries); - importedExportedLibraryElements.addAll(element!.exportedLibraries); + importedExportedLibraryElements.addAll(element.importedLibraries); + importedExportedLibraryElements.addAll(element.exportedLibraries); for (var l in importedExportedLibraryElements) { var lib = modelBuilder.fromElement(l) as Library; _importedExportedLibraries.add(lib); @@ -269,7 +264,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { if (_prefixToLibrary == null) { _prefixToLibrary = {}; // It is possible to have overlapping prefixes. - for (var i in element!.imports) { + for (var i in element.imports) { var prefixName = i.prefix?.name; // Ignore invalid imports. if (prefixName != null && i.importedLibrary != null) { @@ -367,7 +362,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override List get exceptions { _exceptions ??= - allClasses!.where((c) => c.isErrorOrException).toList(growable: false); + allClasses.where((c) => c.isErrorOrException).toList(growable: false); return _exceptions; } @@ -399,7 +394,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _inheritanceManager; } - bool get isAnonymous => element!.name == null || element!.name.isEmpty; + bool get isAnonymous => element.name == null || element.name.isEmpty; @override String get kind => 'library'; @@ -412,18 +407,18 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override String get name { if (_name == null) { - var source = element!.source; + var source = element.source; if (source.uri.isScheme('dart')) { // There are inconsistencies in library naming + URIs for the dart // internal libraries; rationalize them here. if (source.uri.toString().contains('/')) { - _name = element!.name.replaceFirst('dart.', 'dart:'); + _name = element.name.replaceFirst('dart.', 'dart:'); } else { _name = source.uri.toString(); } - } else if (element!.name != null && element!.name.isNotEmpty) { - _name = element!.name; + } else if (element.name != null && element.name.isNotEmpty) { + _name = element.name; } else { _name = pathContext.basename(source.fullName); if (_name.endsWith('.dart')) { @@ -445,7 +440,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// 'lib') are the same, but this will include slashes and possibly colons /// for anonymous libraries in subdirectories or other packages. String get nameFromPath { - _nameFromPath ??= _getNameFromPath(element!, package, _restoredUri); + _nameFromPath ??= _getNameFromPath(element, package, _restoredUri); return _nameFromPath; } @@ -457,8 +452,8 @@ class Library extends ModelElement with Categorization, TopLevelContainer { PackageMeta? get packageMeta { _packageMeta ??= packageGraph.packageMetaProvider.fromElement( - element!, - config!.sdkDir, + element, + config.sdkDir, ); return _packageMeta; } @@ -484,7 +479,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _typedefs; } - TypeSystem get typeSystem => element!.typeSystem; + TypeSystem get typeSystem => element.typeSystem; late final List allClasses = _exportedAndLocalElements @@ -494,7 +489,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { .toList(growable: false); Class? getClassByName(String name) { - return allClasses!.firstWhereOrNull((it) => it.name == name); + return allClasses.firstWhereOrNull((it) => it.name == name); } late final List _variables; @@ -560,7 +555,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { if (_modelElementsMap == null) { var results = quiver.concat(>[ library.constants, - library.functions!, + library.functions, library.properties, library.typedefs, library.extensions.expand((e) { @@ -569,7 +564,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { e.allModelElements! ]); }), - library.allClasses!.expand((c) { + library.allClasses.expand((c) { return quiver.concat([ [c], c.allModelElements! @@ -594,7 +589,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { .putIfAbsent(modelElement.element!, () => {}) .add(modelElement); } - _modelElementsMap.putIfAbsent(element!, () => {}).add(this); + _modelElementsMap.putIfAbsent(element, () => {}).add(this); } return _modelElementsMap; } @@ -619,8 +614,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; - var definedNamesModelElements = element! - .exportNamespace.definedNames.values + var definedNamesModelElements = element.exportNamespace.definedNames.values .map((v) => modelBuilder.fromElement(v)); _referenceChildren!.addEntries( definedNamesModelElements.whereNotType().generateEntries()); diff --git a/lib/src/model/locatable.dart b/lib/src/model/locatable.dart index f7aea47f38..c00866ec25 100644 --- a/lib/src/model/locatable.dart +++ b/lib/src/model/locatable.dart @@ -12,7 +12,7 @@ abstract class Locatable { /// True if documentationFrom contains only one item, [this]. bool get documentationIsLocal => - documentationFrom!.length == 1 && identical(documentationFrom!.first, this); + documentationFrom.length == 1 && identical(documentationFrom.first, this); String get fullyQualifiedName; diff --git a/lib/src/model/method.dart b/lib/src/model/method.dart index fe07e795bd..1f1d247a96 100644 --- a/lib/src/model/method.dart +++ b/lib/src/model/method.dart @@ -125,7 +125,7 @@ class Method extends ModelElement Map? _referenceChildren; @override Map get referenceChildren { - var from = documentationFrom!.first as Method; + var from = documentationFrom.first as Method; if (!identical(this, from)) { return from.referenceChildren; } diff --git a/lib/src/model/mixin.dart b/lib/src/model/mixin.dart index 6ec530bcdd..23b93c61aa 100644 --- a/lib/src/model/mixin.dart +++ b/lib/src/model/mixin.dart @@ -23,7 +23,7 @@ class Mixin extends InheritingContainer with TypeImplementing { _superclassConstraints ??= [ ...element!.superclassConstraints .map( - (InterfaceType i) => modelBuilder.typeFrom(i, library!) as ParameterizedElementType) + (InterfaceType i) => modelBuilder.typeFrom(i, library) as ParameterizedElementType) .where((t) => t.modelElement != packageGraph.specialClasses[SpecialClass.object]) diff --git a/lib/src/model/model_element.dart b/lib/src/model/model_element.dart index 39dbb4aba3..68ff8e19c9 100644 --- a/lib/src/model/model_element.dart +++ b/lib/src/model/model_element.dart @@ -414,11 +414,11 @@ abstract class ModelElement extends Canonicalization return false; } if (enclosingElement is Class && - !(enclosingElement as Class).isPublic!) { + !(enclosingElement as Class).isPublic) { return false; } if (enclosingElement is Extension && - !(enclosingElement as Extension).isPublic!) { + !(enclosingElement as Extension).isPublic) { return false; } return utils.hasPublicName(element!) && !hasNodoc!; @@ -451,7 +451,7 @@ abstract class ModelElement extends Canonicalization @override late final DartdocOptionContext config = DartdocOptionContext.fromContextElement( - packageGraph.config, library!.element!, packageGraph.resourceProvider); + packageGraph.config, library!.element, packageGraph.resourceProvider); Set? _locationPieces; @@ -542,13 +542,13 @@ abstract class ModelElement extends Canonicalization // just shortcut them out. if (!utils.hasPublicName(element!)) { _canonicalLibrary = null; - } else if (!packageGraph.localPublicLibraries!.contains(definingLibrary)) { + } else if (!packageGraph.localPublicLibraries.contains(definingLibrary)) { _canonicalLibrary = _searchForCanonicalLibrary(); } else { _canonicalLibrary = definingLibrary; } // Only pretend when not linking to remote packages. - if (this is Inheritable && !config!.linkToRemote) { + if (this is Inheritable && !config.linkToRemote) { if ((this as Inheritable).isInherited && _canonicalLibrary == null && packageGraph.publicLibraries!.contains(library)) { @@ -590,7 +590,7 @@ abstract class ModelElement extends Canonicalization l.isPublic && l.package.documentedWhere != DocumentLocation.missing) .where((l) { var lookup = - l.element!.exportNamespace.definedNames[topLevelElement?.name!]; + l.element.exportNamespace.definedNames[topLevelElement?.name!]; if (lookup is PropertyAccessorElement) { lookup = lookup.variable; } @@ -630,7 +630,7 @@ abstract class ModelElement extends Canonicalization var highestScore = scoredCandidates.last.score; var confidence = highestScore - secondHighestScore; - if (confidence < config!.ambiguousReexportScorerMinConfidence) { + if (confidence < config.ambiguousReexportScorerMinConfidence) { var libraryNames = candidateLibraries.map((l) => l.name); var message = '$libraryNames -> ${candidateLibraries.last.name} ' '(confidence ${confidence.toStringAsPrecision(4)})'; @@ -643,7 +643,7 @@ abstract class ModelElement extends Canonicalization @override bool get isCanonical { - if (!isPublic!) return false; + if (!isPublic) return false; if (library != canonicalLibrary) return false; // If there's no inheritance to deal with, we're done. if (this is! Inheritable) return true; @@ -658,7 +658,7 @@ abstract class ModelElement extends Canonicalization @override String get documentation { return injectMacros( - documentationFrom!.map((e) => e.documentationLocal).join('

')); + documentationFrom.map((e) => e.documentationLocal).join('

')); } @override @@ -743,7 +743,7 @@ abstract class ModelElement extends Canonicalization bool get hasExtendedDocumentation => href != null && elementDocumentation.hasExtendedDocs!; - bool get hasParameters => parameters!.isNotEmpty; + bool get hasParameters => parameters.isNotEmpty; /// If canonicalLibrary (or canonicalEnclosingElement, for Inheritable /// subclasses) is null, href should be null. @@ -793,7 +793,7 @@ abstract class ModelElement extends Canonicalization } @override - bool get isDocumented => isCanonical && isPublic!; + bool get isDocumented => isCanonical && isPublic; bool get isExecutable => element is ExecutableElement; @@ -841,16 +841,16 @@ abstract class ModelElement extends Canonicalization SourceCodeRenderer get _sourceCodeRenderer => packageGraph.rendererFactory.sourceCodeRenderer; - String get linkedParams => _parameterRenderer.renderLinkedParams(parameters!); + String get linkedParams => _parameterRenderer.renderLinkedParams(parameters); String get linkedParamsLines => - _parameterRendererDetailed.renderLinkedParams(parameters!).trim(); + _parameterRendererDetailed.renderLinkedParams(parameters).trim(); String? get linkedParamsNoMetadata => - _parameterRenderer.renderLinkedParams(parameters!, showMetadata: false); + _parameterRenderer.renderLinkedParams(parameters, showMetadata: false); String get linkedParamsNoMetadataOrNames => _parameterRenderer - .renderLinkedParams(parameters!, showMetadata: false, showNames: false); + .renderLinkedParams(parameters, showMetadata: false, showNames: false); @override String get name => element!.name!; @@ -869,7 +869,7 @@ abstract class ModelElement extends Canonicalization // FIXME(nnbd): package should not have to be nullable just because of dynamic Package? get package => library?.package; - bool get isPublicAndPackageDocumented => isPublic! && package?.isDocumented == true; + bool get isPublicAndPackageDocumented => isPublic&& package?.isDocumented == true; List? _allParameters; @@ -881,9 +881,9 @@ abstract class ModelElement extends Canonicalization var newParameters = {}; if (this is GetterSetterCombo && (this as GetterSetterCombo).setter != null) { - newParameters.addAll((this as GetterSetterCombo).setter!.parameters!); + newParameters.addAll((this as GetterSetterCombo).setter!.parameters); } else { - if (isCallable) newParameters.addAll(parameters!); + if (isCallable) newParameters.addAll(parameters); } // TODO(jcollins-g): This part probably belongs in [ElementType]. while (newParameters.isNotEmpty) { @@ -960,7 +960,7 @@ abstract class ModelElement extends Canonicalization @override int compareTo(dynamic other) { if (other is ModelElement) { - return name!.toLowerCase().compareTo(other.name!.toLowerCase()); + return name.toLowerCase().compareTo(other.name.toLowerCase()); } else { return 0; } @@ -974,7 +974,7 @@ abstract class ModelElement extends Canonicalization fqName ??= e.name; if (e is! EnclosedElement || e.enclosingElement == null) { - return fqName!; + return fqName; } return _buildFullyQualifiedName( @@ -984,7 +984,7 @@ abstract class ModelElement extends Canonicalization String _calculateLinkedName() { // If we're calling this with an empty name, we probably have the wrong // element associated with a ModelElement or there's an analysis bug. - assert(name!.isNotEmpty || + assert(name.isNotEmpty || element?.kind == ElementKind.DYNAMIC || element?.kind == ElementKind.NEVER || this is ModelFunction); @@ -993,7 +993,7 @@ abstract class ModelElement extends Canonicalization if (isPublicAndPackageDocumented) { warn(PackageWarning.noCanonicalFound); } - return htmlEscape.convert(name!); + return htmlEscape.convert(name); } return modelElementRenderer.renderLinkedName(this); diff --git a/lib/src/model/model_function.dart b/lib/src/model/model_function.dart index 9c2da97775..873624fa46 100644 --- a/lib/src/model/model_function.dart +++ b/lib/src/model/model_function.dart @@ -79,7 +79,7 @@ class ModelFunctionTyped extends ModelElement _referenceChildren! .addEntriesIfAbsent(typeParameters.explicitOnCollisionWith(this)); _referenceChildren! - .addEntriesIfAbsent(parameters!.explicitOnCollisionWith(this)); + .addEntriesIfAbsent(parameters.explicitOnCollisionWith(this)); } return _referenceChildren!; } diff --git a/lib/src/model/nameable.dart b/lib/src/model/nameable.dart index e513b35a16..4c04a5e1ba 100644 --- a/lib/src/model/nameable.dart +++ b/lib/src/model/nameable.dart @@ -18,7 +18,7 @@ abstract class Nameable { Set? _namePieces; Set? get namePieces { _namePieces ??= { - ...name!.split(locationSplitter).where((s) => s.isNotEmpty) + ...name.split(locationSplitter).where((s) => s.isNotEmpty) }; return _namePieces; } @@ -29,16 +29,16 @@ abstract class Nameable { String? get namePart { // TODO(jcollins-g): This should really be the same as 'name', but isn't // because of accessors and operators. - _namePart ??= fullyQualifiedName!.split('.').last; + _namePart ??= fullyQualifiedName.split('.').last; return _namePart; } @override - String toString() => name!; + String toString() => name; } int byName(Nameable a, Nameable b) { - var stringCompare = compareAsciiLowerCaseNatural(a.name!, b.name!); + var stringCompare = compareAsciiLowerCaseNatural(a.name, b.name); if (stringCompare == 0) { return a.hashCode.compareTo(b.hashCode); } diff --git a/lib/src/model/operator.dart b/lib/src/model/operator.dart index 8555050bd5..369222362f 100644 --- a/lib/src/model/operator.dart +++ b/lib/src/model/operator.dart @@ -23,7 +23,7 @@ class Operator extends Method { String get fileName { var actualName = super.name; if (operatorNames.containsKey(actualName)) { - actualName = 'operator_${operatorNames[actualName!]}'; + actualName = 'operator_${operatorNames[actualName]}'; } return '$actualName.$fileType'; } @@ -44,5 +44,5 @@ class Operator extends Method { } @override - String get referenceName => super.name!; + String get referenceName => super.name; } diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index 2041817f5f..f433f3e5a7 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -106,7 +106,7 @@ class Package extends LibraryContainer /// Return true if the code has defined non-default categories for libraries /// in this package. - bool get hasCategories => categories!.isNotEmpty; + bool get hasCategories => categories.isNotEmpty; LibraryContainer? get defaultCategory => nameToCategory[null]; @@ -175,7 +175,7 @@ class Package extends LibraryContainer packageMeta.isSdk && libraries.any((l) => _pathContext.isWithin( packageGraph.packageMeta.dir.path, - (l.element!.source.fullName))) || + (l.element.source.fullName))) || // autoIncludeDependencies means everything is local. packageGraph.config.autoIncludeDependencies) && // Regardless of the above rules, do not document as local if @@ -189,13 +189,13 @@ class Package extends LibraryContainer DocumentLocation get documentedWhere { if (_documentedWhere == null) { if (isLocal!) { - if (isPublic!) { + if (isPublic) { _documentedWhere = DocumentLocation.local; } } else { - if (config!.linkToRemote && - config!.linkToUrl.isNotEmpty && - isPublic! && + if (config.linkToRemote && + config.linkToUrl.isNotEmpty && + isPublic&& !packageGraph.config.isPackageExcluded(name)) { _documentedWhere = DocumentLocation.remote; } else { @@ -221,7 +221,7 @@ class Package extends LibraryContainer // from pub.dev, and we know that all of those use html docs. return _fileType ??= (package.documentedWhere == DocumentLocation.remote) ? 'html' - : config!.format; + : config.format; } @override @@ -238,14 +238,14 @@ class Package extends LibraryContainer _baseHref = _remoteBaseHref; if (!_baseHref!.endsWith('/')) _baseHref = '$_baseHref/'; } else { - _baseHref = config!.useBaseHref ? '' : htmlBasePlaceholder; + _baseHref = config.useBaseHref ? '' : htmlBasePlaceholder; } return _baseHref; } String get _remoteBaseHref { - return config!.linkToUrl.replaceAllMapped(_substituteNameVersion, (m) { + return config.linkToUrl.replaceAllMapped(_substituteNameVersion, (m) { switch (m.group(1)) { // Return the prerelease tag of the release if a prerelease, or 'stable' // otherwise. Mostly coded around the Dart SDK's use of dev/stable, but @@ -308,11 +308,11 @@ class Package extends LibraryContainer if (_nameToCategory.isEmpty) { Category? categoryFor(String? category) { _nameToCategory.putIfAbsent( - category, () => Category(category!, this, config!)); + category, () => Category(category!, this, config)); return _nameToCategory[category]; } - _nameToCategory[null] = Category(null, this, config!); + _nameToCategory[null] = Category(null, this, config); for (var c in libraries.expand( (l) => l.allCanonicalModelElements.whereType())) { if (c.hasCategoryNames) { @@ -333,15 +333,15 @@ class Package extends LibraryContainer } (); Iterable get categoriesWithPublicLibraries => - categories!.where((c) => c.publicLibraries.isNotEmpty); + categories.where((c) => c.publicLibraries.isNotEmpty); Iterable get documentedCategories => - categories!.where((c) => c.isDocumented); + categories.where((c) => c.isDocumented); Iterable get documentedCategoriesSorted { // Category display order is configurable; leave the category order // as defined if the order is specified. - if (config!.categoryOrder.isEmpty) { + if (config.categoryOrder.isEmpty) { return documentedCategories; } return documentedCategories.toList()..sort(byName); @@ -381,7 +381,7 @@ class Package extends LibraryContainer Element? get element => null; @override - List get containerOrder => config!.packageOrder; + List get containerOrder => config.packageOrder; Map? _referenceChildren; @override diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index acf782c44f..1ea164f2f8 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -101,7 +101,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // are picked up. for (var package in documentedPackages) { for (var library in package.libraries) { - _addToImplementors(library.allClasses!); + _addToImplementors(library.allClasses); _addToImplementors(library.mixins); _extensions.addAll(library.extensions); } @@ -123,17 +123,17 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { Iterable> precacheOneElement(ModelElement m) sync* { for (var d - in m.documentationFrom!.where((d) => d.hasDocumentationComment)) { + in m.documentationFrom.where((d) => d.hasDocumentationComment)) { if (d.needsPrecache && !precachedElements.contains(d)) { precachedElements.add(d as ModelElement); yield d.precacheLocalDocs(); - logProgress(d.name!); + logProgress(d.name); // TopLevelVariables get their documentation from getters and setters, // so should be precached if either has a template. if (m is TopLevelVariable && !precachedElements.contains(m)) { precachedElements.add(m); yield m.precacheLocalDocs(); - logProgress(d.name!); + logProgress(d.name); } } } @@ -320,7 +320,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // If we don't have an element, we need a message to disambiguate. assert(message != null); } - if (packageWarningCounter!.hasWarning(warnable, kind, message)) { + if (packageWarningCounter.hasWarning(warnable, kind, message)) { return; } // Some kinds of warnings it is OK to drop if we're not documenting them. @@ -470,7 +470,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { } var fullMessage = messageParts.join('\n '); - packageWarningCounter!.addWarning(warnable, kind, message, fullMessage); + packageWarningCounter.addWarning(warnable, kind, message, fullMessage); } String _safeWarnableName(Locatable? locatable) { @@ -497,7 +497,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { "$packageName, packages: ${packages.map((p) => p.name).join(',')}"); } } - _publicPackages = packages.where((p) => p.isPublic!).toList()..sort(); + _publicPackages = packages.where((p) => p.isPublic).toList()..sort(); } return _publicPackages; } @@ -598,7 +598,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { void checkAndAddContainer( InheritingContainer implemented, InheritingContainer implementor) { - if (!implemented.isPublic!) { + if (!implemented.isPublic) { privates.add(implemented); } implemented = implemented.canonicalModelElement as InheritingContainer? ?? implemented; @@ -804,7 +804,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { var combos = matches.whereType().map((a) => a.enclosingCombo).toList(); matches.addAll(combos); - assert(combos.every((c) => c!.isCanonical)); + assert(combos.every((c) => c.isCanonical)); } // This is for situations where multiple classes may actually be canonical diff --git a/lib/src/model/prefix.dart b/lib/src/model/prefix.dart index f90a59e38e..8045d22217 100644 --- a/lib/src/model/prefix.dart +++ b/lib/src/model/prefix.dart @@ -27,7 +27,7 @@ class Prefix extends ModelElement implements EnclosedElement { // TODO(jcollins-g): consider connecting PrefixElement to the imported library // in analyzer? Library get associatedLibrary => - (_associatedLibrary ??= modelBuilder.fromElement(library!.element!.imports + (_associatedLibrary ??= modelBuilder.fromElement(library!.element.imports .firstWhere((i) => i.prefix == element) .importedLibrary!) as Library?)!; diff --git a/lib/src/model/source_code_mixin.dart b/lib/src/model/source_code_mixin.dart index a0904e097f..9694d4282f 100644 --- a/lib/src/model/source_code_mixin.dart +++ b/lib/src/model/source_code_mixin.dart @@ -15,7 +15,7 @@ abstract class SourceCodeMixin implements Documentable { Element? get element; - bool get hasSourceCode => config!.includeSource && sourceCode!.isNotEmpty; + bool get hasSourceCode => config.includeSource && sourceCode!.isNotEmpty; Library? get library; diff --git a/lib/src/model/top_level_variable.dart b/lib/src/model/top_level_variable.dart index d86b6cb514..e5ca5725ce 100644 --- a/lib/src/model/top_level_variable.dart +++ b/lib/src/model/top_level_variable.dart @@ -47,7 +47,7 @@ class TopLevelVariable extends ModelElement ModelElement? get enclosingElement => library; @override - String get filePath => '${library!.dirName}/$fileName'; + String get filePath => '${library.dirName}/$fileName'; @override String? get href { diff --git a/lib/src/model/type_parameter.dart b/lib/src/model/type_parameter.dart index f33405e145..52409a8107 100644 --- a/lib/src/model/type_parameter.dart +++ b/lib/src/model/type_parameter.dart @@ -20,7 +20,7 @@ class TypeParameter extends ModelElement { @override String get filePath => - '${enclosingElement!.library!.dirName}/${enclosingElement!.name}/$name'; + '${enclosingElement.library!.dirName}/${enclosingElement.name}/$name'; @override @@ -81,7 +81,7 @@ mixin TypeParameters implements ModelElement { String get nameWithLinkedGenerics => '$name$linkedGenericParameters'; - bool get hasGenericParameters => typeParameters!.isNotEmpty; + bool get hasGenericParameters => typeParameters.isNotEmpty; String get genericParameters => _typeParametersRenderer.renderGenericParameters(this); diff --git a/lib/src/model/typedef.dart b/lib/src/model/typedef.dart index f1f87990b3..37a9745feb 100644 --- a/lib/src/model/typedef.dart +++ b/lib/src/model/typedef.dart @@ -24,7 +24,7 @@ abstract class Typedef extends ModelElement ElementType? _modelType; ElementType get modelType => - _modelType ??= modelBuilder.typeFrom(element!.aliasedType, library!); + _modelType ??= modelBuilder.typeFrom(element!.aliasedType, library); @override Library? get enclosingElement => library; @@ -40,7 +40,7 @@ abstract class Typedef extends ModelElement _renderer.renderLinkedGenericParameters(this); @override - String get filePath => '${library!.dirName}/$fileName'; + String get filePath => '${library.dirName}/$fileName'; /// Helper for mustache templates, which can't do casting themselves /// without this. @@ -70,7 +70,7 @@ abstract class Typedef extends ModelElement @override List get typeParameters => element!.typeParameters.map((f) { - return modelBuilder.from(f, library!) as TypeParameter; + return modelBuilder.from(f, library) as TypeParameter; }).toList(); TypedefRenderer get _renderer => packageGraph.rendererFactory.typedefRenderer; @@ -140,7 +140,7 @@ class FunctionTypedef extends Typedef { if (_referenceChildren == null) { _referenceChildren = super.referenceChildren; _referenceChildren! - .addEntriesIfAbsent(parameters!.explicitOnCollisionWith(this)); + .addEntriesIfAbsent(parameters.explicitOnCollisionWith(this)); } return _referenceChildren!; } From 3f064c35066d328455191b6754d92280501f9f89 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Fri, 15 Oct 2021 10:36:06 -0700 Subject: [PATCH 10/21] All warnings done so really ship it --- lib/src/model/library.dart | 68 +++++-------------------- lib/src/model/model_element.dart | 8 +-- lib/src/model/model_function.dart | 2 +- lib/src/model/model_node.dart | 2 +- lib/src/model/model_object_builder.dart | 1 - lib/src/model/package.dart | 2 +- lib/src/model/package_builder.dart | 9 +--- lib/src/model/package_graph.dart | 2 +- 8 files changed, 23 insertions(+), 71 deletions(-) diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index 78cab8b23e..df3a821fbc 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -208,14 +208,9 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return true; } - late final List _constants; - @override - Iterable get constants { - _constants ??= + late final Iterable constants = _getVariables().where((v) => v.isConst).toList(growable: false); - return _constants; - } late final Set _packageImportedExportedLibraries; @@ -290,14 +285,14 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _dirName; } - late final Set _canonicalFor; + late final Set? _canonicalFor; Set get canonicalFor { if (_canonicalFor == null) { // TODO(jcollins-g): restructure to avoid using side effects. buildDocumentationAddition(documentationComment); } - return _canonicalFor; + return _canonicalFor!; } static final _canonicalRegExp = RegExp(r'{@canonicalFor\s([^}]+)}'); @@ -333,38 +328,23 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override ModelElement? get enclosingElement => null; - late final List _enums; - @override - List get enums { - _enums ??= _exportedAndLocalElements + late final List enums = _exportedAndLocalElements .whereType() .where((element) => element.isEnum) .map((e) => modelBuilder.from(e, this) as Enum) .toList(growable: false); - return _enums; - } - - late final List _mixins; @override - List get mixins { - _mixins ??= _exportedAndLocalElements + late final List mixins = + _exportedAndLocalElements .whereType() .where((ClassElement c) => c.isMixin) .map((e) => modelBuilder.from(e, this) as Mixin) .toList(growable: false); - return _mixins; - } - - late final List _exceptions; @override - List get exceptions { - _exceptions ??= - allClasses.where((c) => c.isErrorOrException).toList(growable: false); - return _exceptions; - } + late final List exceptions = allClasses.where((c) => c.isErrorOrException).toList(growable: false); @override String get fileName => '$dirName-library.$fileType'; @@ -430,7 +410,6 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _name; } - late final String _nameFromPath; /// Generate a name for this library based on its location. /// @@ -439,10 +418,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// the name calculation. Simple cases (such as an anonymous library in /// 'lib') are the same, but this will include slashes and possibly colons /// for anonymous libraries in subdirectories or other packages. - String get nameFromPath { - _nameFromPath ??= _getNameFromPath(element, package, _restoredUri); - return _nameFromPath; - } + late final String nameFromPath = _getNameFromPath(element, package, _restoredUri); /// The name of the package we were defined in. String get packageName => packageMeta?.name ?? ''; @@ -458,26 +434,15 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _packageMeta; } - late final List _properties; - /// All variables ("properties") except constants. @override - Iterable get properties { - _properties ??= - _getVariables().where((v) => !v.isConst).toList(growable: false); - return _properties; - } - - late final List _typedefs; + late final Iterable properties = _getVariables().where((v) => !v.isConst).toList(growable: false); @override - List get typedefs { - _typedefs ??= _exportedAndLocalElements + late final List typedefs = _exportedAndLocalElements .whereType() .map((e) => modelBuilder.from(e, this) as Typedef) .toList(growable: false); - return _typedefs; - } TypeSystem get typeSystem => element.typeSystem; @@ -594,20 +559,13 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _modelElementsMap; } - late final List _allModelElements; - - Iterable get allModelElements { - return _allModelElements ??= [ + late final Iterable allModelElements = [ for (var modelElements in modelElementsMap.values) ...modelElements, ]; - } - late final List _allCanonicalModelElements; - Iterable get allCanonicalModelElements { - return (_allCanonicalModelElements ??= - allModelElements.where((e) => e.isCanonical).toList()); - } + late final Iterable allCanonicalModelElements = + allModelElements.where((e) => e.isCanonical).toList(); Map? _referenceChildren; @override diff --git a/lib/src/model/model_element.dart b/lib/src/model/model_element.dart index 68ff8e19c9..1071759f0f 100644 --- a/lib/src/model/model_element.dart +++ b/lib/src/model/model_element.dart @@ -725,7 +725,7 @@ abstract class ModelElement extends Canonicalization assert(lineInfo != null, 'No lineInfo data available for element: $fullyQualifiedName'); if (element!.nameOffset >= 0) { - _characterLocation = lineInfo?.getLocation(element!.nameOffset); + _characterLocation = lineInfo.getLocation(element!.nameOffset); } } return _characterLocation; @@ -737,7 +737,7 @@ abstract class ModelElement extends Canonicalization bool get hasAnnotations => annotations.isNotEmpty; @override - bool get hasDocumentation => documentation?.isNotEmpty == true; + bool get hasDocumentation => documentation.isNotEmpty == true; @override bool get hasExtendedDocumentation => @@ -776,8 +776,8 @@ abstract class ModelElement extends Canonicalization // The getter or the setter might be null – so the stored value may be // `true`, `false`, or `null` - var getterDeprecated = pie.getter?.metadata?.any((a) => a.isDeprecated); - var setterDeprecated = pie.setter?.metadata?.any((a) => a.isDeprecated); + var getterDeprecated = pie.getter?.metadata.any((a) => a.isDeprecated); + var setterDeprecated = pie.setter?.metadata.any((a) => a.isDeprecated); var deprecatedValues = [getterDeprecated, setterDeprecated].where((a) => a != null).toList(); diff --git a/lib/src/model/model_function.dart b/lib/src/model/model_function.dart index 873624fa46..843085625c 100644 --- a/lib/src/model/model_function.dart +++ b/lib/src/model/model_function.dart @@ -19,7 +19,7 @@ class ModelFunction extends ModelFunctionTyped with Categorization { bool get isStatic => element!.isStatic; @override - String get name => element!.name ?? ''; + String get name => element!.name; @override FunctionElement? get element => super.element as FunctionElement?; diff --git a/lib/src/model/model_node.dart b/lib/src/model/model_node.dart index 3c0cbb86c7..b0ca512251 100644 --- a/lib/src/model/model_node.dart +++ b/lib/src/model/model_node.dart @@ -26,7 +26,7 @@ class ModelNode { static List _commentRefsFor( AstNode? node, ResourceProvider resourceProvider) { if (node is AnnotatedNode && - node?.documentationComment?.references != null) { + node.documentationComment?.references != null) { return [ for (var m in node.documentationComment!.references) ModelCommentReference(m, resourceProvider), diff --git a/lib/src/model/model_object_builder.dart b/lib/src/model/model_object_builder.dart index c57cf521fc..c9dafd9d4e 100644 --- a/lib/src/model/model_object_builder.dart +++ b/lib/src/model/model_object_builder.dart @@ -10,7 +10,6 @@ import 'package:dartdoc/src/model/container.dart'; import 'package:dartdoc/src/model/library.dart'; import 'package:dartdoc/src/model/model_element.dart'; import 'package:dartdoc/src/model/package_graph.dart'; -import 'package:meta/meta.dart'; abstract class ModelObjectBuilder implements ModelElementBuilder, ElementTypeBuilder {} diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index f433f3e5a7..c371a69533 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -371,7 +371,7 @@ class Package extends LibraryContainer return _packagePath; } - String get version => packageMeta.version ?? '0.0.0-unknown'; + String get version => packageMeta.version; final PackageMeta _packageMeta; diff --git a/lib/src/model/package_builder.dart b/lib/src/model/package_builder.dart index 75754f43fa..dcdee13980 100644 --- a/lib/src/model/package_builder.dart +++ b/lib/src/model/package_builder.dart @@ -34,7 +34,6 @@ import 'package:dartdoc/src/package_meta.dart' import 'package:dartdoc/src/quiver.dart' as quiver; import 'package:dartdoc/src/render/renderer_factory.dart'; import 'package:dartdoc/src/special_elements.dart'; -import 'package:meta/meta.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as path show Context; @@ -83,15 +82,11 @@ class PubPackageBuilder implements PackageBuilder { return newGraph; } - late final DartSdk _sdk; - DartSdk get sdk { - _sdk ??= packageMetaProvider.defaultSdk ?? + late final DartSdk sdk = packageMetaProvider.defaultSdk ?? FolderBasedDartSdk( resourceProvider, resourceProvider.getFolder(config.sdkDir)); - return _sdk; - } EmbedderSdk? _embedderSdk; @@ -383,7 +378,7 @@ class PubPackageBuilder implements PackageBuilder { Iterable get _embedderSdkUris { if (config.topLevelPackageMeta.isSdk) return []; - return embedderSdk?.urlMappings?.keys ?? []; + return embedderSdk?.urlMappings.keys ?? []; } Future getLibraries(PackageGraph uninitializedPackageGraph) async { diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index 1ea164f2f8..2ba67c9ad1 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -874,7 +874,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// set of canonical Libraries). Library? findButDoNotCreateLibraryFor(Element e) { // This is just a cache to avoid creating lots of libraries over and over. - return allLibraries[e.library?.source?.fullName]; + return allLibraries[e.library?.source.fullName]; } /// This is used when we might need a Library object that isn't actually From 3e6812b68b2524e3e3891bf1f464834cf5bd94bd Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Fri, 15 Oct 2021 10:36:39 -0700 Subject: [PATCH 11/21] dartfmt --- lib/dartdoc.dart | 1 - lib/src/element_type.dart | 3 +- lib/src/model/accessor.dart | 31 ++++----- lib/src/model/annotation.dart | 4 +- lib/src/model/canonicalization.dart | 2 - lib/src/model/categorization.dart | 8 +-- lib/src/model/class.dart | 2 - lib/src/model/comment_referable.dart | 1 + lib/src/model/constructor.dart | 24 +++---- lib/src/model/container.dart | 6 +- lib/src/model/container_member.dart | 15 +++-- lib/src/model/documentable.dart | 2 - lib/src/model/documentation.dart | 8 +-- lib/src/model/documentation_comment.dart | 13 ++-- lib/src/model/dynamic.dart | 2 - lib/src/model/enclosed_element.dart | 2 - lib/src/model/enum.dart | 8 +-- lib/src/model/extendable.dart | 2 - lib/src/model/extension.dart | 2 - lib/src/model/extension_target.dart | 2 - lib/src/model/feature.dart | 2 - lib/src/model/feature_set.dart | 2 - lib/src/model/field.dart | 11 +-- lib/src/model/getter_setter_combo.dart | 14 ++-- lib/src/model/indexable.dart | 2 - lib/src/model/inheritable.dart | 20 +++--- lib/src/model/inheriting_container.dart | 55 ++++++++------- lib/src/model/library.dart | 78 +++++++++++----------- lib/src/model/library_container.dart | 2 - lib/src/model/locatable.dart | 2 - lib/src/model/method.dart | 12 ++-- lib/src/model/mixin.dart | 6 +- lib/src/model/model.dart | 2 - lib/src/model/model_element.dart | 85 ++++++++++++------------ lib/src/model/model_function.dart | 9 ++- lib/src/model/model_node.dart | 2 - lib/src/model/nameable.dart | 2 - lib/src/model/never.dart | 2 - lib/src/model/operator.dart | 5 +- lib/src/model/package.dart | 12 ++-- lib/src/model/package_builder.dart | 11 ++- lib/src/model/package_graph.dart | 41 +++++++----- lib/src/model/parameter.dart | 8 +-- lib/src/model/prefix.dart | 2 - lib/src/model/privacy.dart | 2 - lib/src/model/source_code_mixin.dart | 2 - lib/src/model/top_level_container.dart | 2 - lib/src/model/top_level_variable.dart | 5 +- lib/src/model/type_parameter.dart | 11 ++- lib/src/model/typedef.dart | 2 - 50 files changed, 252 insertions(+), 297 deletions(-) diff --git a/lib/dartdoc.dart b/lib/dartdoc.dart index 351827f0eb..00564432aa 100644 --- a/lib/dartdoc.dart +++ b/lib/dartdoc.dart @@ -2,7 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - /// A documentation generator for Dart. /// /// Library interface is still experimental. diff --git a/lib/src/element_type.dart b/lib/src/element_type.dart index d2a7815de8..fc2fe3bf56 100644 --- a/lib/src/element_type.dart +++ b/lib/src/element_type.dart @@ -260,7 +260,8 @@ class AliasedElementType extends ParameterizedElementType with Aliased { ParameterizedType get type; /// Parameters, if available, for the underlying typedef. - late final List aliasedParameters = modelElement.isCallable ? modelElement.parameters : []; + late final List aliasedParameters = + modelElement.isCallable ? modelElement.parameters : []; @override ElementTypeRenderer get _renderer => diff --git a/lib/src/model/accessor.dart b/lib/src/model/accessor.dart index 6a13baa87b..ebf78c242b 100644 --- a/lib/src/model/accessor.dart +++ b/lib/src/model/accessor.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/source/line_info.dart'; // ignore: implementation_imports @@ -38,14 +36,16 @@ class Accessor extends ModelElement implements EnclosedElement { } @override - PropertyAccessorElement? get element => super.element as PropertyAccessorElement?; + PropertyAccessorElement? get element => + super.element as PropertyAccessorElement?; @override - ExecutableMember? get originalMember => super.originalMember as ExecutableMember?; + ExecutableMember? get originalMember => + super.originalMember as ExecutableMember?; Callable? _modelType; - Callable get modelType => (_modelType ??= - modelBuilder.typeFrom((originalMember ?? element)!.type, library!) as Callable?)!; + Callable get modelType => (_modelType ??= modelBuilder.typeFrom( + (originalMember ?? element)!.type, library!) as Callable?)!; bool get isSynthetic => element!.isSynthetic; @@ -94,11 +94,11 @@ class Accessor extends ModelElement implements EnclosedElement { /// Build a documentation comment for this accessor assuming it is synthetic. /// Value here is not useful if [isSynthetic] is false. late final String _syntheticDocumentationComment = () { - if (_hasSyntheticDocumentationComment) { - return definingCombo!.documentationComment; - } - return ''; - } (); + if (_hasSyntheticDocumentationComment) { + return definingCombo!.documentationComment; + } + return ''; + }(); /// If this is a getter, assume we want synthetic documentation. /// If the definingCombo has a nodoc tag, we want synthetic documentation @@ -242,8 +242,9 @@ class ContainerAccessor extends Accessor with ContainerMember, Inheritable { var parent = element!.enclosingElement; if (parent is ClassElement) { for (var t in parent.allSupertypes) { - Element? accessor = - isGetter ? t.getGetter(element!.name) : t.getSetter(element!.name); + Element? accessor = isGetter + ? t.getGetter(element!.name) + : t.getSetter(element!.name); if (accessor != null) { accessor = accessor.declaration; InheritingContainer parentContainer = @@ -252,8 +253,8 @@ class ContainerAccessor extends Accessor with ContainerMember, Inheritable { possibleFields.addAll(parentContainer.instanceFields); possibleFields.addAll(parentContainer.staticFields); var fieldName = accessor!.name!.replaceFirst('=', ''); - var foundField = possibleFields.firstWhereOrNull( - (f) => f.element!.name == fieldName); + var foundField = possibleFields + .firstWhereOrNull((f) => f.element!.name == fieldName); if (foundField != null) { if (isGetter) { _overriddenElement = foundField.getter; diff --git a/lib/src/model/annotation.dart b/lib/src/model/annotation.dart index 233efcb903..8a4a203a8d 100644 --- a/lib/src/model/annotation.dart +++ b/lib/src/model/annotation.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/feature.dart'; @@ -70,7 +68,7 @@ class Annotation extends Feature with ModelBuilder { @override bool get isPublic => - modelType!.isPublic&& + modelType!.isPublic && modelType is DefinedElementType && !packageGraph.invisibleAnnotations .contains((modelType as DefinedElementType).modelElement); diff --git a/lib/src/model/canonicalization.dart b/lib/src/model/canonicalization.dart index 93b32c38f0..7099eab5dc 100644 --- a/lib/src/model/canonicalization.dart +++ b/lib/src/model/canonicalization.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/comment_references/model_comment_reference.dart'; import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/categorization.dart b/lib/src/model/categorization.dart index 11c1d6c032..9cd157b5c4 100644 --- a/lib/src/model/categorization.dart +++ b/lib/src/model/categorization.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/model/model.dart'; final RegExp _categoryRegExp = RegExp( @@ -96,7 +94,6 @@ abstract class Categorization implements ModelElement { return _samples; } - Iterable? _categories; Iterable? get categories { @@ -115,10 +112,11 @@ abstract class Categorization implements ModelElement { } bool? _hasCategorization; + /// True if categories, subcategories, a documentation icon, or samples were /// declared. - late final bool hasCategorization = () { + late final bool hasCategorization = () { if (_hasCategorization == null) documentationLocal; return _hasCategorization!; - } (); + }(); } diff --git a/lib/src/model/class.dart b/lib/src/model/class.dart index 93d0bcd845..c17143769d 100644 --- a/lib/src/model/class.dart +++ b/lib/src/model/class.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/comment_referable.dart b/lib/src/model/comment_referable.dart index cbcf0d5ad1..7c3f022b04 100644 --- a/lib/src/model/comment_referable.dart +++ b/lib/src/model/comment_referable.dart @@ -226,6 +226,7 @@ mixin CommentReferable implements Nameable, ModelBuilderInterface { Library? get library => null; @internal + /// For testing / comparison only, get the comment referable from where this /// [ElementType] was defined. Override where an [Element] is available. CommentReferable get definingCommentReferable => this; diff --git a/lib/src/model/constructor.dart b/lib/src/model/constructor.dart index 53d3505078..4b5f39b1e5 100644 --- a/lib/src/model/constructor.dart +++ b/lib/src/model/constructor.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/source/line_info.dart'; import 'package:dartdoc/src/element_type.dart'; @@ -70,8 +68,8 @@ class Constructor extends ModelElement String get kind => 'constructor'; Callable? _modelType; - Callable get modelType => - (_modelType ??= modelBuilder.typeFrom(element!.type, library!) as Callable?)!; + Callable get modelType => (_modelType ??= + modelBuilder.typeFrom(element!.type, library!) as Callable?)!; @override late final String name = () { @@ -83,18 +81,16 @@ class Constructor extends ModelElement return enclosingElement.name; } return '${enclosingElement.name}.$constructorName'; - } (); - + }(); @override late final String nameWithGenerics = () { - var constructorName = element!.name; - if (constructorName.isEmpty) { - return '${enclosingElement.name}$genericParameters'; - } - return - '${enclosingElement.name}$genericParameters.$constructorName'; - } (); + var constructorName = element!.name; + if (constructorName.isEmpty) { + return '${enclosingElement.name}$genericParameters'; + } + return '${enclosingElement.name}$genericParameters.$constructorName'; + }(); String? get shortName { if (name.contains('.')) { @@ -123,5 +119,5 @@ class Constructor extends ModelElement @override String get referenceName => - isUnnamedConstructor ? enclosingElement.name: element!.name; + isUnnamedConstructor ? enclosingElement.name : element!.name; } diff --git a/lib/src/model/container.dart b/lib/src/model/container.dart index 5181486adb..dfeed70aa5 100644 --- a/lib/src/model/container.dart +++ b/lib/src/model/container.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/scope.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; @@ -119,8 +117,8 @@ abstract class Container extends ModelElement ..sort(byName); @nonVirtual - late final Iterable declaredOperators = - declaredMethods!.whereType().toList(growable: false); + late final Iterable declaredOperators = + declaredMethods!.whereType().toList(growable: false); @override ModelElement? get enclosingElement; diff --git a/lib/src/model/container_member.dart b/lib/src/model/container_member.dart index 4cf3b00f38..4d8daaa594 100644 --- a/lib/src/model/container_member.dart +++ b/lib/src/model/container_member.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/model/feature.dart'; import 'package:dartdoc/src/model/model.dart'; import 'package:meta/meta.dart'; @@ -50,12 +48,12 @@ mixin ContainerMember on ModelElement implements EnclosedElement { Container? computeCanonicalEnclosingContainer() { // TODO(jcollins-g): move Extension specific code to [Extendable] if (enclosingElement is Extension && enclosingElement!.isDocumented) { - return packageGraph - .findCanonicalModelElementFor(enclosingElement!.element) as Container?; + return packageGraph.findCanonicalModelElementFor( + enclosingElement!.element) as Container?; } if (enclosingElement is! Extension) { - return packageGraph - .findCanonicalModelElementFor(element!.enclosingElement) as Container?; + return packageGraph.findCanonicalModelElementFor( + element!.enclosingElement) as Container?; } return null; } @@ -68,7 +66,10 @@ mixin ContainerMember on ModelElement implements EnclosedElement { // references are resolved wrt documentation inheritance, // that has to be resolved in the source by not inheriting // documentation. - [enclosingElement as Container, documentationFrom.first.enclosingElement as Container]; + [ + enclosingElement as Container, + documentationFrom.first.enclosingElement as Container + ]; @override Iterable get referenceGrandparentOverrides sync* { diff --git a/lib/src/model/documentable.dart b/lib/src/model/documentable.dart index 7fec6286f3..b3b0aa5211 100644 --- a/lib/src/model/documentable.dart +++ b/lib/src/model/documentable.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/file_system/file_system.dart'; import 'package:dartdoc/src/dartdoc_options.dart'; import 'package:dartdoc/src/io_utils.dart'; diff --git a/lib/src/model/documentation.dart b/lib/src/model/documentation.dart index f34df083d6..6ef93c8550 100644 --- a/lib/src/model/documentation.dart +++ b/lib/src/model/documentation.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/comment_references/model_comment_reference.dart'; import 'package:dartdoc/src/markdown_processor.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -71,8 +69,10 @@ class Documentation { if (text == null || text.isEmpty) { return DocumentationParseResult.empty; } - showWarningsForGenericsOutsideSquareBracketsBlocks(text, _element as Warnable); - var document = MarkdownDocument.withElementLinkResolver(_element as Warnable); + showWarningsForGenericsOutsideSquareBracketsBlocks( + text, _element as Warnable); + var document = + MarkdownDocument.withElementLinkResolver(_element as Warnable); return document.parseMarkdownText(text, processFullDocs); } diff --git a/lib/src/model/documentation_comment.dart b/lib/src/model/documentation_comment.dart index 6c75ddeaad..8f6f59b4c7 100644 --- a/lib/src/model/documentation_comment.dart +++ b/lib/src/model/documentation_comment.dart @@ -1,5 +1,3 @@ - - import 'package:analyzer/file_system/file_system.dart'; import 'package:args/args.dart'; import 'package:crypto/crypto.dart' as crypto; @@ -274,7 +272,9 @@ mixin DocumentationComment return await config.tools.runner.run(args, content: basicMatch[2]!, toolErrorCallback: (String message) async { warn(PackageWarning.toolError, message: message); - }, environment: _toolsEnvironment(invocationIndex: invocationIndex) as Map); + }, + environment: _toolsEnvironment(invocationIndex: invocationIndex) + as Map); }); } @@ -336,7 +336,8 @@ mixin DocumentationComment replacement = replacement.replaceFirst('```', '```$lang'); } } else { - var filePath = element!.source!.fullName.substring(dirPath?.length ?? -1 + 1); + var filePath = + element!.source!.fullName.substring(dirPath?.length ?? -1 + 1); // TODO(srawlins): If a file exists at the location without the // appended 'md' extension, note this. @@ -767,8 +768,8 @@ mixin DocumentationComment } bool? _needsPrecache; - bool get needsPrecache => _needsPrecache ??= - _needsPrecacheRegExp.hasMatch(documentationComment); + bool get needsPrecache => + _needsPrecache ??= _needsPrecacheRegExp.hasMatch(documentationComment); String? _rawDocs; diff --git a/lib/src/model/dynamic.dart b/lib/src/model/dynamic.dart index 34fa1fc7b8..9d4b4cee45 100644 --- a/lib/src/model/dynamic.dart +++ b/lib/src/model/dynamic.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; diff --git a/lib/src/model/enclosed_element.dart b/lib/src/model/enclosed_element.dart index 42184290d7..579f1ffdae 100644 --- a/lib/src/model/enclosed_element.dart +++ b/lib/src/model/enclosed_element.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/model/model.dart'; /// An element that is enclosed by some other element. diff --git a/lib/src/model/enum.dart b/lib/src/model/enum.dart index f21203dc52..f6b739ee20 100644 --- a/lib/src/model/enum.dart +++ b/lib/src/model/enum.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - // TODO(jcollins-g): Consider Enum as subclass of Container? import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -46,11 +44,13 @@ class EnumField extends Field { EnumField(FieldElement element, Library library, PackageGraph packageGraph, Accessor? getter, Accessor? setter) - : super(element, library, packageGraph, getter as ContainerAccessor?, setter as ContainerAccessor?); + : super(element, library, packageGraph, getter as ContainerAccessor?, + setter as ContainerAccessor?); EnumField.forConstant(this.index, FieldElement element, Library library, PackageGraph packageGraph, Accessor? getter) - : super(element, library, packageGraph, getter as ContainerAccessor?, null); + : super( + element, library, packageGraph, getter as ContainerAccessor?, null); @override String get constantValueBase => _fieldRenderer.renderValue(this); diff --git a/lib/src/model/extendable.dart b/lib/src/model/extendable.dart index e296fd1c47..bb496c6b4f 100644 --- a/lib/src/model/extendable.dart +++ b/lib/src/model/extendable.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/model/model.dart'; /// Mixin for subclasses of [ModelElement] representing Elements that can be diff --git a/lib/src/model/extension.dart b/lib/src/model/extension.dart index e643b263f4..909459967f 100644 --- a/lib/src/model/extension.dart +++ b/lib/src/model/extension.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; diff --git a/lib/src/model/extension_target.dart b/lib/src/model/extension_target.dart index db0a065d1f..27e7893024 100644 --- a/lib/src/model/extension_target.dart +++ b/lib/src/model/extension_target.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/feature.dart b/lib/src/model/feature.dart index befff3805b..5529ce0cc8 100644 --- a/lib/src/model/feature.dart +++ b/lib/src/model/feature.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:collection/collection.dart'; import 'package:dartdoc/src/model/privacy.dart'; diff --git a/lib/src/model/feature_set.dart b/lib/src/model/feature_set.dart index a6365c6f55..cbfd50b5d3 100644 --- a/lib/src/model/feature_set.dart +++ b/lib/src/model/feature_set.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/model/language_feature.dart'; import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/field.dart b/lib/src/model/field.dart index f239ef3d29..e9ee5d164d 100644 --- a/lib/src/model/field.dart +++ b/lib/src/model/field.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/feature.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -34,7 +32,8 @@ class Field extends ModelElement PackageGraph packageGraph, Accessor? getter, Accessor? setter) { - var newField = Field(element, library, packageGraph, getter as ContainerAccessor?, setter as ContainerAccessor?); + var newField = Field(element, library, packageGraph, + getter as ContainerAccessor?, setter as ContainerAccessor?); newField._isInherited = true; newField._enclosingContainer = enclosingContainer; // Can't set _isInherited to true if this is the defining element, because @@ -57,7 +56,8 @@ class Field extends ModelElement } @override - Container get enclosingElement => modelBuilder.from(field!.enclosingElement, library) as Container; + Container get enclosingElement => + modelBuilder.from(field!.enclosingElement, library) as Container; @override String get filePath => @@ -65,7 +65,8 @@ class Field extends ModelElement @override String? get href { - assert(!identical(canonicalModelElement, this) || canonicalEnclosingContainer == enclosingElement); + assert(!identical(canonicalModelElement, this) || + canonicalEnclosingContainer == enclosingElement); return super.href; } diff --git a/lib/src/model/getter_setter_combo.dart b/lib/src/model/getter_setter_combo.dart index 8a7845f44f..f7a38f3ad2 100644 --- a/lib/src/model/getter_setter_combo.dart +++ b/lib/src/model/getter_setter_combo.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'dart:convert'; import 'package:analyzer/dart/ast/ast.dart' @@ -113,7 +111,6 @@ mixin GetterSetterCombo on ModelElement { @override bool get isPublic => hasPublicGetter || hasPublicSetter; - @override late final List documentationFrom = () { var toReturn = []; @@ -127,7 +124,7 @@ mixin GetterSetterCombo on ModelElement { toReturn = super.documentationFrom; } return toReturn; - } (); + }(); bool get hasAccessorsWithDocs => (hasPublicGetter && !getter!.isSynthetic && getter!.hasDocumentation || @@ -190,7 +187,8 @@ mixin GetterSetterCombo on ModelElement { var fromGetter = getter!.documentationFrom.first; // We have to check against dropTextFrom here since documentationFrom // doesn't yield the real elements for GetterSetterCombos. - if (!config.dropTextFrom.contains(fromGetter.element!.library!.name)) { + if (!config.dropTextFrom + .contains(fromGetter.element!.library!.name)) { if (fromGetter.hasDocumentationComment) { buffer.write(fromGetter.documentationComment); } @@ -200,7 +198,8 @@ mixin GetterSetterCombo on ModelElement { if (hasSetter && !setter!.isSynthetic && setter!.isPublic) { assert(setter!.documentationFrom.length == 1); var fromSetter = setter!.documentationFrom.first; - if (!config.dropTextFrom.contains(fromSetter.element!.library!.name)) { + if (!config.dropTextFrom + .contains(fromSetter.element!.library!.name)) { if (fromSetter.hasDocumentationComment) { if (buffer.isNotEmpty) buffer.write('\n\n'); buffer.write(fromSetter.documentationComment); @@ -267,7 +266,8 @@ mixin GetterSetterCombo on ModelElement { if (_referenceChildren == null) { _referenceChildren = {}; if (hasParameters) { - _referenceChildren!.addEntries(parameters.explicitOnCollisionWith(this)); + _referenceChildren! + .addEntries(parameters.explicitOnCollisionWith(this)); } _referenceChildren! .addEntries(modelType.typeArguments.explicitOnCollisionWith(this)); diff --git a/lib/src/model/indexable.dart b/lib/src/model/indexable.dart index 6c46312c83..c96e77cb8c 100644 --- a/lib/src/model/indexable.dart +++ b/lib/src/model/indexable.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/model/model.dart'; /// Something able to be indexed. diff --git a/lib/src/model/inheritable.dart b/lib/src/model/inheritable.dart index a86ec10b42..37f0c777a8 100644 --- a/lib/src/model/inheritable.dart +++ b/lib/src/model/inheritable.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:collection/collection.dart' show IterableExtension; import 'package:dartdoc/src/model/feature.dart'; import 'package:dartdoc/src/model/model.dart'; @@ -40,7 +38,8 @@ mixin Inheritable on ContainerMember { }; @override - Library? get canonicalLibrary => canonicalEnclosingContainer?.canonicalLibrary; + Library? get canonicalLibrary => + canonicalEnclosingContainer?.canonicalLibrary; @override ModelElement? buildCanonicalModelElement() { @@ -49,8 +48,9 @@ mixin Inheritable on ContainerMember { return this; } if (canonicalEnclosingContainer is Container) { - return canonicalEnclosingContainer!.allCanonicalModelElements.firstWhereOrNull( - (m) => m.name == name && m.isPropertyAccessor == isPropertyAccessor); + return canonicalEnclosingContainer!.allCanonicalModelElements + .firstWhereOrNull((m) => + m.name == name && m.isPropertyAccessor == isPropertyAccessor); } if (canonicalEnclosingContainer != null) { throw UnimplementedError('$canonicalEnclosingContainer: unknown type'); @@ -78,8 +78,8 @@ mixin Inheritable on ContainerMember { .memberByExample(this) .canonicalEnclosingContainer; } - Container? canonicalC = - packageGraph.findCanonicalModelElementFor(c.element) as Container?; + Container? canonicalC = packageGraph + .findCanonicalModelElementFor(c.element) as Container?; // TODO(jcollins-g): invert this lookup so traversal is recursive // starting from the ModelElement. if (canonicalC != null) { @@ -105,8 +105,8 @@ mixin Inheritable on ContainerMember { } } else if (!isInherited && definingEnclosingContainer is! Extension) { // TODO(jcollins-g): factor out extension logic into [Extendable]. - return packageGraph - .findCanonicalModelElementFor(element!.enclosingElement) as Container?; + return packageGraph.findCanonicalModelElementFor( + element!.enclosingElement) as Container?; } return super.computeCanonicalEnclosingContainer(); } @@ -179,5 +179,5 @@ mixin Inheritable on ContainerMember { e = e.overriddenElement!; } return depth; - } (); + }(); } diff --git a/lib/src/model/inheriting_container.dart b/lib/src/model/inheriting_container.dart index d40327d910..1cc36b4c0b 100644 --- a/lib/src/model/inheriting_container.dart +++ b/lib/src/model/inheriting_container.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:collection/collection.dart' show IterableExtension; @@ -42,8 +40,8 @@ mixin Constructable on InheritingContainer { Constructor? _unnamedConstructor; Constructor? get unnamedConstructor { - _unnamedConstructor ??= constructors - .firstWhereOrNull((c) => c.isUnnamedConstructor); + _unnamedConstructor ??= + constructors.firstWhereOrNull((c) => c.isUnnamedConstructor); return _unnamedConstructor; } @@ -99,7 +97,8 @@ mixin MixedInTypes on InheritingContainer { _mixedInTypes ?? [ ...element!.mixins - .map((f) => modelBuilder.typeFrom(f, library) as DefinedElementType) + .map( + (f) => modelBuilder.typeFrom(f, library) as DefinedElementType) .where((mixin) => mixin != null) ]; @@ -120,7 +119,8 @@ mixin TypeImplementing on InheritingContainer { _directInterfaces ?? [ ...element!.interfaces - .map((f) => modelBuilder.typeFrom(f, library) as DefinedElementType) + .map( + (f) => modelBuilder.typeFrom(f, library) as DefinedElementType) .toList(growable: false) ]; @@ -229,7 +229,8 @@ abstract class InheritingContainer extends Container DefinedElementType? get supertype => _supertype ??= element!.supertype?.element.supertype == null ? null - : modelBuilder.typeFrom(element!.supertype!, library) as DefinedElementType?; + : modelBuilder.typeFrom(element!.supertype!, library) + as DefinedElementType?; InheritingContainer( ClassElement element, Library? library, PackageGraph packageGraph) @@ -301,7 +302,8 @@ abstract class InheritingContainer extends Container }).toSet(); for (var e in inheritedMethodElements) { - Method m = modelBuilder.from(e!, library, enclosingContainer: this) as Method; + Method m = + modelBuilder.from(e!, library, enclosingContainer: this) as Method; _inheritedMethods!.add(m); } } @@ -327,7 +329,8 @@ abstract class InheritingContainer extends Container !operatorNames.contains(e.name)); }).toSet(); for (var e in inheritedOperatorElements) { - Operator o = modelBuilder.from(e!, library, enclosingContainer: this) as Operator; + Operator o = modelBuilder.from(e!, library, enclosingContainer: this) + as Operator; _inheritedOperators!.add(o); } } @@ -353,7 +356,8 @@ abstract class InheritingContainer extends Container @override DefinedElementType get modelType => - (_modelType ??= modelBuilder.typeFrom(element!.thisType, library) as DefinedElementType?)!; + (_modelType ??= modelBuilder.typeFrom(element!.thisType, library) + as DefinedElementType?)!; /// Not the same as superChain as it may include mixins. /// It's really not even the same as ordinary Dart inheritance, either, @@ -374,7 +378,8 @@ abstract class InheritingContainer extends Container parent = null; } else { parent = modelBuilder.typeFrom( - (parent.type as InterfaceType).superclass!, library) as DefinedElementType?; + (parent.type as InterfaceType).superclass!, library) + as DefinedElementType?; } } else { parent = (parent.modelElement as Class).supertype; @@ -428,15 +433,16 @@ abstract class InheritingContainer extends Container e.name == 'Object' && e.library.name == 'dart.core'; assert(inheritanceChainElements .contains(imap[nameObj]!.enclosingElement) || - _isDartCoreObject(imap[nameObj]!.enclosingElement as ClassElement)); + _isDartCoreObject( + imap[nameObj]!.enclosingElement as ClassElement)); // If the concrete object from [InheritanceManager3.getInheritedConcreteMap2] // is farther from this class in the inheritance chain than the one // provided by InheritedMap2, prefer InheritedMap2. This // correctly accounts for intermediate abstract classes that have // method/field implementations. - if (inheritanceChainElements - .indexOf(combinedMap[nameObj.name]!.enclosingElement as ClassElement?) < + if (inheritanceChainElements.indexOf(combinedMap[nameObj.name]! + .enclosingElement as ClassElement?) < inheritanceChainElements .indexOf(imap[nameObj]!.enclosingElement as ClassElement?)) { combinedMap[nameObj.name] = imap[nameObj]; @@ -473,13 +479,13 @@ abstract class InheritingContainer extends Container for (var f in element!.fields) { var getterElement = f.getter; if (getterElement == null && accessorMap.containsKey(f.name)) { - getterElement = accessorMap[f.name]! - .firstWhereOrNull((e) => e.isGetter); + getterElement = + accessorMap[f.name]!.firstWhereOrNull((e) => e.isGetter); } var setterElement = f.setter; if (setterElement == null && accessorMap.containsKey(f.name)) { - setterElement = accessorMap[f.name]! - .firstWhereOrNull((e) => e.isSetter); + setterElement = + accessorMap[f.name]!.firstWhereOrNull((e) => e.isSetter); } _addSingleField( getterElement, setterElement, inheritedAccessorElements, f); @@ -490,10 +496,8 @@ abstract class InheritingContainer extends Container // anything in cls._fields. for (var fieldName in accessorMap.keys) { var elements = accessorMap[fieldName]!.toList(); - var getterElement = - elements.firstWhereOrNull((e) => e.isGetter); - var setterElement = - elements.firstWhereOrNull((e) => e.isSetter); + var getterElement = elements.firstWhereOrNull((e) => e.isGetter); + var setterElement = elements.firstWhereOrNull((e) => e.isSetter); _addSingleField( getterElement, setterElement, inheritedAccessorElements); } @@ -526,7 +530,8 @@ abstract class InheritingContainer extends Container accessor = modelBuilder.from(element, enclosingContainer.library, enclosingContainer: enclosingContainer) as ContainerAccessor; } else { - accessor = modelBuilder.from(element, enclosingContainer.library) as ContainerAccessor; + accessor = modelBuilder.from(element, enclosingContainer.library) + as ContainerAccessor; } return accessor; } @@ -552,8 +557,8 @@ abstract class InheritingContainer extends Container // for this single Field we're trying to compose. Pick the one closest // to this class on the inheritance chain. if (setter!.enclosingElement is Class && - (setter.enclosingElement as Class) - ._isInheritingFrom(getter!.enclosingElement as InheritingContainer?)) { + (setter.enclosingElement as Class)._isInheritingFrom( + getter!.enclosingElement as InheritingContainer?)) { f = setterElement!.variable as FieldElement?; } else { f = getterElement!.variable as FieldElement?; diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index df3a821fbc..d73d86eee0 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart' show CompilationUnit; @@ -151,8 +149,8 @@ class Library extends ModelElement with Categorization, TopLevelContainer { setter = modelBuilder.fromElement(e.setter!.element!) as Accessor; } return modelBuilder - .fromPropertyInducingElement( - e.element!, modelBuilder.fromElement(e.element!.library!) as Library, + .fromPropertyInducingElement(e.element!, + modelBuilder.fromElement(e.element!.library!) as Library, getter: getter, setter: setter) .fullyQualifiedName; } @@ -183,9 +181,9 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override late final Iterable extensions = _exportedAndLocalElements - .whereType() - .map((e) => modelBuilder.from(e, this) as Extension) - .toList(growable: false); + .whereType() + .map((e) => modelBuilder.from(e, this) as Extension) + .toList(growable: false); SdkLibrary? get sdkLib { if (packageGraph.sdkLibrarySources!.containsKey(element.librarySource)) { @@ -210,7 +208,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override late final Iterable constants = - _getVariables().where((v) => v.isConst).toList(growable: false); + _getVariables().where((v) => v.isConst).toList(growable: false); late final Set _packageImportedExportedLibraries; @@ -329,22 +327,22 @@ class Library extends ModelElement with Categorization, TopLevelContainer { ModelElement? get enclosingElement => null; @override - late final List enums = _exportedAndLocalElements - .whereType() - .where((element) => element.isEnum) - .map((e) => modelBuilder.from(e, this) as Enum) - .toList(growable: false); + late final List enums = _exportedAndLocalElements + .whereType() + .where((element) => element.isEnum) + .map((e) => modelBuilder.from(e, this) as Enum) + .toList(growable: false); @override - late final List mixins = - _exportedAndLocalElements - .whereType() - .where((ClassElement c) => c.isMixin) - .map((e) => modelBuilder.from(e, this) as Mixin) - .toList(growable: false); + late final List mixins = _exportedAndLocalElements + .whereType() + .where((ClassElement c) => c.isMixin) + .map((e) => modelBuilder.from(e, this) as Mixin) + .toList(growable: false); @override - late final List exceptions = allClasses.where((c) => c.isErrorOrException).toList(growable: false); + late final List exceptions = + allClasses.where((c) => c.isErrorOrException).toList(growable: false); @override String get fileName => '$dirName-library.$fileType'; @@ -354,9 +352,9 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override late final List functions = - _exportedAndLocalElements.whereType().map((e) { - return modelBuilder.from(e, this) as ModelFunction; - }).toList(growable: false); + _exportedAndLocalElements.whereType().map((e) { + return modelBuilder.from(e, this) as ModelFunction; + }).toList(growable: false); @override String? get href { @@ -410,7 +408,6 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _name; } - /// Generate a name for this library based on its location. /// /// nameFromPath provides filename collision-proofing for anonymous libraries @@ -418,7 +415,8 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// the name calculation. Simple cases (such as an anonymous library in /// 'lib') are the same, but this will include slashes and possibly colons /// for anonymous libraries in subdirectories or other packages. - late final String nameFromPath = _getNameFromPath(element, package, _restoredUri); + late final String nameFromPath = + _getNameFromPath(element, package, _restoredUri); /// The name of the package we were defined in. String get packageName => packageMeta?.name ?? ''; @@ -436,22 +434,22 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// All variables ("properties") except constants. @override - late final Iterable properties = _getVariables().where((v) => !v.isConst).toList(growable: false); + late final Iterable properties = + _getVariables().where((v) => !v.isConst).toList(growable: false); @override late final List typedefs = _exportedAndLocalElements - .whereType() - .map((e) => modelBuilder.from(e, this) as Typedef) - .toList(growable: false); + .whereType() + .map((e) => modelBuilder.from(e, this) as Typedef) + .toList(growable: false); TypeSystem get typeSystem => element.typeSystem; - late final List allClasses = _exportedAndLocalElements - .whereType() - .where((e) => !e.isMixin && !e.isEnum) - .map((e) => modelBuilder.from(e, this) as Class) - .toList(growable: false); + .whereType() + .where((e) => !e.isMixin && !e.isEnum) + .map((e) => modelBuilder.from(e, this) as Class) + .toList(growable: false); Class? getClassByName(String name) { return allClasses.firstWhereOrNull((it) => it.name == name); @@ -560,19 +558,19 @@ class Library extends ModelElement with Categorization, TopLevelContainer { } late final Iterable allModelElements = [ - for (var modelElements in modelElementsMap.values) ...modelElements, - ]; - + for (var modelElements in modelElementsMap.values) ...modelElements, + ]; - late final Iterable allCanonicalModelElements = - allModelElements.where((e) => e.isCanonical).toList(); + late final Iterable allCanonicalModelElements = + allModelElements.where((e) => e.isCanonical).toList(); Map? _referenceChildren; @override Map get referenceChildren { if (_referenceChildren == null) { _referenceChildren = {}; - var definedNamesModelElements = element.exportNamespace.definedNames.values + var definedNamesModelElements = element + .exportNamespace.definedNames.values .map((v) => modelBuilder.fromElement(v)); _referenceChildren!.addEntries( definedNamesModelElements.whereNotType().generateEntries()); diff --git a/lib/src/model/library_container.dart b/lib/src/model/library_container.dart index 4d3ee50689..e8594c94f0 100644 --- a/lib/src/model/library_container.dart +++ b/lib/src/model/library_container.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:collection/collection.dart'; import 'package:dartdoc/src/model/model.dart'; import 'package:dartdoc/src/model_utils.dart' as model_utils; diff --git a/lib/src/model/locatable.dart b/lib/src/model/locatable.dart index c00866ec25..27633b63f9 100644 --- a/lib/src/model/locatable.dart +++ b/lib/src/model/locatable.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart' show Element; /// Something that can be located for warning purposes. diff --git a/lib/src/model/method.dart b/lib/src/model/method.dart index 1f1d247a96..14e5be8f7e 100644 --- a/lib/src/model/method.dart +++ b/lib/src/model/method.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/source/line_info.dart'; // ignore: implementation_imports @@ -71,7 +69,8 @@ class Method extends ModelElement @override String? get href { - assert(!identical(canonicalModelElement, this) || canonicalEnclosingContainer == enclosingElement); + assert(!identical(canonicalModelElement, this) || + canonicalEnclosingContainer == enclosingElement); return super.href; } @@ -93,11 +92,12 @@ class Method extends ModelElement String get kind => 'method'; @override - ExecutableMember? get originalMember => super.originalMember as ExecutableMember?; + ExecutableMember? get originalMember => + super.originalMember as ExecutableMember?; Callable? _modelType; - Callable get modelType => (_modelType ??= - modelBuilder.typeFrom((originalMember ?? element)!.type, library!) as Callable?)!; + Callable get modelType => (_modelType ??= modelBuilder.typeFrom( + (originalMember ?? element)!.type, library!) as Callable?)!; @override Method? get overriddenElement { diff --git a/lib/src/model/mixin.dart b/lib/src/model/mixin.dart index 23b93c61aa..35e17c5065 100644 --- a/lib/src/model/mixin.dart +++ b/lib/src/model/mixin.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:dartdoc/src/element_type.dart'; @@ -22,8 +20,8 @@ class Mixin extends InheritingContainer with TypeImplementing { Iterable? get superclassConstraints { _superclassConstraints ??= [ ...element!.superclassConstraints - .map( - (InterfaceType i) => modelBuilder.typeFrom(i, library) as ParameterizedElementType) + .map((InterfaceType i) => + modelBuilder.typeFrom(i, library) as ParameterizedElementType) .where((t) => t.modelElement != packageGraph.specialClasses[SpecialClass.object]) diff --git a/lib/src/model/model.dart b/lib/src/model/model.dart index e84c726640..a6d40f3d2f 100644 --- a/lib/src/model/model.dart +++ b/lib/src/model/model.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - export 'accessor.dart'; export 'canonicalization.dart'; export 'categorization.dart'; diff --git a/lib/src/model/model_element.dart b/lib/src/model/model_element.dart index 1071759f0f..a0bb421bf4 100644 --- a/lib/src/model/model_element.dart +++ b/lib/src/model/model_element.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - /// The models used to represent Dart code. library dartdoc.models; @@ -50,8 +48,8 @@ ModelElement resolveMultiplyInheritedElement( late Inheritable foundInheritable; var lowIndex = enclosingClass.inheritanceChain.length; for (var inheritable in inheritables) { - var index = - enclosingClass.inheritanceChain.indexOf(inheritable.enclosingElement as InheritingContainer?); + var index = enclosingClass.inheritanceChain + .indexOf(inheritable.enclosingElement as InheritingContainer?); if (index < lowIndex) { foundInheritable = inheritable; lowIndex = index; @@ -76,8 +74,11 @@ mixin ModelElementBuilderImpl implements ModelElementBuilder { @override ModelElement fromPropertyInducingElement(Element e, Library l, - {Container? enclosingContainer, Accessor? getter, Accessor? setter}) => - ModelElement._fromPropertyInducingElement(e as PropertyInducingElement, l, packageGraph, + {Container? enclosingContainer, + Accessor? getter, + Accessor? setter}) => + ModelElement._fromPropertyInducingElement( + e as PropertyInducingElement, l, packageGraph, enclosingContainer: enclosingContainer, getter: getter, setter: setter); @@ -130,7 +131,6 @@ abstract class ModelElement extends Canonicalization final Member? _originalMember; final Library? _library; - String? _linkedName; ModelElement(this._element, this._library, this._packageGraph, @@ -185,12 +185,14 @@ abstract class ModelElement extends Canonicalization newModelElement = EnumField.forConstant(index, e, library, packageGraph, getter); } else if (e.enclosingElement is ExtensionElement) { - newModelElement = Field(e, library, packageGraph, getter as ContainerAccessor?, setter as ContainerAccessor?); + newModelElement = Field(e, library, packageGraph, + getter as ContainerAccessor?, setter as ContainerAccessor?); } else if (e.enclosingElement is ClassElement && (e.enclosingElement as ClassElement).isEnum) { newModelElement = EnumField(e, library, packageGraph, getter, setter); } else { - newModelElement = Field(e, library, packageGraph, getter as ContainerAccessor?, setter as ContainerAccessor?); + newModelElement = Field(e, library, packageGraph, + getter as ContainerAccessor?, setter as ContainerAccessor?); } } else { // EnumFields can't be inherited, so this case is simpler. @@ -254,11 +256,13 @@ abstract class ModelElement extends Canonicalization var key = Tuple3(e, library, enclosingContainer); if (packageGraph.allConstructedModelElements.containsKey(key)) { - return packageGraph.allConstructedModelElements[key as Tuple3]!; + return packageGraph.allConstructedModelElements[ + key as Tuple3]!; } var newModelElement = ModelElement._fromParameters(e, library, packageGraph, - enclosingContainer: enclosingContainer, originalMember: originalMember)!; + enclosingContainer: enclosingContainer, + originalMember: originalMember)!; if (enclosingContainer != null) assert(newModelElement is Inheritable); _cacheNewModelElement(e, newModelElement, library, @@ -401,28 +405,28 @@ abstract class ModelElement extends Canonicalization Iterable get annotations => _annotations ??= element!.metadata .whereNot((m) => m.element == null || - packageGraph.specialClasses[SpecialClass.pragma]!.element!.constructors + packageGraph + .specialClasses[SpecialClass.pragma]!.element!.constructors .contains(m.element)) .map((m) => Annotation(m, library, packageGraph)); @override late final bool isPublic = () { - if (name == '') { - return false; - } - if (this is! Library && (library == null || !library!.isPublic)) { - return false; - } - if (enclosingElement is Class && - !(enclosingElement as Class).isPublic) { - return false; - } - if (enclosingElement is Extension && - !(enclosingElement as Extension).isPublic) { - return false; - } - return utils.hasPublicName(element!) && !hasNodoc!; - } (); + if (name == '') { + return false; + } + if (this is! Library && (library == null || !library!.isPublic)) { + return false; + } + if (enclosingElement is Class && !(enclosingElement as Class).isPublic) { + return false; + } + if (enclosingElement is Extension && + !(enclosingElement as Extension).isPublic) { + return false; + } + return utils.hasPublicName(element!) && !hasNodoc!; + }(); @override late final Map commentRefs = () { @@ -438,20 +442,19 @@ abstract class ModelElement extends Canonicalization // the element visitor, or both. assert(e is Parameter || e.modelNode != null); _commentRefs.addAll({ - for (var r in e.modelNode?.commentRefs ?? - []) + for (var r in e.modelNode?.commentRefs ?? []) r.codeRef: r }); } } } return _commentRefs; - } (); - + }(); @override - late final DartdocOptionContext config = DartdocOptionContext.fromContextElement( - packageGraph.config, library!.element, packageGraph.resourceProvider); + late final DartdocOptionContext config = + DartdocOptionContext.fromContextElement( + packageGraph.config, library!.element, packageGraph.resourceProvider); Set? _locationPieces; @@ -869,7 +872,8 @@ abstract class ModelElement extends Canonicalization // FIXME(nnbd): package should not have to be nullable just because of dynamic Package? get package => library?.package; - bool get isPublicAndPackageDocumented => isPublic&& package?.isDocumented == true; + bool get isPublicAndPackageDocumented => + isPublic && package?.isDocumented == true; List? _allParameters; @@ -917,7 +921,7 @@ abstract class ModelElement extends Canonicalization if (element is TypeAliasElement) { return ModelElement._fromElement( - (element as TypeAliasElement).aliasedElement!, packageGraph) + (element as TypeAliasElement).aliasedElement!, packageGraph) .parameters; } List? params; @@ -939,10 +943,9 @@ abstract class ModelElement extends Canonicalization return [ ...params! - .map((p) => - ModelElement._from(p, library, packageGraph) as Parameter) + .map((p) => ModelElement._from(p, library, packageGraph) as Parameter) ]; - } (); + }(); @override String get documentationComment => element!.documentationComment ?? ''; @@ -977,8 +980,8 @@ abstract class ModelElement extends Canonicalization return fqName; } - return _buildFullyQualifiedName( - e.enclosingElement as ModelElement?, '${e.enclosingElement!.name}.$fqName'); + return _buildFullyQualifiedName(e.enclosingElement as ModelElement?, + '${e.enclosingElement!.name}.$fqName'); } String _calculateLinkedName() { diff --git a/lib/src/model/model_function.dart b/lib/src/model/model_function.dart index 843085625c..f5d33c4872 100644 --- a/lib/src/model/model_function.dart +++ b/lib/src/model/model_function.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; @@ -42,7 +40,8 @@ class ModelFunctionTyped extends ModelElement List? _typeParameters; @override List get typeParameters => _typeParameters ??= [ - for (var p in element!.typeParameters) modelBuilder.from(p, library!) as TypeParameter, + for (var p in element!.typeParameters) + modelBuilder.from(p, library!) as TypeParameter, ]; ModelFunctionTyped( @@ -94,6 +93,6 @@ class ModelFunctionTyped extends ModelElement FunctionTypedElement? get element => super.element as FunctionTypedElement?; Callable? _modelType; - Callable get modelType => - (_modelType ??= modelBuilder.typeFrom(element!.type, library!) as Callable?)!; + Callable get modelType => (_modelType ??= + modelBuilder.typeFrom(element!.type, library!) as Callable?)!; } diff --git a/lib/src/model/model_node.dart b/lib/src/model/model_node.dart index b0ca512251..a2d8d568f7 100644 --- a/lib/src/model/model_node.dart +++ b/lib/src/model/model_node.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/file_system/file_system.dart'; diff --git a/lib/src/model/nameable.dart b/lib/src/model/nameable.dart index 4c04a5e1ba..b8ead8010d 100644 --- a/lib/src/model/nameable.dart +++ b/lib/src/model/nameable.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:collection/collection.dart'; import 'locatable.dart'; diff --git a/lib/src/model/never.dart b/lib/src/model/never.dart index 9c6b2ba255..9b88f0ca95 100644 --- a/lib/src/model/never.dart +++ b/lib/src/model/never.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/operator.dart b/lib/src/model/operator.dart index 369222362f..4523cfb4b0 100644 --- a/lib/src/model/operator.dart +++ b/lib/src/model/operator.dart @@ -2,11 +2,10 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; // ignore: implementation_imports -import 'package:analyzer/src/dart/element/member.dart' show ExecutableMember, Member; +import 'package:analyzer/src/dart/element/member.dart' + show ExecutableMember, Member; import 'package:dartdoc/src/comment_references/parser.dart'; import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index c371a69533..1570cf00d4 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:dartdoc/src/comment_references/model_comment_reference.dart'; @@ -195,7 +193,7 @@ class Package extends LibraryContainer } else { if (config.linkToRemote && config.linkToUrl.isNotEmpty && - isPublic&& + isPublic && !packageGraph.config.isPackageExcluded(name)) { _documentedWhere = DocumentLocation.remote; } else { @@ -330,7 +328,7 @@ class Package extends LibraryContainer late final List categories = () { return nameToCategory.values.toList()..sort(); - } (); + }(); Iterable get categoriesWithPublicLibraries => categories.where((c) => c.publicLibraries.isNotEmpty); @@ -351,9 +349,9 @@ class Package extends LibraryContainer @override late final DartdocOptionContext config = DartdocOptionContext.fromContext( - packageGraph.config, - packageGraph.resourceProvider.getFolder(packagePath!), - packageGraph.resourceProvider); + packageGraph.config, + packageGraph.resourceProvider.getFolder(packagePath!), + packageGraph.resourceProvider); /// Is this the package at the top of the list? We display the first /// package specially (with "Libraries" rather than the package name). diff --git a/lib/src/model/package_builder.dart b/lib/src/model/package_builder.dart index dcdee13980..6852b02570 100644 --- a/lib/src/model/package_builder.dart +++ b/lib/src/model/package_builder.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'dart:async'; import 'package:analyzer/dart/analysis/analysis_context_collection.dart'; @@ -82,11 +80,9 @@ class PubPackageBuilder implements PackageBuilder { return newGraph; } - late final DartSdk sdk = packageMetaProvider.defaultSdk ?? - FolderBasedDartSdk( - resourceProvider, resourceProvider.getFolder(config.sdkDir)); - + FolderBasedDartSdk( + resourceProvider, resourceProvider.getFolder(config.sdkDir)); EmbedderSdk? _embedderSdk; @@ -256,7 +252,8 @@ class PubPackageBuilder implements PackageBuilder { if (autoIncludeDependencies) { var info = await (packageConfigProvider - .findPackageConfig(resourceProvider.getFolder(basePackageDir)) as FutureOr); + .findPackageConfig(resourceProvider.getFolder(basePackageDir)) + as FutureOr); for (var package in info.packages) { if (!filterExcludes || !config.exclude.contains(package.name)) { packageDirs.add(_pathContext.dirname( diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index 2ba67c9ad1..f85f11c553 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart' hide CommentReference; @@ -212,7 +210,8 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { final allLibraries = {}; /// All ModelElements constructed for this package; a superset of [allModelElements]. - final HashMap, ModelElement?> allConstructedModelElements = + final HashMap, ModelElement?> + allConstructedModelElements = HashMap, ModelElement?>(); /// Anything that might be inheritable, place here for later lookup. @@ -282,7 +281,8 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { bool _localDocumentationBuilt = false; /// Keep track of warnings. - late final PackageWarningCounter packageWarningCounter = PackageWarningCounter(this); + late final PackageWarningCounter packageWarningCounter = + PackageWarningCounter(this); final Set> _warnAlreadySeen = {}; @@ -601,7 +601,8 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { if (!implemented.isPublic) { privates.add(implemented); } - implemented = implemented.canonicalModelElement as InheritingContainer? ?? implemented; + implemented = implemented.canonicalModelElement as InheritingContainer? ?? + implemented; _implementors.putIfAbsent(implemented, () => []); var list = _implementors[implemented]!; // TODO(srawlins): This would be more efficient if we created a @@ -613,7 +614,8 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { void addImplementor(InheritingContainer clazz) { if (clazz.supertype != null) { - checkAndAddContainer(clazz.supertype!.modelElement as InheritingContainer, clazz); + checkAndAddContainer( + clazz.supertype!.modelElement as InheritingContainer, clazz); } if (clazz is Class) { for (var type in clazz.mixedInTypes) { @@ -662,9 +664,9 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { } late final Iterable localPublicLibraries = () { - assert(allLibrariesAdded); - return utils.filterNonPublic(localLibraries!).toList(); - } (); + assert(allLibrariesAdded); + return utils.filterNonPublic(localLibraries!).toList(); + }(); Set? _inheritThrough; @@ -761,7 +763,8 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { ModelElement? modelElement; // For elements defined in extensions, they are canonical. if (e?.enclosingElement is ExtensionElement) { - lib ??= modelBuilder.fromElement(e!.enclosingElement!.library!) as Library?; + lib ??= + modelBuilder.fromElement(e!.enclosingElement!.library!) as Library?; // (TODO:keertip) Find a better way to exclude members of extensions // when libraries are specified using the "--include" flag if (lib?.isDocumented == true) { @@ -781,22 +784,28 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { var keyWithClass = Tuple4( e, lib, preferredClass as Class?, null); if (allConstructedModelElements.containsKey(key)) { - candidates.add(allConstructedModelElements[key as Tuple3]); + candidates.add(allConstructedModelElements[ + key as Tuple3]); } if (allConstructedModelElements.containsKey(keyWithClass)) { - candidates.add(allConstructedModelElements[keyWithClass as Tuple3]); + candidates.add(allConstructedModelElements[ + keyWithClass as Tuple3]); } if (candidates.isEmpty && allInheritableElements.containsKey(iKey)) { - candidates - .addAll(allInheritableElements[iKey as Tuple2]!.where((me) => me.isCanonical)); + candidates.addAll( + allInheritableElements[iKey as Tuple2]! + .where((me) => me.isCanonical)); } - Class? canonicalClass = findCanonicalModelElementFor(e!.enclosingElement) as Class?; + Class? canonicalClass = + findCanonicalModelElementFor(e!.enclosingElement) as Class?; if (canonicalClass != null) { candidates.addAll(canonicalClass.allCanonicalModelElements.where((m) { return m.element == e; })); } - var matches = {...candidates.where((me) => me!.isCanonical)}; + var matches = { + ...candidates.where((me) => me!.isCanonical) + }; // It's possible to find accessors but no combos. Be sure that if we // have Accessors, we find their combos too. diff --git a/lib/src/model/parameter.dart b/lib/src/model/parameter.dart index 62e4a0b714..270e6705cf 100644 --- a/lib/src/model/parameter.dart +++ b/lib/src/model/parameter.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; // ignore: implementation_imports import 'package:analyzer/src/dart/element/member.dart' show ParameterMember; @@ -22,7 +20,8 @@ class Parameter extends ModelElement implements EnclosedElement { } @override - ModelElement get enclosingElement => modelBuilder.from(element!.enclosingElement!, library!); + ModelElement get enclosingElement => + modelBuilder.from(element!.enclosingElement!, library!); bool get hasDefaultValue { return element!.defaultValueCode != null && @@ -106,7 +105,8 @@ class Parameter extends ModelElement implements EnclosedElement { ParameterElement? get element => super.element as ParameterElement?; @override - ParameterMember? get originalMember => super.originalMember as ParameterMember?; + ParameterMember? get originalMember => + super.originalMember as ParameterMember?; ElementType? _modelType; ElementType get modelType => _modelType ??= diff --git a/lib/src/model/prefix.dart b/lib/src/model/prefix.dart index 8045d22217..be1a931ba1 100644 --- a/lib/src/model/prefix.dart +++ b/lib/src/model/prefix.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/scope.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; diff --git a/lib/src/model/privacy.dart b/lib/src/model/privacy.dart index af4ee55725..9961eb0dda 100644 --- a/lib/src/model/privacy.dart +++ b/lib/src/model/privacy.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - /// Classes implementing this have a public/private distinction. abstract class Privacy { bool get isPublic; diff --git a/lib/src/model/source_code_mixin.dart b/lib/src/model/source_code_mixin.dart index 9694d4282f..d5dfd98a0d 100644 --- a/lib/src/model/source_code_mixin.dart +++ b/lib/src/model/source_code_mixin.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/source/line_info.dart'; import 'package:dartdoc/src/model/model.dart'; diff --git a/lib/src/model/top_level_container.dart b/lib/src/model/top_level_container.dart index 174bbbd2d7..2148dcd8e6 100644 --- a/lib/src/model/top_level_container.dart +++ b/lib/src/model/top_level_container.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:dartdoc/src/model/model.dart'; import 'package:dartdoc/src/model_utils.dart' as model_utils; diff --git a/lib/src/model/top_level_variable.dart b/lib/src/model/top_level_variable.dart index e5ca5725ce..2fb9f905ff 100644 --- a/lib/src/model/top_level_variable.dart +++ b/lib/src/model/top_level_variable.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; import 'package:dartdoc/src/model/feature.dart'; @@ -82,7 +80,8 @@ class TopLevelVariable extends ModelElement @override String get fileName => '${isConst ? '$name-constant' : name}.$fileType'; - TopLevelVariableElement? get _variable => (element as TopLevelVariableElement?); + TopLevelVariableElement? get _variable => + (element as TopLevelVariableElement?); @override Package get package => super.package!; diff --git a/lib/src/model/type_parameter.dart b/lib/src/model/type_parameter.dart index 52409a8107..33b18742ee 100644 --- a/lib/src/model/type_parameter.dart +++ b/lib/src/model/type_parameter.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:dartdoc/src/element_type.dart'; import 'package:dartdoc/src/model/comment_referable.dart'; @@ -16,7 +14,8 @@ class TypeParameter extends ModelElement { : super(element, library, packageGraph); @override - ModelElement get enclosingElement => modelBuilder.from(element!.enclosingElement!, library!); + ModelElement get enclosingElement => + modelBuilder.from(element!.enclosingElement!, library!); @override String get filePath => @@ -47,8 +46,8 @@ class TypeParameter extends ModelElement { @override late final String name = element!.bound != null - ? '${element!.name} extends ${boundType!.nameWithGenerics}' - : element!.name; + ? '${element!.name} extends ${boundType!.nameWithGenerics}' + : element!.name; String? _linkedName; @@ -65,7 +64,7 @@ class TypeParameter extends ModelElement { var boundType = this.boundType; if (boundType == null) return {}; return {boundType.name: boundType}; - } (); + }(); @override Iterable get referenceParents => [enclosingElement]; diff --git a/lib/src/model/typedef.dart b/lib/src/model/typedef.dart index 37a9745feb..9964a839c1 100644 --- a/lib/src/model/typedef.dart +++ b/lib/src/model/typedef.dart @@ -2,8 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. - - import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:dartdoc/src/element_type.dart'; From dbf872118bad4f33d28d63ee7a3d2a7ec5db78b9 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Fri, 15 Oct 2021 13:03:51 -0700 Subject: [PATCH 12/21] close --- lib/src/model/extension.dart | 5 +- lib/src/model/field.dart | 7 +- lib/src/model/inheriting_container.dart | 4 +- lib/src/model/library.dart | 246 +++++++++--------------- lib/src/model/package.dart | 75 +++----- lib/src/model/package_builder.dart | 4 +- lib/src/model/package_graph.dart | 5 +- lib/src/model_utils.dart | 4 +- lib/src/package_meta.dart | 9 +- test/end2end/model_test.dart | 2 +- 10 files changed, 145 insertions(+), 216 deletions(-) diff --git a/lib/src/model/extension.dart b/lib/src/model/extension.dart index 909459967f..14be030fd6 100644 --- a/lib/src/model/extension.dart +++ b/lib/src/model/extension.dart @@ -60,7 +60,10 @@ class Extension extends Container implements EnclosedElement { } @override - String get name => super.name; + ExtensionElement get element => super.element as ExtensionElement; + + @override + String get name => element.name == null ? '' : super.name; List? _declaredFields; diff --git a/lib/src/model/field.dart b/lib/src/model/field.dart index e9ee5d164d..d99318633b 100644 --- a/lib/src/model/field.dart +++ b/lib/src/model/field.dart @@ -11,7 +11,7 @@ class Field extends ModelElement with GetterSetterCombo, ContainerMember, Inheritable implements EnclosedElement { bool _isInherited = false; - Container? _enclosingContainer; + late final Container _enclosingContainer; @override final ContainerAccessor? getter; @override @@ -56,8 +56,9 @@ class Field extends ModelElement } @override - Container get enclosingElement => - modelBuilder.from(field!.enclosingElement, library) as Container; + Container get enclosingElement => isInherited + ? _enclosingContainer + : modelBuilder.from(field!.enclosingElement, library) as Container; @override String get filePath => diff --git a/lib/src/model/inheriting_container.dart b/lib/src/model/inheriting_container.dart index 1cc36b4c0b..866389f859 100644 --- a/lib/src/model/inheriting_container.dart +++ b/lib/src/model/inheriting_container.dart @@ -570,14 +570,14 @@ abstract class InheritingContainer extends Container (setter == null || setter.isInherited)) { // Field is 100% inherited. field = modelBuilder.fromPropertyInducingElement(f!, library, - enclosingContainer: this, getter: getter!, setter: setter!) as Field; + enclosingContainer: this, getter: getter, setter: setter) as Field; } else { // Field is <100% inherited (could be half-inherited). // TODO(jcollins-g): Navigation is probably still confusing for // half-inherited fields when traversing the inheritance tree. Make // this better, somehow. field = modelBuilder.fromPropertyInducingElement(f!, library, - getter: getter!, setter: setter!) as Field; + getter: getter, setter: setter) as Field; } _allFields!.add(field); } diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index d73d86eee0..ee24627e8d 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -22,6 +22,7 @@ import 'package:dartdoc/src/model/model.dart'; import 'package:dartdoc/src/package_meta.dart' show PackageMeta; import 'package:dartdoc/src/quiver.dart' as quiver; import 'package:dartdoc/src/warnings.dart'; +import 'package:meta/meta.dart'; /// Find all hashable children of a given element that are defined in the /// [LibraryElement] given at initialization. @@ -140,8 +141,8 @@ class Library extends ModelElement with Categorization, TopLevelContainer { Iterable? get _allOriginalModelElementNames { __allOriginalModelElementNames ??= allModelElements.map((e) { if (e is GetterSetterCombo) { - late Accessor getter; - late Accessor setter; + Accessor? getter; + Accessor? setter; if (e.hasGetter) { getter = modelBuilder.fromElement(e.getter!.element!) as Accessor; } @@ -208,82 +209,45 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override late final Iterable constants = - _getVariables().where((v) => v.isConst).toList(growable: false); - - late final Set _packageImportedExportedLibraries; - - /// Returns all libraries either imported by or exported by any public library - /// this library's package. (Not [PackageGraph], but sharing a package name). - /// - /// Note: will still contain non-public libraries because those can be - /// imported or exported. - // TODO(jcollins-g): move this to [Package] once it really knows about - // more than one package. - Set get packageImportedExportedLibraries { - if (_packageImportedExportedLibraries == null) { - _packageImportedExportedLibraries = {}; - packageGraph.publicLibraries! - .where((l) => l.packageName == packageName) - .forEach((l) { - _packageImportedExportedLibraries.addAll(l.importedExportedLibraries); - }); - } - return _packageImportedExportedLibraries; - } - - late final Set _importedExportedLibraries; - - /// Returns all libraries either imported by or exported by this library, - /// recursively. - Set get importedExportedLibraries { - if (_importedExportedLibraries == null) { - _importedExportedLibraries = {}; - var importedExportedLibraryElements = {}; - importedExportedLibraryElements.addAll(element.importedLibraries); - importedExportedLibraryElements.addAll(element.exportedLibraries); - for (var l in importedExportedLibraryElements) { - var lib = modelBuilder.fromElement(l) as Library; - _importedExportedLibraries.add(lib); - _importedExportedLibraries.addAll(lib.importedExportedLibraries); - } + _variables.where((v) => v.isConst).toList(growable: false); + + /// Returns all libraries directly imported or exported by this library. + @visibleForTesting + late final Set importedExportedLibrariesLocal = () { + var _importedExportedLibraries = {}; + for (var l in {...element.importedLibraries, ...element.exportedLibraries}) { + var lib = modelBuilder.fromElement(l) as Library; + _importedExportedLibraries.add(lib); } return _importedExportedLibraries; - } - - late final Map> _prefixToLibrary; + } (); /// Map of import prefixes ('import "foo" as prefix;') to [Library]. - Map> get prefixToLibrary { - if (_prefixToLibrary == null) { - _prefixToLibrary = {}; - // It is possible to have overlapping prefixes. - for (var i in element.imports) { - var prefixName = i.prefix?.name; - // Ignore invalid imports. - if (prefixName != null && i.importedLibrary != null) { - _prefixToLibrary - .putIfAbsent(prefixName, () => {}) - .add(modelBuilder.from(i.importedLibrary!, library) as Library); - } + late final Map> prefixToLibrary = () { + var prefixToLibrary = >{}; + // It is possible to have overlapping prefixes. + for (var i in element.imports) { + var prefixName = i.prefix?.name; + // Ignore invalid imports. + if (prefixName != null && i.importedLibrary != null) { + prefixToLibrary + .putIfAbsent(prefixName, () => {}) + .add(modelBuilder.from(i.importedLibrary!, library) as Library); } } - return _prefixToLibrary; - } - - late final String _dirName; + return prefixToLibrary; + } (); - String get dirName { - if (_dirName == null) { - _dirName = name; + late final String dirName = () { + var _dirName = name; if (isAnonymous) { _dirName = nameFromPath; } _dirName = _dirName.replaceAll(':', '-').replaceAll('/', '_'); - } - return _dirName; - } + return _dirName; + } (); - late final Set? _canonicalFor; + Set? _canonicalFor; Set get canonicalFor { if (_canonicalFor == null) { @@ -380,33 +344,25 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @override Library get library => this; - late final String _name; - @override - String get name { - if (_name == null) { - var source = element.source; - - if (source.uri.isScheme('dart')) { - // There are inconsistencies in library naming + URIs for the dart - // internal libraries; rationalize them here. - if (source.uri.toString().contains('/')) { - _name = element.name.replaceFirst('dart.', 'dart:'); - } else { - _name = source.uri.toString(); - } - } else if (element.name != null && element.name.isNotEmpty) { - _name = element.name; - } else { - _name = pathContext.basename(source.fullName); - if (_name.endsWith('.dart')) { - _name = _name.substring(0, _name.length - '.dart'.length); - } + late final String name = () { + var source = element.source; + if (source.uri.isScheme('dart')) { + // There are inconsistencies in library naming + URIs for the dart + // internal libraries; rationalize them here. + if (source.uri.toString().contains('/')) { + return element.name.replaceFirst('dart.', 'dart:'); } + return source.uri.toString(); + } else if (element.name.isNotEmpty) { + return element.name; + } + var _name = pathContext.basename(source.fullName); + if (_name.endsWith('.dart')) { + _name = _name.substring(0, _name.length - '.dart'.length); } - return _name; - } + }(); /// Generate a name for this library based on its location. /// @@ -435,7 +391,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { /// All variables ("properties") except constants. @override late final Iterable properties = - _getVariables().where((v) => !v.isConst).toList(growable: false); + _variables.where((v) => !v.isConst).toList(growable: false); @override late final List typedefs = _exportedAndLocalElements @@ -455,33 +411,28 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return allClasses.firstWhereOrNull((it) => it.name == name); } - late final List _variables; - - List _getVariables() { - if (_variables == null) { - var elements = _exportedAndLocalElements - .whereType() - .toSet(); - elements.addAll(_exportedAndLocalElements - .whereType() - .map((a) => a.variable as TopLevelVariableElement)); - _variables = []; - for (var element in elements) { - late Accessor getter; - if (element.getter != null) { - getter = modelBuilder.from(element.getter!, this) as Accessor; - } - late Accessor setter; - if (element.setter != null) { - setter = modelBuilder.from(element.setter!, this) as Accessor; - } - var me = modelBuilder.fromPropertyInducingElement(element, this, - getter: getter, setter: setter); - _variables.add(me as TopLevelVariable); + late final List _variables = () { + var elements = + _exportedAndLocalElements.whereType().toSet(); + elements.addAll(_exportedAndLocalElements + .whereType() + .map((a) => a.variable as TopLevelVariableElement)); + var _variables = []; + for (var element in elements) { + Accessor? getter; + if (element.getter != null) { + getter = modelBuilder.from(element.getter!, this) as Accessor; + } + Accessor? setter; + if (element.setter != null) { + setter = modelBuilder.from(element.setter!, this) as Accessor; } + var me = modelBuilder.fromPropertyInducingElement(element, this, + getter: getter, setter: setter); + _variables.add(me as TopLevelVariable); } return _variables; - } + }(); /// Reverses URIs if needed to get a package URI. /// @@ -512,50 +463,33 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return name; } - late final HashMap> _modelElementsMap; - - HashMap> get modelElementsMap { - if (_modelElementsMap == null) { - var results = quiver.concat(>[ - library.constants, - library.functions, - library.properties, - library.typedefs, - library.extensions.expand((e) { - return quiver.concat([ - [e], - e.allModelElements! - ]); - }), - library.allClasses.expand((c) { - return quiver.concat([ - [c], - c.allModelElements! - ]); - }), - library.enums.expand((e) { - return quiver.concat([ - [e], - e.allModelElements! - ]); - }), - library.mixins.expand((m) { - return quiver.concat([ - [m], - m.allModelElements! - ]); - }), - ]); - _modelElementsMap = HashMap>(); - for (var modelElement in results) { - _modelElementsMap - .putIfAbsent(modelElement.element!, () => {}) - .add(modelElement); - } - _modelElementsMap.putIfAbsent(element, () => {}).add(this); + late final HashMap> modelElementsMap = () { + var _modelElementsMap = HashMap>(); + for (var modelElement in [ + ...library.constants, + ...library.functions, + ...library.properties, + ...library.typedefs, + ...library.extensions.expand((e) { + return [e, ...e.allModelElements!]; + }), + ...library.allClasses.expand((c) { + return [c, ...c.allModelElements!]; + }), + ...library.enums.expand((e) { + return [e, ...e.allModelElements!]; + }), + ...library.mixins.expand((m) { + return [m, ...m.allModelElements!]; + }), + ]) { + _modelElementsMap + .putIfAbsent(modelElement.element!, () => {}) + .add(modelElement); } + _modelElementsMap.putIfAbsent(element, () => {}).add(this); return _modelElementsMap; - } + }(); late final Iterable allModelElements = [ for (var modelElements in modelElementsMap.values) ...modelElements, diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index 1570cf00d4..ca7780d8d1 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -156,53 +156,42 @@ class Package extends LibraryContainer @override late final bool isPublic = libraries.any((l) => l.isPublic); - bool? _isLocal; - /// Return true if this is the default package, this is part of an embedder /// SDK, or if [DartdocOptionContext.autoIncludeDependencies] is true -- but /// only if the package was not excluded on the command line. - bool? get isLocal { - _isLocal ??= ( - // Document as local if this is the default package. - packageMeta == packageGraph.packageMeta || - // Assume we want to document an embedded SDK as local if - // it has libraries defined in the default package. - // TODO(jcollins-g): Handle case where embedder SDKs can be - // assembled from multiple locations? - packageGraph.hasEmbedderSdk && - packageMeta.isSdk && - libraries.any((l) => _pathContext.isWithin( - packageGraph.packageMeta.dir.path, - (l.element.source.fullName))) || - // autoIncludeDependencies means everything is local. - packageGraph.config.autoIncludeDependencies) && - // Regardless of the above rules, do not document as local if - // we excluded this package by name. - !packageGraph.config.isPackageExcluded(name); - return _isLocal; - } - - late DocumentLocation _documentedWhere; - - DocumentLocation get documentedWhere { - if (_documentedWhere == null) { - if (isLocal!) { - if (isPublic) { - _documentedWhere = DocumentLocation.local; - } - } else { - if (config.linkToRemote && - config.linkToUrl.isNotEmpty && - isPublic && - !packageGraph.config.isPackageExcluded(name)) { - _documentedWhere = DocumentLocation.remote; - } else { - _documentedWhere = DocumentLocation.missing; - } + late final bool isLocal = ( + // Document as local if this is the default package. + packageMeta == packageGraph.packageMeta || + // Assume we want to document an embedded SDK as local if + // it has libraries defined in the default package. + // TODO(jcollins-g): Handle case where embedder SDKs can be + // assembled from multiple locations? + packageGraph.hasEmbedderSdk && + packageMeta.isSdk && + libraries.any((l) => _pathContext.isWithin( + packageGraph.packageMeta.dir.path, + (l.element.source.fullName))) || + // autoIncludeDependencies means everything is local. + packageGraph.config.autoIncludeDependencies) && + // Regardless of the above rules, do not document as local if + // we excluded this package by name. + !packageGraph.config.isPackageExcluded(name); + + late final DocumentLocation documentedWhere = () { + if (isLocal) { + if (isPublic) { + return DocumentLocation.local; } + assert(false, 'Local non public package?'); } - return _documentedWhere; - } + if (config.linkToRemote && + config.linkToUrl.isNotEmpty && + isPublic && + !packageGraph.config.isPackageExcluded(name)) { + return DocumentLocation.remote; + } + return DocumentLocation.missing; + }(); @override String get enclosingName => packageGraph.defaultPackageName; @@ -327,7 +316,7 @@ class Package extends LibraryContainer } late final List categories = () { - return nameToCategory.values.toList()..sort(); + return nameToCategory.values.where((c) => c.name.isNotEmpty).toList()..sort(); }(); Iterable get categoriesWithPublicLibraries => diff --git a/lib/src/model/package_builder.dart b/lib/src/model/package_builder.dart index 6852b02570..7b424fad15 100644 --- a/lib/src/model/package_builder.dart +++ b/lib/src/model/package_builder.dart @@ -60,7 +60,7 @@ class PubPackageBuilder implements PackageBuilder { 'Top level package requires Flutter but FLUTTER_ROOT environment variable not set'); } if (config.topLevelPackageMeta.needsPubGet) { - config.topLevelPackageMeta.runPubGet(config.flutterRoot!); + config.topLevelPackageMeta.runPubGet(config.flutterRoot); } } @@ -96,8 +96,8 @@ class PubPackageBuilder implements PackageBuilder { ResourceProvider get resourceProvider => packageMetaProvider.resourceProvider; + /// Do not call more than once for a given PackageBuilder. Future _calculatePackageMap() async { - assert(_packageMap == null); _packageMap = >{}; Folder cwd = resourceProvider.getResource(config.inputDir) as Folder; var info = await packageConfigProvider diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index f85f11c553..ffa87f901c 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -80,6 +80,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { findOrCreateLibraryFor(resolvedLibrary); } + /// Call after all libraries are added. Future initializePackageGraph() async { allLibrariesAdded = true; @@ -103,7 +104,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { _addToImplementors(library.mixins); _extensions.addAll(library.extensions); } - if (package.isLocal! && !package.hasPublicLibraries) { + if (package.isLocal && !package.hasPublicLibraries) { package.warn(PackageWarning.noDocumentableLibrariesInPackage); } } @@ -504,7 +505,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// Local packages are to be documented locally vs. remote or not at all. List get localPackages => - publicPackages!.where((p) => p.isLocal!).toList(); + publicPackages!.where((p) => p.isLocal).toList(); /// Documented packages are documented somewhere (local or remote). Iterable get documentedPackages => diff --git a/lib/src/model_utils.dart b/lib/src/model_utils.dart index 6509d6cb58..71889910d0 100644 --- a/lib/src/model_utils.dart +++ b/lib/src/model_utils.dart @@ -95,9 +95,7 @@ Iterable findCanonicalFor( Iterable containers) { return containers.map((c) => c.packageGraph.findCanonicalModelElementFor(c.element) - as InheritingContainer ?? - // FIXME(nnbd) : remove ignore after package_graph is migrated - // ignore: dead_null_aware_expression + as InheritingContainer? ?? c); } diff --git a/lib/src/package_meta.dart b/lib/src/package_meta.dart index 99cd3db50c..6fb0c663f4 100644 --- a/lib/src/package_meta.dart +++ b/lib/src/package_meta.dart @@ -133,7 +133,7 @@ abstract class PackageMeta { bool get requiresFlutter; - void runPubGet(String flutterRoot); + void runPubGet(String? flutterRoot); String get name; @@ -355,10 +355,13 @@ class _FilePackageMeta extends PubPackageMeta { .exists); @override - void runPubGet(String flutterRoot) { + void runPubGet(String? flutterRoot) { String binPath; List parameters; if (requiresFlutter) { + if (flutterRoot == null) { + throw DartdocFailure('Package requires flutter but FLUTTER_ROOT unset'); + } binPath = p.join(flutterRoot, 'bin', 'flutter'); if (Platform.isWindows) binPath += '.bat'; parameters = ['pub', 'get']; @@ -459,7 +462,7 @@ class _SdkMeta extends PubPackageMeta { bool get isSdk => true; @override - void runPubGet(String flutterRoot) { + void runPubGet(String? flutterRoot) { throw 'unsupported operation'; } diff --git a/test/end2end/model_test.dart b/test/end2end/model_test.dart index da005cbb74..7ce9c8dc34 100644 --- a/test/end2end/model_test.dart +++ b/test/end2end/model_test.dart @@ -1049,7 +1049,7 @@ void main() { test('can import other libraries with unusual URIs', () { expect( - fakeLibrary.importedExportedLibraries + fakeLibrary.importedExportedLibrariesLocal .where((l) => l.name == 'import_unusual'), isNotEmpty); }); From 4f973d71dce229a92e581a7d6494022fbf506602 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Wed, 20 Oct 2021 08:39:43 -0700 Subject: [PATCH 13/21] manual changes on renderers --- .../templates.runtime_renderers.dart | 24 ------------------- 1 file changed, 24 deletions(-) diff --git a/lib/src/generator/templates.runtime_renderers.dart b/lib/src/generator/templates.runtime_renderers.dart index 6dbb9a312e..0f053e7062 100644 --- a/lib/src/generator/templates.runtime_renderers.dart +++ b/lib/src/generator/templates.runtime_renderers.dart @@ -7628,18 +7628,6 @@ class _Renderer_Library extends RendererBase { _render_String(c.href, ast, r.template, sink, parent: r); }, ), - 'importedExportedLibraries': Property( - getValue: (CT_ c) => c.importedExportedLibraries, - renderVariable: (CT_ c, Property self, - List remainingNames) => - self.renderSimpleVariable( - c, remainingNames, 'Set'), - renderIterable: (CT_ c, RendererBase r, - List ast, StringSink sink) { - return c.importedExportedLibraries.map((e) => - _render_Library(e, ast, r.template, sink, parent: r)); - }, - ), 'inheritanceManager': Property( getValue: (CT_ c) => c.inheritanceManager, renderVariable: (CT_ c, Property self, @@ -7805,18 +7793,6 @@ class _Renderer_Library extends RendererBase { parent: r); }, ), - 'packageImportedExportedLibraries': Property( - getValue: (CT_ c) => c.packageImportedExportedLibraries, - renderVariable: (CT_ c, Property self, - List remainingNames) => - self.renderSimpleVariable( - c, remainingNames, 'Set'), - renderIterable: (CT_ c, RendererBase r, - List ast, StringSink sink) { - return c.packageImportedExportedLibraries.map((e) => - _render_Library(e, ast, r.template, sink, parent: r)); - }, - ), 'packageMeta': Property( getValue: (CT_ c) => c.packageMeta, renderVariable: (CT_ c, Property self, From 51931908c0900bdf36a3ae481bbada29aab4c110 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Wed, 20 Oct 2021 13:11:50 -0700 Subject: [PATCH 14/21] comments --- tool/subprocess_launcher.dart | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tool/subprocess_launcher.dart b/tool/subprocess_launcher.dart index 783c231835..c0ada7434d 100644 --- a/tool/subprocess_launcher.dart +++ b/tool/subprocess_launcher.dart @@ -14,9 +14,7 @@ import 'package:path/path.dart' as p; class CoverageSubprocessLauncher extends SubprocessLauncher { CoverageSubprocessLauncher(String context, [Map? environment]) : super( - context, - (environment ?? {}) - ..addAll({'DARTDOC_COVERAGE_DATA': tempDir.path})); + context, {...?environment, 'DARTDOC_COVERAGE_DATA': tempDir.path}); static int nextRun = 0; From 1d0da253cf4176b82d914b3f9288f96f985fe4b6 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Wed, 20 Oct 2021 13:59:53 -0700 Subject: [PATCH 15/21] partial --- lib/src/model/package.dart | 7 ++----- lib/src/model/package_graph.dart | 2 +- lib/src/package_meta.dart | 8 ++++---- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index ca7780d8d1..8c2e962836 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -178,11 +178,8 @@ class Package extends LibraryContainer !packageGraph.config.isPackageExcluded(name); late final DocumentLocation documentedWhere = () { - if (isLocal) { - if (isPublic) { - return DocumentLocation.local; - } - assert(false, 'Local non public package?'); + if (isLocal && isPublic) { + return DocumentLocation.local; } if (config.linkToRemote && config.linkToUrl.isNotEmpty && diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index ffa87f901c..1e11225ba5 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -299,7 +299,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // don't allow warnings we're already working on to get in there. _warnAlreadySeen.add(newEntry); _warnOnElement(warnable, kind, - message: message!, + message: message ?? '', referredFrom: referredFrom, extendedDebug: extendedDebug); _warnAlreadySeen.remove(newEntry); diff --git a/lib/src/package_meta.dart b/lib/src/package_meta.dart index 6fb0c663f4..9e267fe511 100644 --- a/lib/src/package_meta.dart +++ b/lib/src/package_meta.dart @@ -388,16 +388,16 @@ class _FilePackageMeta extends PubPackageMeta { } @override - String get name => _pubspec['name']; + String get name => _pubspec['name'] ?? ''; @override - String get version => _pubspec['version']; + String get version => _pubspec['version'] ?? '0.0.0-unknown'; @override - String get description => _pubspec['description']; + String get description => _pubspec['description'] ?? ''; @override - String get homepage => _pubspec['homepage']; + String get homepage => _pubspec['homepage'] ?? ''; @override bool get requiresFlutter => From c66cc0b6b2c1d968dfb9ec74b957035c9c323f67 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 21 Oct 2021 09:48:30 -0700 Subject: [PATCH 16/21] fix some errors post-migration --- lib/src/model/documentation_comment.dart | 2 +- lib/src/model/package.dart | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/lib/src/model/documentation_comment.dart b/lib/src/model/documentation_comment.dart index 8f6f59b4c7..79c454f9b2 100644 --- a/lib/src/model/documentation_comment.dart +++ b/lib/src/model/documentation_comment.dart @@ -337,7 +337,7 @@ mixin DocumentationComment } } else { var filePath = - element!.source!.fullName.substring(dirPath?.length ?? -1 + 1); + element!.source!.fullName.substring((dirPath?.length ?? -1) + 1); // TODO(srawlins): If a file exists at the location without the // appended 'md' extension, note this. diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index 8c2e962836..7724cacb99 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -154,14 +154,16 @@ class Package extends LibraryContainer Warnable? get enclosingElement => null; @override - late final bool isPublic = libraries.any((l) => l.isPublic); + /// If we have public libraries, this is the default package, or we are + /// auto-including dependencies, this package is public. + late final bool isPublic = libraries.any((l) => l.isPublic) || _isLocalPublicByDefault; /// Return true if this is the default package, this is part of an embedder /// SDK, or if [DartdocOptionContext.autoIncludeDependencies] is true -- but /// only if the package was not excluded on the command line. late final bool isLocal = ( // Document as local if this is the default package. - packageMeta == packageGraph.packageMeta || + _isLocalPublicByDefault || // Assume we want to document an embedded SDK as local if // it has libraries defined in the default package. // TODO(jcollins-g): Handle case where embedder SDKs can be @@ -170,13 +172,19 @@ class Package extends LibraryContainer packageMeta.isSdk && libraries.any((l) => _pathContext.isWithin( packageGraph.packageMeta.dir.path, - (l.element.source.fullName))) || - // autoIncludeDependencies means everything is local. - packageGraph.config.autoIncludeDependencies) && + (l.element.source.fullName)))) && // Regardless of the above rules, do not document as local if // we excluded this package by name. - !packageGraph.config.isPackageExcluded(name); + !_isExcluded; + /// True if the global config excludes this package by name. + late final bool _isExcluded = packageGraph.config.isPackageExcluded(name); + /// True if this is the package being documented by default, or the + /// global config indicates we are auto-including dependencies. + late final bool _isLocalPublicByDefault = (packageMeta == packageGraph.packageMeta || packageGraph.config.autoIncludeDependencies); + + /// Returns the location of documentation for this package, for linkToRemote + /// and canonicalization decision making. late final DocumentLocation documentedWhere = () { if (isLocal && isPublic) { return DocumentLocation.local; From a752169371c21dc37726d9b36940bf23be7176a3 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 21 Oct 2021 11:11:45 -0700 Subject: [PATCH 17/21] holy cow it passes the tests now --- lib/src/dartdoc_options.dart | 2 +- lib/src/element_type.dart | 70 ++++++++++++------------ lib/src/model/documentation_comment.dart | 8 ++- lib/src/model/enum.dart | 6 -- lib/src/model/extension.dart | 10 ++-- lib/src/model/field.dart | 2 + lib/src/model/inheriting_container.dart | 16 +----- lib/src/model/library.dart | 26 +++++---- lib/src/model/model_element.dart | 21 +++---- lib/src/model/package.dart | 15 +++-- lib/src/model/package_builder.dart | 4 +- lib/src/model/package_graph.dart | 9 +-- lib/src/model/parameter.dart | 3 +- lib/src/render/parameter_renderer.dart | 2 +- lib/src/warnings.dart | 18 ++++++ 15 files changed, 105 insertions(+), 107 deletions(-) diff --git a/lib/src/dartdoc_options.dart b/lib/src/dartdoc_options.dart index c4f8da93b7..344d4fb08f 100644 --- a/lib/src/dartdoc_options.dart +++ b/lib/src/dartdoc_options.dart @@ -1246,7 +1246,7 @@ class DartdocOptionContext extends DartdocOptionContextBase List get dropTextFrom => optionSet['dropTextFrom'].valueAt(context); - String get examplePathPrefix => + String? get examplePathPrefix => optionSet['examplePathPrefix'].valueAt(context); // TODO(srawlins): This memoization saved a lot of time in unit testing, but diff --git a/lib/src/element_type.dart b/lib/src/element_type.dart index fc2fe3bf56..4779815ab7 100644 --- a/lib/src/element_type.dart +++ b/lib/src/element_type.dart @@ -43,6 +43,7 @@ abstract class ElementType extends Privacy if (fElement == null || fElement.kind == ElementKind.DYNAMIC || fElement.kind == ElementKind.NEVER) { + // [UndefinedElementType]s. if (f is FunctionType) { if (f.alias?.element != null) { return AliasedFunctionTypeElementType( @@ -51,43 +52,42 @@ abstract class ElementType extends Privacy return FunctionTypeElementType(f, library, packageGraph, returnedFrom); } return UndefinedElementType(f, library, packageGraph, returnedFrom); - } else { - var element = packageGraph.modelBuilder.fromElement(fElement); - // [TypeAliasElement.aliasElement] has different implications. - // In that case it is an actual type alias of some kind (generic - // or otherwise. Here however aliasElement signals that this is a - // type referring to an alias. - if (f is! TypeAliasElement && f.alias?.element != null) { - return AliasedElementType(f as ParameterizedType, library, packageGraph, - element, returnedFrom); - } - assert(f is ParameterizedType || f is TypeParameterType); - // TODO(jcollins-g): strip out all the cruft that's accumulated - // here for non-generic type aliases. - var isGenericTypeAlias = f.alias?.element != null && f is! InterfaceType; - if (f is FunctionType) { - assert(f is ParameterizedType); - // This is an indication we have an extremely out of date analyzer.... - assert( - !isGenericTypeAlias, 'should never occur: out of date analyzer?'); - // And finally, delete this case and its associated class - // after https://dart-review.googlesource.com/c/sdk/+/201520 - // is in all published versions of analyzer this version of dartdoc - // is compatible with. - return CallableElementType( - f, library, packageGraph, element, returnedFrom); - } else if (isGenericTypeAlias) { - return GenericTypeAliasElementType(f as TypeParameterType, library, - packageGraph, element, returnedFrom); - } - if (f is TypeParameterType) { - return TypeParameterElementType( - f, library, packageGraph, element, returnedFrom); - } - assert(f is ParameterizedType); - return ParameterizedElementType( + } + // [DefinedElementType]s. + var element = packageGraph.modelBuilder.fromElement(fElement); + // [TypeAliasElement.aliasElement] has different implications. + // In that case it is an actual type alias of some kind (generic + // or otherwise. Here however aliasElement signals that this is a + // type referring to an alias. + if (f is! TypeAliasElement && f.alias?.element != null) { + return AliasedElementType( f as ParameterizedType, library, packageGraph, element, returnedFrom); } + assert(f is ParameterizedType || f is TypeParameterType); + // TODO(jcollins-g): strip out all the cruft that's accumulated + // here for non-generic type aliases. + var isGenericTypeAlias = f.alias?.element != null && f is! InterfaceType; + if (f is FunctionType) { + assert(f is ParameterizedType); + // This is an indication we have an extremely out of date analyzer.... + assert(!isGenericTypeAlias, 'should never occur: out of date analyzer?'); + // And finally, delete this case and its associated class + // after https://dart-review.googlesource.com/c/sdk/+/201520 + // is in all published versions of analyzer this version of dartdoc + // is compatible with. + return CallableElementType( + f, library, packageGraph, element, returnedFrom); + } else if (isGenericTypeAlias) { + return GenericTypeAliasElementType( + f as TypeParameterType, library, packageGraph, element, returnedFrom); + } + if (f is TypeParameterType) { + return TypeParameterElementType( + f, library, packageGraph, element, returnedFrom); + } + assert(f is ParameterizedType); + return ParameterizedElementType( + f as ParameterizedType, library, packageGraph, element, returnedFrom); } bool get canHaveParameters => false; diff --git a/lib/src/model/documentation_comment.dart b/lib/src/model/documentation_comment.dart index 79c454f9b2..0b9fb0832c 100644 --- a/lib/src/model/documentation_comment.dart +++ b/lib/src/model/documentation_comment.dart @@ -385,9 +385,10 @@ mixin DocumentationComment var ext = pathContext.extension(src); file = pathContext.join(dir, '$basename-$region$ext$fragExtension'); } - args['file'] = config.examplePathPrefix == null + var examplePathPrefix = config.examplePathPrefix; + args['file'] = examplePathPrefix == null ? file - : pathContext.join(config.examplePathPrefix, file); + : pathContext.join(examplePathPrefix, file); return args; } @@ -847,9 +848,10 @@ mixin DocumentationComment if (!config.injectHtml) return rawDocs; return rawDocs!.replaceAllMapped(_htmlInjectRegExp, (match) { - var fragment = packageGraph.getHtmlFragment(match[1])!; + var fragment = packageGraph.getHtmlFragment(match[1]); if (fragment == null) { warn(PackageWarning.unknownHtmlFragment, message: match[1]); + return ''; } return fragment; }); diff --git a/lib/src/model/enum.dart b/lib/src/model/enum.dart index f6b739ee20..607fef9de7 100644 --- a/lib/src/model/enum.dart +++ b/lib/src/model/enum.dart @@ -114,12 +114,6 @@ class EnumField extends Field { @override Inheritable? get overriddenElement => null; - @override - Package get package => super.package; - - @override - Library get library => super.library; - EnumFieldRenderer get _fieldRenderer => packageGraph.rendererFactory.enumFieldRenderer; } diff --git a/lib/src/model/extension.dart b/lib/src/model/extension.dart index 14be030fd6..b424454d4c 100644 --- a/lib/src/model/extension.dart +++ b/lib/src/model/extension.dart @@ -16,7 +16,7 @@ class Extension extends Container implements EnclosedElement { Extension( ExtensionElement element, Library library, PackageGraph packageGraph) : super(element, library, packageGraph) { - extendedType = modelBuilder.typeFrom(_extension!.extendedType, library); + extendedType = modelBuilder.typeFrom(element.extendedType, library); } /// Detect if this extension applies to every object. @@ -44,8 +44,6 @@ class Extension extends Container implements EnclosedElement { @override ModelElement? get enclosingElement => library; - ExtensionElement? get _extension => (element as ExtensionElement?); - @override String get kind => 'extension'; @@ -53,7 +51,7 @@ class Extension extends Container implements EnclosedElement { @override List? get declaredMethods { - _methods ??= _extension!.methods.map((e) { + _methods ??= element.methods.map((e) { return modelBuilder.from(e, library) as Method; }).toList(growable: false); return _methods; @@ -69,7 +67,7 @@ class Extension extends Container implements EnclosedElement { @override List? get declaredFields { - _declaredFields ??= _extension!.fields.map((f) { + _declaredFields ??= element.fields.map((f) { Accessor? getter, setter; if (f.getter != null) { getter = ContainerAccessor(f.getter, library, packageGraph); @@ -88,7 +86,7 @@ class Extension extends Container implements EnclosedElement { // a stronger hash? @override List get typeParameters { - _typeParameters ??= _extension!.typeParameters.map((f) { + _typeParameters ??= element.typeParameters.map((f) { var lib = modelBuilder.fromElement(f.enclosingElement!.library!); return modelBuilder.from(f, lib as Library) as TypeParameter; }).toList(); diff --git a/lib/src/model/field.dart b/lib/src/model/field.dart index d99318633b..60179047df 100644 --- a/lib/src/model/field.dart +++ b/lib/src/model/field.dart @@ -166,8 +166,10 @@ class Field extends ModelElement return _sourceCode; } + @override Library get library => super.library!; + @override Package get package => super.package!; @override diff --git a/lib/src/model/inheriting_container.dart b/lib/src/model/inheriting_container.dart index 866389f859..039264ae41 100644 --- a/lib/src/model/inheriting_container.dart +++ b/lib/src/model/inheriting_container.dart @@ -96,10 +96,8 @@ mixin MixedInTypes on InheritingContainer { List get mixedInTypes => _mixedInTypes ?? [ - ...element!.mixins - .map( - (f) => modelBuilder.typeFrom(f, library) as DefinedElementType) - .where((mixin) => mixin != null) + ...element!.mixins.map( + (f) => modelBuilder.typeFrom(f, library) as DefinedElementType) ]; bool get hasPublicMixedInTypes => publicMixedInTypes.isNotEmpty; @@ -402,16 +400,6 @@ abstract class InheritingContainer extends Container return __inheritedElements = []; } - if (definingLibrary == null) { - // [definingLibrary] may be null if [element] has been imported or - // exported with a non-normalized URI, like "src//a.dart". - // TODO(srawlins): It would be nice to allow references from such - // libraries, but for now, PackageGraph.allLibraries is a Map with - // LibraryElement keys, which include [Element.location] in their - // `==` calculation; I think we should not key off of Elements. - return __inheritedElements = []; - } - var inheritance = definingLibrary.inheritanceManager!; var cmap = inheritance.getInheritedConcreteMap2(element!); var imap = inheritance.getInheritedMap2(element!); diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index ee24627e8d..245edab282 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -74,7 +74,6 @@ class Library extends ModelElement with Categorization, TopLevelContainer { factory Library.fromLibraryResult(DartDocResolvedLibrary resolvedLibrary, PackageGraph packageGraph, Package package) { var element = resolvedLibrary.result.element; - if (element == null) throw ArgumentError.notNull('element'); // Initialize [packageGraph]'s cache of [ModelNode]s for relevant // elements in this library. @@ -215,12 +214,15 @@ class Library extends ModelElement with Categorization, TopLevelContainer { @visibleForTesting late final Set importedExportedLibrariesLocal = () { var _importedExportedLibraries = {}; - for (var l in {...element.importedLibraries, ...element.exportedLibraries}) { + for (var l in { + ...element.importedLibraries, + ...element.exportedLibraries + }) { var lib = modelBuilder.fromElement(l) as Library; _importedExportedLibraries.add(lib); } return _importedExportedLibraries; - } (); + }(); /// Map of import prefixes ('import "foo" as prefix;') to [Library]. late final Map> prefixToLibrary = () { @@ -236,16 +238,16 @@ class Library extends ModelElement with Categorization, TopLevelContainer { } } return prefixToLibrary; - } (); + }(); late final String dirName = () { - var _dirName = name; - if (isAnonymous) { - _dirName = nameFromPath; - } - _dirName = _dirName.replaceAll(':', '-').replaceAll('/', '_'); - return _dirName; - } (); + var _dirName = name; + if (isAnonymous) { + _dirName = nameFromPath; + } + _dirName = _dirName.replaceAll(':', '-').replaceAll('/', '_'); + return _dirName; + }(); Set? _canonicalFor; @@ -336,7 +338,7 @@ class Library extends ModelElement with Categorization, TopLevelContainer { return _inheritanceManager; } - bool get isAnonymous => element.name == null || element.name.isEmpty; + bool get isAnonymous => element.name.isEmpty; @override String get kind => 'library'; diff --git a/lib/src/model/model_element.dart b/lib/src/model/model_element.dart index a0bb421bf4..e7e66ead6a 100644 --- a/lib/src/model/model_element.dart +++ b/lib/src/model/model_element.dart @@ -160,10 +160,6 @@ abstract class ModelElement extends Canonicalization {Container? enclosingContainer, required Accessor? getter, required Accessor? setter}) { - assert(packageGraph != null); - assert(e != null); - assert(library != null); - // TODO(jcollins-g): Refactor object model to instantiate 'ModelMembers' // for members? if (e is Member) { @@ -228,8 +224,6 @@ abstract class ModelElement extends Canonicalization factory ModelElement._from( Element e, Library? library, PackageGraph packageGraph, {Container? enclosingContainer}) { - assert(packageGraph != null); - assert(e != null); assert(library != null || e is ParameterElement || e is TypeParameterElement || @@ -522,11 +516,15 @@ abstract class ModelElement extends Canonicalization } Library get definingLibrary { - Library library = modelBuilder.fromElement(element!.library!) as Library; + Library? library = modelBuilder.fromElement(element!.library!) as Library?; if (library == null) { warn(PackageWarning.noDefiningLibraryFound); } - return library; + Library? fallback; + if (enclosingElement is ModelElement) { + fallback = (enclosingElement as ModelElement).definingLibrary; + } + return library ?? fallback ?? this.library!; } Library? _canonicalLibrary; @@ -569,9 +567,6 @@ abstract class ModelElement extends Canonicalization } Library? _searchForCanonicalLibrary() { - if (definingLibrary == null) { - return null; - } var thisAndExported = definingLibrary.exportedInLibraries; if (thisAndExported == null) { @@ -721,14 +716,14 @@ abstract class ModelElement extends Canonicalization @override CharacterLocation? get characterLocation { if (!_characterLocationIsSet) { - var lineInfo = compilationUnitElement!.lineInfo!; + var lineInfo = compilationUnitElement!.lineInfo; _characterLocationIsSet = true; assert(element!.nameOffset >= 0, 'Invalid location data for element: $fullyQualifiedName'); assert(lineInfo != null, 'No lineInfo data available for element: $fullyQualifiedName'); if (element!.nameOffset >= 0) { - _characterLocation = lineInfo.getLocation(element!.nameOffset); + _characterLocation = lineInfo?.getLocation(element!.nameOffset); } } return _characterLocation; diff --git a/lib/src/model/package.dart b/lib/src/model/package.dart index 7724cacb99..2c8d4d62e2 100644 --- a/lib/src/model/package.dart +++ b/lib/src/model/package.dart @@ -91,8 +91,7 @@ class Package extends LibraryContainer /// non-documented libraries unless they are all referenced by documented ones. final Set allLibraries = {}; - bool get hasHomepage => - packageMeta.homepage != null && packageMeta.homepage.isNotEmpty; + bool get hasHomepage => packageMeta.homepage.isNotEmpty; String get homepage => packageMeta.homepage; @@ -154,9 +153,11 @@ class Package extends LibraryContainer Warnable? get enclosingElement => null; @override + /// If we have public libraries, this is the default package, or we are /// auto-including dependencies, this package is public. - late final bool isPublic = libraries.any((l) => l.isPublic) || _isLocalPublicByDefault; + late final bool isPublic = + libraries.any((l) => l.isPublic) || _isLocalPublicByDefault; /// Return true if this is the default package, this is part of an embedder /// SDK, or if [DartdocOptionContext.autoIncludeDependencies] is true -- but @@ -179,9 +180,12 @@ class Package extends LibraryContainer /// True if the global config excludes this package by name. late final bool _isExcluded = packageGraph.config.isPackageExcluded(name); + /// True if this is the package being documented by default, or the /// global config indicates we are auto-including dependencies. - late final bool _isLocalPublicByDefault = (packageMeta == packageGraph.packageMeta || packageGraph.config.autoIncludeDependencies); + late final bool _isLocalPublicByDefault = + (packageMeta == packageGraph.packageMeta || + packageGraph.config.autoIncludeDependencies); /// Returns the location of documentation for this package, for linkToRemote /// and canonicalization decision making. @@ -321,7 +325,8 @@ class Package extends LibraryContainer } late final List categories = () { - return nameToCategory.values.where((c) => c.name.isNotEmpty).toList()..sort(); + return nameToCategory.values.where((c) => c.name.isNotEmpty).toList() + ..sort(); }(); Iterable get categoriesWithPublicLibraries => diff --git a/lib/src/model/package_builder.dart b/lib/src/model/package_builder.dart index 7b424fad15..ea21b20f74 100644 --- a/lib/src/model/package_builder.dart +++ b/lib/src/model/package_builder.dart @@ -338,9 +338,7 @@ class PubPackageBuilder implements PackageBuilder { for (var file in files) { var fileContext = DartdocOptionContext.fromContext(config, config.resourceProvider.getFile(file), config.resourceProvider); - if (fileContext.includeExternal != null) { - yield* fileContext.includeExternal; - } + yield* fileContext.includeExternal; } } diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index 1e11225ba5..dd3c695feb 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -80,7 +80,6 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { findOrCreateLibraryFor(resolvedLibrary); } - /// Call after all libraries are added. Future initializePackageGraph() async { allLibrariesAdded = true; @@ -319,7 +318,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { } } else { // If we don't have an element, we need a message to disambiguate. - assert(message != null); + assert(message.isNotEmpty); } if (packageWarningCounter.hasWarning(warnable, kind, message)) { return; @@ -753,7 +752,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { {Container? preferredClass}) { assert(allLibrariesAdded); var lib = findCanonicalLibraryFor(e); - if (preferredClass != null && preferredClass is Container) { + if (preferredClass != null) { Container? canonicalClass = findCanonicalModelElementFor(preferredClass.element) as Container?; if (canonicalClass != null) preferredClass = canonicalClass; @@ -819,9 +818,7 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { // This is for situations where multiple classes may actually be canonical // for an inherited element whose defining Class is not canonical. - if (matches.length > 1 && - preferredClass != null && - preferredClass is Class) { + if (matches.length > 1 && preferredClass != null) { // Search for matches inside our superchain. var superChain = preferredClass.superChain .map((et) => et.modelElement) diff --git a/lib/src/model/parameter.dart b/lib/src/model/parameter.dart index 270e6705cf..4af1d25f6a 100644 --- a/lib/src/model/parameter.dart +++ b/lib/src/model/parameter.dart @@ -108,7 +108,6 @@ class Parameter extends ModelElement implements EnclosedElement { ParameterMember? get originalMember => super.originalMember as ParameterMember?; - ElementType? _modelType; - ElementType get modelType => _modelType ??= + late final ElementType modelType = modelBuilder.typeFrom((originalMember ?? element)!.type, library!); } diff --git a/lib/src/render/parameter_renderer.dart b/lib/src/render/parameter_renderer.dart index aad9feea19..b3061d6b27 100644 --- a/lib/src/render/parameter_renderer.dart +++ b/lib/src/render/parameter_renderer.dart @@ -210,7 +210,7 @@ abstract class ParameterRenderer { buf.write(')'); buf.write(paramModelType.nullabilitySuffix); } - } else if (param.modelType != null) { + } else { var linkedTypeName = paramModelType.linkedName; if (linkedTypeName.isNotEmpty) { buf.write(typeName(linkedTypeName)); diff --git a/lib/src/warnings.dart b/lib/src/warnings.dart index f591a2c85f..685c48617b 100644 --- a/lib/src/warnings.dart +++ b/lib/src/warnings.dart @@ -165,6 +165,24 @@ const Map packageWarningDefinitions = 'no-defining-library-found', 'The defining library for an element could not be found; the library may ' 'be imported or exported with a non-standard URI', + longHelp: [ + 'For non-canonicalized import or export paths, dartdoc can sometimes lose ', + 'track of the defining library for an element. If this happens, canonicalization', + 'will assume that reexported elements are defined somewhere it deems "reasonable", ', + 'defaulting first to the enclosing context\'s definingLibrary if available, ', + 'or the library is is visible in. This can lead to confusing documentation ', + 'structure that implies duplicate code where none exists.', + '', + 'To correct this, canonicalize all paths in the import or export chain', + 'making this symbol visible.', + '', + "For example: 'change `import 'package:dartdoc/src/model/../model/extension_target.dart';`", + "to `import 'package:dartdoc/src/model/extension_target.dart';`", + "or `import 'src/../src/foo.dart';`", + "to `import 'src/foo.dart';", + "or `import 'package:dartdoc//lib//foo.dart';", + "to `import 'package:dartdoc/lib/foo.dart';", + ], defaultWarningMode: PackageWarningMode.error), PackageWarning.notImplemented: PackageWarningDefinition( PackageWarning.notImplemented, From c53da36c14142434d08739041e90c8456da19afb Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 21 Oct 2021 12:40:02 -0700 Subject: [PATCH 18/21] make mustache happier and clean up an interface --- .../templates.aot_renderers_for_md.dart | 82 ++-- .../templates.runtime_renderers.dart | 435 ++++++++++++------ lib/src/model/categorization.dart | 8 +- lib/src/model/library.dart | 15 - lib/src/model/model_element.dart | 2 +- test/end2end/model_test.dart | 18 +- 6 files changed, 363 insertions(+), 197 deletions(-) diff --git a/lib/src/generator/templates.aot_renderers_for_md.dart b/lib/src/generator/templates.aot_renderers_for_md.dart index 7abba63417..7aef7ce29d 100644 --- a/lib/src/generator/templates.aot_renderers_for_md.dart +++ b/lib/src/generator/templates.aot_renderers_for_md.dart @@ -712,12 +712,10 @@ String renderClass(_i1.ClassTemplateData context0) { '''); var context11 = context2.potentiallyApplicableExtensions; if (context11 != null) { - for (var context12 in context11) { - buffer.writeln(); - buffer.write(''' + buffer.writeln(); + buffer.write(''' - '''); - buffer.write(context12.linkedName.toString()); - } + buffer.write(context2.linkedName.toString()); } } buffer.writeln(); @@ -726,13 +724,13 @@ String renderClass(_i1.ClassTemplateData context0) { buffer.write(''' **Annotations** '''); - var context13 = context2.annotations; - if (context13 != null) { - for (var context14 in context13) { + var context12 = context2.annotations; + if (context12 != null) { + for (var context13 in context12) { buffer.writeln(); buffer.write(''' - '''); - buffer.write(context14.linkedNameWithParameters.toString()); + buffer.write(context13.linkedNameWithParameters.toString()); } } } @@ -743,25 +741,25 @@ String renderClass(_i1.ClassTemplateData context0) { buffer.write(''' ## Constructors '''); - var context15 = context2.publicConstructorsSorted; - if (context15 != null) { - for (var context16 in context15) { + var context14 = context2.publicConstructorsSorted; + if (context14 != null) { + for (var context15 in context14) { buffer.writeln(); - buffer.write(context16.linkedName.toString()); + buffer.write(context15.linkedName.toString()); buffer.write(''' ('''); - buffer.write(context16.linkedParams.toString()); + buffer.write(context15.linkedParams.toString()); buffer.write(''') '''); - buffer.write(context16.oneLineDoc.toString()); + buffer.write(context15.oneLineDoc.toString()); buffer.write(' '); - buffer.write(context16.extendedDocLink.toString()); + buffer.write(context15.extendedDocLink.toString()); buffer.write(' '); - if (context16.isConst == true) { + if (context15.isConst == true) { buffer.write('''_const_'''); } buffer.write(' '); - if (context16.isFactory == true) { + if (context15.isFactory == true) { buffer.write('''_factory_'''); } buffer.writeln(); @@ -774,12 +772,12 @@ String renderClass(_i1.ClassTemplateData context0) { buffer.write(''' ## Properties '''); - var context17 = context2.publicInstanceFieldsSorted; - if (context17 != null) { - for (var context18 in context17) { + var context16 = context2.publicInstanceFieldsSorted; + if (context16 != null) { + for (var context17 in context16) { buffer.writeln(); buffer.write( - _renderClass_partial_property_5(context18, context2, context0)); + _renderClass_partial_property_5(context17, context2, context0)); buffer.writeln(); } } @@ -790,12 +788,12 @@ String renderClass(_i1.ClassTemplateData context0) { buffer.write(''' ## Methods '''); - var context19 = context2.publicInstanceMethodsSorted; - if (context19 != null) { - for (var context20 in context19) { + var context18 = context2.publicInstanceMethodsSorted; + if (context18 != null) { + for (var context19 in context18) { buffer.writeln(); buffer.write( - _renderClass_partial_callable_6(context20, context2, context0)); + _renderClass_partial_callable_6(context19, context2, context0)); buffer.writeln(); } } @@ -806,12 +804,12 @@ String renderClass(_i1.ClassTemplateData context0) { buffer.write(''' ## Operators '''); - var context21 = context2.publicInstanceOperatorsSorted; - if (context21 != null) { - for (var context22 in context21) { + var context20 = context2.publicInstanceOperatorsSorted; + if (context20 != null) { + for (var context21 in context20) { buffer.writeln(); buffer.write( - _renderClass_partial_callable_6(context22, context2, context0)); + _renderClass_partial_callable_6(context21, context2, context0)); buffer.writeln(); } } @@ -822,12 +820,12 @@ String renderClass(_i1.ClassTemplateData context0) { buffer.write(''' ## Static Properties '''); - var context23 = context2.publicVariableStaticFieldsSorted; - if (context23 != null) { - for (var context24 in context23) { + var context22 = context2.publicVariableStaticFieldsSorted; + if (context22 != null) { + for (var context23 in context22) { buffer.writeln(); buffer.write( - _renderClass_partial_property_5(context24, context2, context0)); + _renderClass_partial_property_5(context23, context2, context0)); buffer.writeln(); } } @@ -838,12 +836,12 @@ String renderClass(_i1.ClassTemplateData context0) { buffer.write(''' ## Static Methods '''); - var context25 = context2.publicStaticMethodsSorted; - if (context25 != null) { - for (var context26 in context25) { + var context24 = context2.publicStaticMethodsSorted; + if (context24 != null) { + for (var context25 in context24) { buffer.writeln(); buffer.write( - _renderClass_partial_callable_6(context26, context2, context0)); + _renderClass_partial_callable_6(context25, context2, context0)); buffer.writeln(); } } @@ -854,12 +852,12 @@ String renderClass(_i1.ClassTemplateData context0) { buffer.write(''' ## Constants '''); - var context27 = context2.publicConstantFieldsSorted; - if (context27 != null) { - for (var context28 in context27) { + var context26 = context2.publicConstantFieldsSorted; + if (context26 != null) { + for (var context27 in context26) { buffer.writeln(); buffer.write( - _renderClass_partial_constant_7(context28, context2, context0)); + _renderClass_partial_constant_7(context27, context2, context0)); buffer.writeln(); } } diff --git a/lib/src/generator/templates.runtime_renderers.dart b/lib/src/generator/templates.runtime_renderers.dart index c4ca533f4c..56508a6a6f 100644 --- a/lib/src/generator/templates.runtime_renderers.dart +++ b/lib/src/generator/templates.runtime_renderers.dart @@ -731,10 +731,11 @@ class _Renderer_Categorization extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.categoryNames == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.categoryNames.map((e) => - _render_String(e, ast, r.template, sink, parent: r)); + renderSimple(c.categoryNames, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); }, ), 'displayedCategories': Property( @@ -828,10 +829,11 @@ class _Renderer_Categorization extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.subCategoryNames == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.subCategoryNames.map((e) => - _render_String(e, ast, r.template, sink, parent: r)); + renderSimple(c.subCategoryNames, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); }, ), }); @@ -1599,11 +1601,11 @@ class _Renderer_Class extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.allModelElements == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.allModelElements.map((e) => _render_ModelElement( - e, ast, r.template, sink, - parent: r)); + renderSimple(c.allModelElements, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); }, ), 'constantFields': Property( @@ -2269,25 +2271,6 @@ class _Renderer_Constructor extends RendererBase { parent: r); }, ), - 'href': Property( - getValue: (CT_ c) => c.href, - renderVariable: - (CT_ c, Property self, List remainingNames) { - if (remainingNames.isEmpty) { - return self.getValue(c).toString(); - } - var name = remainingNames.first; - var nextProperty = - _Renderer_String.propertyMap().getValue(name); - return nextProperty.renderVariable(self.getValue(c), - nextProperty, [...remainingNames.skip(1)]); - }, - isNullValue: (CT_ c) => c.href == null, - renderValue: (CT_ c, RendererBase r, - List ast, StringSink sink) { - _render_String(c.href, ast, r.template, sink, parent: r); - }, - ), 'isConst': Property( getValue: (CT_ c) => c.isConst, renderVariable: (CT_ c, Property self, @@ -2786,11 +2769,11 @@ class _Renderer_Container extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.allModelElements == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.allModelElements.map((e) => _render_ModelElement( - e, ast, r.template, sink, - parent: r)); + renderSimple(c.allModelElements, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'constantFields': Property( @@ -2811,10 +2794,11 @@ class _Renderer_Container extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.declaredFields == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.declaredFields.map((e) => - _render_Field(e, ast, r.template, sink, parent: r)); + renderSimple(c.declaredFields, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'declaredMethods': Property( @@ -2823,10 +2807,11 @@ class _Renderer_Container extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.declaredMethods == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.declaredMethods.map((e) => - _render_Method(e, ast, r.template, sink, parent: r)); + renderSimple(c.declaredMethods, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'declaredOperators': Property( @@ -3035,6 +3020,46 @@ class _Renderer_Container extends RendererBase { self.renderSimpleVariable(c, remainingNames, 'bool'), getBool: (CT_ c) => c.isMixin == true, ), + 'library': Property( + getValue: (CT_ c) => c.library, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Library.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.library == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Library(c.library, ast, r.template, sink, + parent: r); + }, + ), + 'package': Property( + getValue: (CT_ c) => c.package, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Package.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.package == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Package(c.package, ast, r.template, sink, + parent: r); + }, + ), 'publicConstantFields': Property( getValue: (CT_ c) => c.publicConstantFields, renderVariable: (CT_ c, Property self, @@ -3705,12 +3730,13 @@ class _Renderer_DefinedElementType extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => + c.referenceGrandparentOverrides == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.referenceGrandparentOverrides.map((e) => - renderSimple(e, ast, r.template, sink, - parent: r, - getters: _invisibleGetters['CommentReferable'])); + renderSimple( + c.referenceGrandparentOverrides, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'referenceParents': Property( @@ -4489,11 +4515,11 @@ class _Renderer_Extension extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.allModelElements == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.allModelElements.map((e) => _render_ModelElement( - e, ast, r.template, sink, - parent: r)); + renderSimple(c.allModelElements, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); }, ), 'alwaysApplies': Property( @@ -4509,10 +4535,11 @@ class _Renderer_Extension extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.declaredFields == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.declaredFields.map((e) => - _render_Field(e, ast, r.template, sink, parent: r)); + renderSimple(c.declaredFields, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); }, ), 'declaredMethods': Property( @@ -4521,10 +4548,25 @@ class _Renderer_Extension extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.declaredMethods == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.declaredMethods.map((e) => - _render_Method(e, ast, r.template, sink, parent: r)); + renderSimple(c.declaredMethods, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); + }, + ), + 'element': Property( + getValue: (CT_ c) => c.element, + renderVariable: (CT_ c, Property self, + List remainingNames) => + self.renderSimpleVariable( + c, remainingNames, 'ExtensionElement'), + isNullValue: (CT_ c) => c.element == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + renderSimple(c.element, ast, r.template, sink, + parent: r, + getters: _invisibleGetters['ExtensionElement']); }, ), 'enclosingElement': Property( @@ -4588,25 +4630,6 @@ class _Renderer_Extension extends RendererBase { parent: r); }, ), - 'href': Property( - getValue: (CT_ c) => c.href, - renderVariable: - (CT_ c, Property self, List remainingNames) { - if (remainingNames.isEmpty) { - return self.getValue(c).toString(); - } - var name = remainingNames.first; - var nextProperty = - _Renderer_String.propertyMap().getValue(name); - return nextProperty.renderVariable(self.getValue(c), - nextProperty, [...remainingNames.skip(1)]); - }, - isNullValue: (CT_ c) => c.href == null, - renderValue: (CT_ c, RendererBase r, - List ast, StringSink sink) { - _render_String(c.href, ast, r.template, sink, parent: r); - }, - ), 'kind': Property( getValue: (CT_ c) => c.kind, renderVariable: @@ -4735,10 +4758,13 @@ class _Renderer_ExtensionTarget extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => + c.potentiallyApplicableExtensions == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.potentiallyApplicableExtensions.map((e) => - _render_Extension(e, ast, r.template, sink, parent: r)); + renderSimple(c.potentiallyApplicableExtensions, ast, + r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'potentiallyApplicableExtensionsSorted': Property( @@ -5463,6 +5489,26 @@ class _Renderer_Field extends RendererBase { _render_String(c.kind, ast, r.template, sink, parent: r); }, ), + 'library': Property( + getValue: (CT_ c) => c.library, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Library.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.library == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Library(c.library, ast, r.template, sink, + parent: r); + }, + ), 'overriddenElement': Property( getValue: (CT_ c) => c.overriddenElement, renderVariable: @@ -5483,6 +5529,26 @@ class _Renderer_Field extends RendererBase { parent: r, getters: _invisibleGetters['Inheritable']); }, ), + 'package': Property( + getValue: (CT_ c) => c.package, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Package.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.package == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Package(c.package, ast, r.template, sink, + parent: r); + }, + ), 'setter': Property( getValue: (CT_ c) => c.setter, renderVariable: @@ -6500,10 +6566,11 @@ class _Renderer_InheritingContainer extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.allFields == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.allFields.map((e) => - _render_Field(e, ast, r.template, sink, parent: r)); + renderSimple(c.allFields, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); }, ), 'allModelElements': Property( @@ -6512,11 +6579,11 @@ class _Renderer_InheritingContainer extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.allModelElements == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.allModelElements.map((e) => _render_ModelElement( - e, ast, r.template, sink, - parent: r)); + renderSimple(c.allModelElements, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); }, ), 'constantFields': Property( @@ -6672,25 +6739,6 @@ class _Renderer_InheritingContainer extends RendererBase { self.renderSimpleVariable(c, remainingNames, 'bool'), getBool: (CT_ c) => c.hasPublicSuperChainReversed == true, ), - 'href': Property( - getValue: (CT_ c) => c.href, - renderVariable: - (CT_ c, Property self, List remainingNames) { - if (remainingNames.isEmpty) { - return self.getValue(c).toString(); - } - var name = remainingNames.first; - var nextProperty = - _Renderer_String.propertyMap().getValue(name); - return nextProperty.renderVariable(self.getValue(c), - nextProperty, [...remainingNames.skip(1)]); - }, - isNullValue: (CT_ c) => c.href == null, - renderValue: (CT_ c, RendererBase r, - List ast, StringSink sink) { - _render_String(c.href, ast, r.template, sink, parent: r); - }, - ), 'inheritanceChain': Property( getValue: (CT_ c) => c.inheritanceChain, renderVariable: (CT_ c, Property self, @@ -6722,10 +6770,11 @@ class _Renderer_InheritingContainer extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.inheritedMethods == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.inheritedMethods.map((e) => - _render_Method(e, ast, r.template, sink, parent: r)); + renderSimple(c.inheritedMethods, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'inheritedOperators': Property( @@ -6734,10 +6783,11 @@ class _Renderer_InheritingContainer extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.inheritedOperators == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.inheritedOperators.map((e) => - _render_Operator(e, ast, r.template, sink, parent: r)); + renderSimple(c.inheritedOperators, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'instanceFields': Property( @@ -9225,12 +9275,11 @@ class _Renderer_Mixin extends RendererBase { List remainingNames) => self.renderSimpleVariable(c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.superclassConstraints == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.superclassConstraints.map((e) => - _render_ParameterizedElementType( - e, ast, r.template, sink, - parent: r)); + renderSimple(c.superclassConstraints, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), }); @@ -9404,10 +9453,11 @@ class _Renderer_ModelElement extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'List'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.allParameters == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.allParameters.map((e) => - _render_Parameter(e, ast, r.template, sink, parent: r)); + renderSimple(c.allParameters, ast, r.template, sink, + parent: r, getters: _invisibleGetters['List']); }, ), 'annotations': Property( @@ -9633,10 +9683,11 @@ class _Renderer_ModelElement extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Set'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.exportedInLibraries == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.exportedInLibraries.map((e) => - _render_Library(e, ast, r.template, sink, parent: r)); + renderSimple(c.exportedInLibraries, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Set']); }, ), 'extendedDocLink': Property( @@ -10570,6 +10621,26 @@ class _Renderer_ModelFunctionTyped extends RendererBase { parent: r); }, ), + 'package': Property( + getValue: (CT_ c) => c.package, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Package.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.package == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Package(c.package, ast, r.template, sink, + parent: r); + }, + ), 'referenceChildren': Property( getValue: (CT_ c) => c.referenceChildren, renderVariable: (CT_ c, Property self, @@ -10698,10 +10769,11 @@ class _Renderer_Nameable extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Set'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.namePieces == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.namePieces.map((e) => - _render_String(e, ast, r.template, sink, parent: r)); + renderSimple(c.namePieces, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Set']); }, ), }); @@ -13309,11 +13381,11 @@ class _Renderer_TopLevelContainer extends RendererBase { List remainingNames) => self.renderSimpleVariable( c, remainingNames, 'Iterable'), - renderIterable: (CT_ c, RendererBase r, + isNullValue: (CT_ c) => c.functions == null, + renderValue: (CT_ c, RendererBase r, List ast, StringSink sink) { - return c.functions.map((e) => _render_ModelFunction( - e, ast, r.template, sink, - parent: r)); + renderSimple(c.functions, ast, r.template, sink, + parent: r, getters: _invisibleGetters['Iterable']); }, ), 'hasPublicClasses': Property( @@ -14063,6 +14135,46 @@ class _Renderer_TopLevelVariable extends RendererBase { _render_String(c.kind, ast, r.template, sink, parent: r); }, ), + 'library': Property( + getValue: (CT_ c) => c.library, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Library.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.library == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Library(c.library, ast, r.template, sink, + parent: r); + }, + ), + 'package': Property( + getValue: (CT_ c) => c.package, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Package.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.package == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Package(c.package, ast, r.template, sink, + parent: r); + }, + ), 'referenceParents': Property( getValue: (CT_ c) => c.referenceParents, renderVariable: (CT_ c, Property self, @@ -14749,6 +14861,26 @@ class _Renderer_Typedef extends RendererBase { _render_String(c.kind, ast, r.template, sink, parent: r); }, ), + 'library': Property( + getValue: (CT_ c) => c.library, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Library.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.library == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Library(c.library, ast, r.template, sink, + parent: r); + }, + ), 'linkedGenericParameters': Property( getValue: (CT_ c) => c.linkedGenericParameters, renderVariable: @@ -14810,6 +14942,26 @@ class _Renderer_Typedef extends RendererBase { parent: r); }, ), + 'package': Property( + getValue: (CT_ c) => c.package, + renderVariable: + (CT_ c, Property self, List remainingNames) { + if (remainingNames.isEmpty) { + return self.getValue(c).toString(); + } + var name = remainingNames.first; + var nextProperty = + _Renderer_Package.propertyMap().getValue(name); + return nextProperty.renderVariable(self.getValue(c), + nextProperty, [...remainingNames.skip(1)]); + }, + isNullValue: (CT_ c) => c.package == null, + renderValue: (CT_ c, RendererBase r, + List ast, StringSink sink) { + _render_Package(c.package, ast, r.template, sink, + parent: r); + }, + ), 'referenceChildren': Property( getValue: (CT_ c) => c.referenceChildren, renderVariable: (CT_ c, Property self, @@ -15465,6 +15617,15 @@ const _invisibleGetters = { 'staticType', 'unParenthesized' }, + 'ExtensionElement': { + 'hashCode', + 'runtimeType', + 'accessors', + 'enclosingElement', + 'extendedType', + 'fields', + 'methods' + }, 'Feature': { 'hashCode', 'runtimeType', @@ -15514,6 +15675,7 @@ const _invisibleGetters = { }, 'GetterSetterCombo': { 'enclosingElement', + 'documentationFrom', 'getter', 'setter', 'annotations', @@ -15528,7 +15690,6 @@ const _invisibleGetters = { 'hasPublicGetter', 'hasPublicSetter', 'isPublic', - 'documentationFrom', 'hasAccessorsWithDocs', 'getterSetterBothAvailable', 'oneLineDoc', @@ -15554,14 +15715,14 @@ const _invisibleGetters = { }, 'HashMap': {'hashCode', 'runtimeType'}, 'Inheritable': { + 'overriddenDepth', 'isInherited', 'isCovariant', 'features', 'canonicalLibrary', 'inheritance', 'overriddenElement', - 'isOverride', - 'overriddenDepth' + 'isOverride' }, 'InheritanceManager3': {'hashCode', 'runtimeType'}, 'Iterable': { @@ -15608,6 +15769,7 @@ const _invisibleGetters = { 'typeSystem', 'units' }, + 'List': {'hashCode', 'runtimeType', 'length', 'reversed'}, 'Locatable': { 'hashCode', 'runtimeType', @@ -15702,6 +15864,8 @@ const _invisibleGetters = { 'packageMap', 'sdk', 'allLibrariesAdded', + 'packageWarningCounter', + 'localPublicLibraries', 'name', 'implementors', 'documentedExtensions', @@ -15712,7 +15876,6 @@ const _invisibleGetters = { 'packageGraph', 'resourceProvider', 'sdkLibrarySources', - 'packageWarningCounter', 'packages', 'publicPackages', 'localPackages', @@ -15722,7 +15885,6 @@ const _invisibleGetters = { 'libraries', 'publicLibraries', 'localLibraries', - 'localPublicLibraries', 'inheritThrough', 'invisibleAnnotations', 'allModelElements', @@ -15855,6 +16017,17 @@ const _invisibleGetters = { 'path', 'shortName' }, + 'Set': { + 'hashCode', + 'runtimeType', + 'iterator', + 'length', + 'isEmpty', + 'isNotEmpty', + 'first', + 'last', + 'single' + }, 'TemplateOptions': { 'hashCode', 'runtimeType', diff --git a/lib/src/model/categorization.dart b/lib/src/model/categorization.dart index 9cd157b5c4..2ecea4edf7 100644 --- a/lib/src/model/categorization.dart +++ b/lib/src/model/categorization.dart @@ -96,19 +96,19 @@ abstract class Categorization implements ModelElement { Iterable? _categories; - Iterable? get categories { + Iterable get categories { _categories ??= categoryNames! .map((n) => package?.nameToCategory[n]) .where((c) => c != null) .toList() ..sort(); - return _categories; + return _categories!; } @override - Iterable? get displayedCategories { + Iterable get displayedCategories { if (config.showUndocumentedCategories) return categories; - return categories!.where((c) => c!.isDocumented); + return categories.where((c) => c!.isDocumented); } bool? _hasCategorization; diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index 245edab282..498e965d89 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -22,7 +22,6 @@ import 'package:dartdoc/src/model/model.dart'; import 'package:dartdoc/src/package_meta.dart' show PackageMeta; import 'package:dartdoc/src/quiver.dart' as quiver; import 'package:dartdoc/src/warnings.dart'; -import 'package:meta/meta.dart'; /// Find all hashable children of a given element that are defined in the /// [LibraryElement] given at initialization. @@ -210,20 +209,6 @@ class Library extends ModelElement with Categorization, TopLevelContainer { late final Iterable constants = _variables.where((v) => v.isConst).toList(growable: false); - /// Returns all libraries directly imported or exported by this library. - @visibleForTesting - late final Set importedExportedLibrariesLocal = () { - var _importedExportedLibraries = {}; - for (var l in { - ...element.importedLibraries, - ...element.exportedLibraries - }) { - var lib = modelBuilder.fromElement(l) as Library; - _importedExportedLibraries.add(lib); - } - return _importedExportedLibraries; - }(); - /// Map of import prefixes ('import "foo" as prefix;') to [Library]. late final Map> prefixToLibrary = () { var prefixToLibrary = >{}; diff --git a/lib/src/model/model_element.dart b/lib/src/model/model_element.dart index e7e66ead6a..ccf9a04b5d 100644 --- a/lib/src/model/model_element.dart +++ b/lib/src/model/model_element.dart @@ -379,7 +379,7 @@ abstract class ModelElement extends Canonicalization bool get hasCategoryNames => false; // Stub for mustache. - Iterable? get displayedCategories => []; + Iterable get displayedCategories => []; Set? get exportedInLibraries { return library!.packageGraph.libraryElementReexportedBy[element!.library!]; diff --git a/test/end2end/model_test.dart b/test/end2end/model_test.dart index 7ce9c8dc34..8a41f48592 100644 --- a/test/end2end/model_test.dart +++ b/test/end2end/model_test.dart @@ -9,6 +9,7 @@ library dartdoc.model_test; import 'dart:io'; +import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/source/line_info.dart'; import 'package:async/async.dart'; @@ -1048,10 +1049,19 @@ void main() { }); test('can import other libraries with unusual URIs', () { - expect( - fakeLibrary.importedExportedLibrariesLocal - .where((l) => l.name == 'import_unusual'), - isNotEmpty); + final Set fakeLibraryImportedExported = () { + var _importedExportedLibraries = {}; + for (var l in { + ...fakeLibrary.element.importedLibraries, + ...fakeLibrary.element.exportedLibraries + }) { + var lib = packageGraph.modelBuilder.fromElement(l) as Library; + _importedExportedLibraries.add(lib); + } + return _importedExportedLibraries; + }(); + expect(fakeLibraryImportedExported.any((l) => l.name == 'import_unusual'), + isTrue); }); test('@canonicalFor directive works', () { From 00ff7902b60681dedd009eb77e9c433439f68011 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 21 Oct 2021 12:47:40 -0700 Subject: [PATCH 19/21] forgot to remove a fixme --- lib/src/model/package_graph.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/src/model/package_graph.dart b/lib/src/model/package_graph.dart index dd3c695feb..f289a89fe5 100644 --- a/lib/src/model/package_graph.dart +++ b/lib/src/model/package_graph.dart @@ -747,7 +747,6 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder { /// This doesn't know anything about [PackageGraph.inheritThrough] and probably /// shouldn't, so using it with [Inheritable]s without special casing is /// not advised. - // FIXME(nnbd): remove null check ignore in model_utils after migration ModelElement? findCanonicalModelElementFor(Element? e, {Container? preferredClass}) { assert(allLibrariesAdded); From 420e1fdb2924956de57dfb05a5a2430858c26fea Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 21 Oct 2021 13:02:55 -0700 Subject: [PATCH 20/21] Work around strange super-not-allowed error in stable --- lib/src/model/getter_setter_combo.dart | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/src/model/getter_setter_combo.dart b/lib/src/model/getter_setter_combo.dart index f7a38f3ad2..1ac12f0d03 100644 --- a/lib/src/model/getter_setter_combo.dart +++ b/lib/src/model/getter_setter_combo.dart @@ -111,6 +111,9 @@ mixin GetterSetterCombo on ModelElement { @override bool get isPublic => hasPublicGetter || hasPublicSetter; + List get _superDocumentationFrom => + super.documentationFrom; + @override late final List documentationFrom = () { var toReturn = []; @@ -121,7 +124,10 @@ mixin GetterSetterCombo on ModelElement { } if (toReturn.isEmpty || toReturn.every((e) => e.documentationComment == '')) { - toReturn = super.documentationFrom; + // TODO(jcollins-g): Remove indirection once analyzer realizes super is + // allowed from from inside a late final variable's anonymous closure call + // (sdk >= 2.15.0-239.0.dev, but possibly earlier dev versions too). + toReturn = _superDocumentationFrom; } return toReturn; }(); From 6e1360f8827338e7dccb0cb6f0650841c047a04c Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Tue, 26 Oct 2021 11:49:35 -0700 Subject: [PATCH 21/21] review comments --- lib/src/model/accessor.dart | 64 ++++++++++++++++-------------------- lib/src/model/extension.dart | 27 ++++++++------- lib/src/model/library.dart | 4 +-- 3 files changed, 44 insertions(+), 51 deletions(-) diff --git a/lib/src/model/accessor.dart b/lib/src/model/accessor.dart index ebf78c242b..2364570c82 100644 --- a/lib/src/model/accessor.dart +++ b/lib/src/model/accessor.dart @@ -16,7 +16,7 @@ import 'package:dartdoc/src/warnings.dart'; /// Getters and setters. class Accessor extends ModelElement implements EnclosedElement { - /// The combo ([Field] or [TopLevelVariable] containing this accessor. + /// The combo ([Field] or [TopLevelVariable]) containing this accessor. /// Initialized by the combo's constructor. late final GetterSetterCombo enclosingCombo; @@ -27,8 +27,8 @@ class Accessor extends ModelElement implements EnclosedElement { @override CharacterLocation? get characterLocation { - if (element!.nameOffset < 0) { - assert(element!.isSynthetic, 'Invalid offset for non-synthetic element'); + if (element.nameOffset < 0) { + assert(element.isSynthetic, 'Invalid offset for non-synthetic element'); // TODO(jcollins-g): switch to [element.nonSynthetic] after analyzer 1.8 return enclosingCombo.characterLocation; } @@ -36,32 +36,24 @@ class Accessor extends ModelElement implements EnclosedElement { } @override - PropertyAccessorElement? get element => - super.element as PropertyAccessorElement?; + PropertyAccessorElement get element => + super.element as PropertyAccessorElement; @override ExecutableMember? get originalMember => super.originalMember as ExecutableMember?; - Callable? _modelType; - Callable get modelType => (_modelType ??= modelBuilder.typeFrom( - (originalMember ?? element)!.type, library!) as Callable?)!; + late final Callable modelType = modelBuilder.typeFrom( + (originalMember ?? element).type, library) as Callable; - bool get isSynthetic => element!.isSynthetic; + bool get isSynthetic => element.isSynthetic; SourceCodeRenderer get _sourceCodeRenderer => packageGraph.rendererFactory.sourceCodeRenderer; - GetterSetterCombo? _definingCombo; // The [enclosingCombo] where this element was defined. - GetterSetterCombo? get definingCombo { - if (_definingCombo == null) { - var variable = element!.variable; - _definingCombo = modelBuilder.fromElement(variable) as GetterSetterCombo?; - assert(_definingCombo != null, 'Unable to find defining combo'); - } - return _definingCombo; - } + late final GetterSetterCombo definingCombo = + modelBuilder.fromElement(element.variable) as GetterSetterCombo; String? _sourceCode; @@ -70,7 +62,7 @@ class Accessor extends ModelElement implements EnclosedElement { if (_sourceCode == null) { if (isSynthetic) { _sourceCode = _sourceCodeRenderer.renderSourceCode( - packageGraph.getModelNodeFor(definingCombo!.element)!.sourceCode!); + packageGraph.getModelNodeFor(definingCombo.element)!.sourceCode!); } else { _sourceCode = super.sourceCode; } @@ -95,7 +87,7 @@ class Accessor extends ModelElement implements EnclosedElement { /// Value here is not useful if [isSynthetic] is false. late final String _syntheticDocumentationComment = () { if (_hasSyntheticDocumentationComment) { - return definingCombo!.documentationComment; + return definingCombo.documentationComment; } return ''; }(); @@ -105,16 +97,16 @@ class Accessor extends ModelElement implements EnclosedElement { /// for a synthetic accessor just in case it is inherited somewhere /// down the line due to split inheritance. bool get _hasSyntheticDocumentationComment => - (isGetter || definingCombo!.hasNodoc! || _comboDocsAreIndependent()) && - definingCombo!.hasDocumentationComment; + (isGetter || definingCombo.hasNodoc! || _comboDocsAreIndependent()) && + definingCombo.hasDocumentationComment; // If we're a setter, and a getter exists, do not add synthetic // documentation if the combo's documentation is actually derived // from that getter. bool _comboDocsAreIndependent() { - if (isSetter && definingCombo!.hasGetter) { - if (definingCombo!.getter!.isSynthetic || - !definingCombo!.documentationFrom.contains(this)) { + if (isSetter && definingCombo.hasGetter) { + if (definingCombo.getter!.isSynthetic || + !definingCombo.documentationFrom.contains(this)) { return true; } } @@ -124,7 +116,7 @@ class Accessor extends ModelElement implements EnclosedElement { @override bool get hasDocumentationComment => isSynthetic ? _hasSyntheticDocumentationComment - : element!.documentationComment != null; + : element.documentationComment != null; @override void warn( @@ -141,12 +133,12 @@ class Accessor extends ModelElement implements EnclosedElement { @override ModelElement? get enclosingElement { - if (element!.enclosingElement is CompilationUnitElement) { + if (element.enclosingElement is CompilationUnitElement) { return modelBuilder - .fromElement(element!.enclosingElement.enclosingElement!); + .fromElement(element.enclosingElement.enclosingElement!); } - return modelBuilder.from(element!.enclosingElement, library!); + return modelBuilder.from(element.enclosingElement, library); } @override @@ -160,9 +152,9 @@ class Accessor extends ModelElement implements EnclosedElement { return enclosingCombo.href; } - bool get isGetter => element!.isGetter; + bool get isGetter => element.isGetter; - bool get isSetter => element!.isSetter; + bool get isSetter => element.isSetter; @override String get kind => 'accessor'; @@ -175,6 +167,9 @@ class Accessor extends ModelElement implements EnclosedElement { return _namePart; } + @override + Library get library => super.library!; + @override /// Accessors should never be participating directly in comment reference @@ -239,12 +234,11 @@ class ContainerAccessor extends Accessor with ContainerMember, Inheritable { assert(packageGraph.allLibrariesAdded); if (!_overriddenElementIsSet) { _overriddenElementIsSet = true; - var parent = element!.enclosingElement; + var parent = element.enclosingElement; if (parent is ClassElement) { for (var t in parent.allSupertypes) { - Element? accessor = isGetter - ? t.getGetter(element!.name) - : t.getSetter(element!.name); + Element? accessor = + isGetter ? t.getGetter(element.name) : t.getSetter(element.name); if (accessor != null) { accessor = accessor.declaration; InheritingContainer parentContainer = diff --git a/lib/src/model/extension.dart b/lib/src/model/extension.dart index b424454d4c..1a031e3cdd 100644 --- a/lib/src/model/extension.dart +++ b/lib/src/model/extension.dart @@ -11,33 +11,32 @@ import 'package:dartdoc/src/quiver.dart' as quiver; /// Extension methods class Extension extends Container implements EnclosedElement { - ElementType? extendedType; + late final ElementType extendedType = + modelBuilder.typeFrom(element.extendedType, library); Extension( ExtensionElement element, Library library, PackageGraph packageGraph) - : super(element, library, packageGraph) { - extendedType = modelBuilder.typeFrom(element.extendedType, library); - } + : super(element, library, packageGraph); /// Detect if this extension applies to every object. bool get alwaysApplies => - extendedType!.instantiatedType.isDynamic || - extendedType!.instantiatedType.isVoid || - extendedType!.instantiatedType.isDartCoreObject; + extendedType.instantiatedType.isDynamic || + extendedType.instantiatedType.isVoid || + extendedType.instantiatedType.isDartCoreObject; bool couldApplyTo(T c) => _couldApplyTo(c.modelType as DefinedElementType); /// Return true if this extension could apply to [t]. bool _couldApplyTo(DefinedElementType t) { - if (extendedType!.instantiatedType.isDynamic || - extendedType!.instantiatedType.isVoid) { + if (extendedType.instantiatedType.isDynamic || + extendedType.instantiatedType.isVoid) { return true; } - return t.instantiatedType == extendedType!.instantiatedType || - (t.instantiatedType.element == extendedType!.instantiatedType.element && - extendedType!.isSubtypeOf(t)) || - extendedType!.isBoundSupertypeTo(t); + return t.instantiatedType == extendedType.instantiatedType || + (t.instantiatedType.element == extendedType.instantiatedType.element && + extendedType.isSubtypeOf(t)) || + extendedType.isBoundSupertypeTo(t); } /// Returns the library that encloses this element. @@ -112,7 +111,7 @@ class Extension extends Container implements EnclosedElement { @override Map get referenceChildren { return _referenceChildren ??= { - ...extendedType!.referenceChildren, + ...extendedType.referenceChildren, // Override extendedType entries with local items. ...super.referenceChildren, }; diff --git a/lib/src/model/library.dart b/lib/src/model/library.dart index 498e965d89..9355e03c61 100644 --- a/lib/src/model/library.dart +++ b/lib/src/model/library.dart @@ -142,10 +142,10 @@ class Library extends ModelElement with Categorization, TopLevelContainer { Accessor? getter; Accessor? setter; if (e.hasGetter) { - getter = modelBuilder.fromElement(e.getter!.element!) as Accessor; + getter = modelBuilder.fromElement(e.getter!.element) as Accessor; } if (e.hasSetter) { - setter = modelBuilder.fromElement(e.setter!.element!) as Accessor; + setter = modelBuilder.fromElement(e.setter!.element) as Accessor; } return modelBuilder .fromPropertyInducingElement(e.element!,