Version 3.15.0-218.0.dev Merge 1c131fde935f4c9ed67b1472d97e97e3af0b0f08 into dev
diff --git a/DEPS b/DEPS index 7f8967f..edccdfb 100644 --- a/DEPS +++ b/DEPS
@@ -83,7 +83,7 @@ "gcloud_version": "version:3@584.0.0.chromium.4", # https://chrome-infra-packages.appspot.com/p/fuchsia/third_party/clang - "clang_version": "git_revision:32e6b5082d000a0da4a5af148d63f30d29e95a18", + "clang_version": "git_revision:8817a66ccf36c5585c36b424ee3eaf3f2bad6848", # https://chrome-infra-packages.appspot.com/p/gn/gn "gn_version": "git_revision:f6065658b2e06b07853a90b9503013357eb2288e", @@ -134,23 +134,23 @@ # 'tools/rev_sdk_deps.dart' will rev pkg dependencies to their latest; put an # EOL comment after a dependency to instead pin at the current revision. "core_rev": "fbb4f2b65905d1d1787d0b9357b96e8e63d07d22", - "dartdoc_rev": "4c55e91c953474dc6651f375d8eefff24dc0f307", - "ecosystem_rev": "089511113298a25fed9c0b9d05bda0e8a0bb18bf", + "dartdoc_rev": "9711249d2a1e2044a4ef06bca830e6c141fd4541", + "ecosystem_rev": "d339c861545b493978e3f1710085e8edb603ab0d", "flute_rev": "b84119fba67016a80c3eb80765762bcc4d0d0b8d", "http_rev": "a4d1d41a07be04f29799e8f81b8188f8925ab160", "i18n_rev": "bde721fe67be7cab4054227db858aac220bec305", "leak_tracker_rev": "f5620600a5ce1c44f65ddaa02001e200b096e14c", # rolled manually "material_color_utilities_rev": "799b6ba2f3f1c28c67cc7e0b4f18e0c7d7f3c03e", - "native_rev": "2c63bb68a06658c8116510834f7dde38454522ec", + "native_rev": "f4073fdd93daa2ca0c8e6222ca77d5af38ca1f24", "protobuf_rev": "19191c8c5881d4a63db804bbed26fa1dcdd17ed0", "pub_rev": "9df389a76385f82c1165c7cf93b78807b5ea8890", # rolled manually "shelf_rev": "ec6548800a39a09755ef2834a2bbb008840b9a4d", - "sync_http_rev": "6666fff944221891182e1f80bf56569338164d72", + "sync_http_rev": "6d0b77ff981ae4a570fe70d26afb866f29181471", "tar_rev": "e7fc9cc69cad53b2cd35002d80b2ac71bd1f0299", - "test_rev": "96d87a1b229f794fee050ef2e2ef688963d0bd3a", - "tools_rev": "b4eaf6e10f4ac9744c1646b97ea0b7a6050e2526", + "test_rev": "4697f3491ab7582d12a3978def49ef0707112393", + "tools_rev": "1ccf1008f67adcb2d602af0d06b6ad2fa59a08cd", "vector_math_rev": "cf3b5db7340d317dd3489e5a35434b408020a852", - "web_rev": "7a31fbcee73fed29846f544ce4d592017b88078e", + "web_rev": "c68b6276c05e77af3e5598b4aaac89c864e75c9d", "webdriver_rev": "8e5c611ea242efdc9f597a8a37c38a9c586120ee", "webkit_inspection_protocol_rev": "2c255f2a153239d009385774f12eb57e1c3056eb",
diff --git a/pkg/analysis_server/lib/src/analytics/analytics_manager.dart b/pkg/analysis_server/lib/src/analytics/analytics_manager.dart index eb7b9b8..65c503c 100644 --- a/pkg/analysis_server/lib/src/analytics/analytics_manager.dart +++ b/pkg/analysis_server/lib/src/analytics/analytics_manager.dart
@@ -332,6 +332,35 @@ ); } + /// Sends an [Event.migrateRun] event for a `dart migrate` request. + void sendMigrationRun({ + required String? fromSdkVersion, + required String? toSdkVersion, + required bool targetSdk, + required bool prepare, + required bool bump, + required bool cleanup, + required bool apply, + required int durationMs, + required int? cleanupCheckDurationMs, + required int migrateSessionId, + }) { + analytics.send( + Event.migrateRun( + fromSdkVersion: fromSdkVersion, + toSdkVersion: toSdkVersion, + targetSdk: targetSdk, + prepare: prepare, + bump: bump, + cleanup: cleanup, + apply: apply, + durationMs: durationMs, + cleanupCheckDurationMs: cleanupCheckDurationMs, + migrateSessionId: migrateSessionId, + ), + ); + } + @visibleForTesting Future<void> sendPeriodicData() => _sendPeriodicData();
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/migration/migration_runner.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/migration/migration_runner.dart index b567c07..e1c3128 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/migration/migration_runner.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/migration/migration_runner.dart
@@ -56,8 +56,18 @@ final ProgressReporter _progressReporter = progressReporter ?? ProgressReporter.noop; + /// The time this migration started, in milliseconds since the epoch, which + /// is sent with each of its analytics events to group them. + final int _migrateSessionId = DateTime.now().millisecondsSinceEpoch; + this : super(server); + /// Whether any package was last raised to an SDK version that has clean up + /// fixes to look for. + bool get _hasCleanUpToCheck => _lastBumpRounds.values.any( + (round) => cleanUpLintsRegistry[round.toSdkVersion]?.isNotEmpty ?? false, + ); + /// Runs the migration runner. /// /// The migration is executed based on the provided [steps]: @@ -273,6 +283,7 @@ Future<ErrorOr<List<SourceFileEdit>>> _computeMigrationEdits( List<MigrationStep> steps, ) async { + var stopwatch = Stopwatch()..start(); var schedule = MigrationSchedule.plan( pubspecs: pubspecTargets, summaryBuilder: summaryBuilder, @@ -280,6 +291,7 @@ steps: steps, ); + int? cleanupCheckDurationMs; try { for ( var round = schedule.nextRound(); @@ -289,14 +301,24 @@ await _runRound(schedule, round, steps); schedule.completeRound(round); } - if (!steps.runCleanup) { + // Without any clean up fixes to look for, there's no check to run, so no + // duration is sent rather than one of 0. + if (!steps.runCleanup && _hasCleanUpToCheck) { + var cleanupCheckStopwatch = Stopwatch()..start(); await _recordAvailableCleanUp(); + cleanupCheckDurationMs = cleanupCheckStopwatch.elapsedMilliseconds; } } finally { // Revert all temporary overlays back to their original state. await revertOverlays(); } + _sendRunMetrics( + schedule, + steps, + durationMs: stopwatch.elapsedMilliseconds, + cleanupCheckDurationMs: cleanupCheckDurationMs, + ); return success(_fileEdits); } @@ -482,6 +504,49 @@ } } + /// Sends one run event for this migration, which runs [steps] as planned by + /// [schedule]. + /// + /// [durationMs] is the time from when the migration started, after any + /// analysis in progress finished, until the edits are computed and the + /// temporary overlays are reverted. + /// + /// [cleanupCheckDurationMs] is the time spent looking for the clean up fixes + /// that the summary lists without applying them. It's `null` when the user + /// opted in to the clean up step, which applies them instead, or when there + /// were no clean up fixes to look for. + void _sendRunMetrics( + MigrationSchedule schedule, + List<MigrationStep> steps, { + required int durationMs, + required int? cleanupCheckDurationMs, + }) { + // The event is sent even when every package is skipped, so a request with + // nothing to migrate is still counted. The versions come from the plan + // rather than from a round, since no round runs in that case. + var fromSdkVersion = schedule.lowestSupportedSdkVersion; + var toSdkVersion = targetSdk; + if (toSdkVersion == null && fromSdkVersion != null) { + // Without the prepare or bump step, packages stay at the version they're + // on. + toSdkVersion = steps.runPrepare || steps.runBump + ? nextSdkVersion(fromSdkVersion) + : fromSdkVersion; + } + server.analyticsManager.sendMigrationRun( + fromSdkVersion: fromSdkVersion?.majorMinor, + toSdkVersion: toSdkVersion?.majorMinor, + targetSdk: targetSdk != null, + prepare: steps.runPrepare, + bump: steps.runBump, + cleanup: steps.runCleanup, + apply: summaryBuilder.apply, + durationMs: durationMs, + cleanupCheckDurationMs: cleanupCheckDurationMs, + migrateSessionId: _migrateSessionId, + ); + } + /// Checks everything that can stop [package] from reaching [round]'s SDK /// version, before anything has been changed. /// @@ -550,3 +615,9 @@ /// The edit that raises the package's SDK constraint to the round's version. required final PubspecEdit bumpEdit, }); + +extension on Version { + /// The major and minor parts of this version, such as `3.11`, which is how + /// analytics reports SDK versions. + String get majorMinor => '$major.$minor'; +}
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/migration/migration_schedule.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/migration/migration_schedule.dart index 2d2c7ff..4bf7778 100644 --- a/pkg/analysis_server/lib/src/lsp/handlers/custom/migration/migration_schedule.dart +++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/migration/migration_schedule.dart
@@ -103,6 +103,14 @@ /// A cleanup-only migration doesn't: its single round applies fixes at the /// version each package is already on. final bool _advancesSdkVersion, + + /// The lowest supported SDK version that any requested package declares as + /// its minimum, including packages that are skipped. + /// + /// It's where the first round starts when one runs. It's `null` when no + /// package declares a minimum SDK version that migration supports, or when + /// [plan] rejects the target SDK version before it reads the packages. + final Version? lowestSupportedSdkVersion, ) { /// The migrating packages, indexed by declared package name. /// @@ -143,13 +151,14 @@ 'and ${knownSdkVersions.last}.', ); } - return MigrationSchedule._(const [], null, false); + return MigrationSchedule._(const [], null, false, null); } } var advancesSdkVersion = steps.runPrepare || steps.runBump; var packages = <MigratingPackage>[]; + Version? lowestSupportedVersion; for (var pubspec in pubspecs) { var summary = summaryBuilder.forPackage(pubspec); @@ -174,6 +183,10 @@ ); continue; } + if (lowestSupportedVersion == null || + supportedVersion < lowestSupportedVersion) { + lowestSupportedVersion = supportedVersion; + } if (finalSdkVersion != null) { if (supportedVersion >= finalSdkVersion) { @@ -200,6 +213,7 @@ // Without a target, every package runs exactly one round. advancesSdkVersion ? finalSdkVersion : null, advancesSdkVersion, + lowestSupportedVersion, ); }
diff --git a/pkg/analysis_server/test/lsp/migrate_test.dart b/pkg/analysis_server/test/lsp/migrate_test.dart index 7a7bc96..d2bfd80 100644 --- a/pkg/analysis_server/test/lsp/migrate_test.dart +++ b/pkg/analysis_server/test/lsp/migrate_test.dart
@@ -11,10 +11,13 @@ import 'package:analysis_server/src/utilities/pubspec.dart'; import 'package:analyzer/src/context/packages.dart'; import 'package:analyzer_testing/package_config_file_builder.dart'; +import 'package:http/http.dart' as http; import 'package:linter/src/rules.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:test/test.dart'; import 'package:test_reflective_loader/test_reflective_loader.dart'; +import 'package:unified_analytics/src/enums.dart'; +import 'package:unified_analytics/unified_analytics.dart'; import 'package:yaml/yaml.dart'; import '../tool/lsp_spec/matchers.dart'; @@ -22,6 +25,7 @@ void main() { defineReflectiveSuite(() { + defineReflectiveTests(MigrateAnalyticsTest); defineReflectiveTests(MigrateDependencyConflictTest); defineReflectiveTests(MigrateLockstepTest); defineReflectiveTests(MigrateMultiVersionTest); @@ -126,6 +130,352 @@ } @reflectiveTest +class MigrateAnalyticsTest extends AbstractMigrateTest { + final _analytics = _RecordingAnalytics(); + + @override + Analytics get analytics => _analytics; + + /// The data of every migrate run event sent so far. + Iterable<Map<String, Object?>> get _migrateRunEventData => _analytics.events + .where((event) => event.eventName == DashEvent.migrateRun) + .map((event) => event.eventData); + + Future<void> test_bumped_multipleVersions() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^3.11.0' +'''); + newFile(mainFilePath, 'void m(int x) {}\n'); + await initialize(); + + await _assertMigrationResult(targetSdk: '3.13.0'); + + _expectRunEvent({ + 'fromSdkVersion': '3.11', + 'toSdkVersion': '3.13', + 'targetSdk': true, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + 'cleanupCheckDurationMs': isNonNegative, + }); + } + + /// A package raised to an SDK version without clean up fixes has nothing to + /// look for, so no check duration is sent. + Future<void> test_cleanupCheck_noCleanUpFixes() async { + // 3.14 registers no clean up fixes. + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^3.13.0' +'''); + newFile(mainFilePath, 'void m(int x) {}\n'); + await initialize(); + + await _assertMigrationResult(); + + _expectRunEvent({ + 'fromSdkVersion': '3.13', + 'toSdkVersion': '3.14', + 'targetSdk': false, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + }); + } + + Future<void> test_failed() async { + // Setup writes a package config for `test`, not `test_project`, so the + // bump can't update it. + newFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^3.12.0' +'''); + newFile(mainFilePath, 'void m(int x) {}\n'); + await initialize(); + + await _assertMigrationResult(expectedSummary: contains(': Failed')); + + _expectRunEvent({ + 'fromSdkVersion': '3.12', + 'toSdkVersion': '3.13', + 'targetSdk': false, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + }); + } + + Future<void> test_flags_bumpAndCleanup() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^3.12.0' +'''); + newFile(mainFilePath, 'void m(int x) {}\n'); + await initialize(); + + await _assertMigrationResult( + steps: [MigrationStep.Bump, MigrationStep.Cleanup], + apply: true, + ); + + _expectRunEvent({ + 'fromSdkVersion': '3.12', + 'toSdkVersion': '3.13', + 'targetSdk': false, + 'prepare': false, + 'bump': true, + 'cleanup': true, + 'apply': true, + }); + } + + Future<void> test_flags_cleanup() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^3.12.0' +'''); + newFile(mainFilePath, 'void m(int x) {}\n'); + await initialize(); + + await _assertMigrationResult(steps: [MigrationStep.Cleanup]); + + _expectRunEvent({ + 'fromSdkVersion': '3.12', + 'toSdkVersion': '3.12', + 'targetSdk': false, + 'prepare': false, + 'bump': false, + 'cleanup': true, + 'apply': false, + }); + } + + Future<void> test_flags_prepare() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^3.12.0' +'''); + newFile(mainFilePath, 'void m(int x) {}\n'); + await initialize(); + + await _assertMigrationResult(steps: [MigrationStep.Prepare]); + + _expectRunEvent({ + 'fromSdkVersion': '3.12', + 'toSdkVersion': '3.13', + 'targetSdk': false, + 'prepare': true, + 'bump': false, + 'cleanup': false, + 'apply': false, + }); + } + + Future<void> test_fromSdkVersion_ignoresUnsupportedVersion() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^3.12.0' +'''); + var unsupportedPackagePath = convertPath('/home/unsupported_package'); + writePubspecFile(join(unsupportedPackagePath, 'pubspec.yaml'), ''' +name: unsupported_package +environment: + sdk: '^2.19.0' +'''); + await initialize(); + + await _assertMigrationResult( + uris: [projectFolderUri, toUri(unsupportedPackagePath)], + ); + + _expectRunEvent({ + 'fromSdkVersion': '3.12', + 'toSdkVersion': '3.13', + 'targetSdk': false, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + 'cleanupCheckDurationMs': isNonNegative, + }); + } + + Future<void> test_fromSdkVersion_lowestAcrossPackages() async { + // The lowest version is in the middle, so a migration that kept the first, + // the last or the highest version would report a different one. The first + // package is skipped because it's already at the latest version. + var latestVersion = knownSdkVersions.last; + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^$latestVersion' +'''); + var lowestPackagePath = convertPath('/home/lowest_package'); + writePubspecFile(join(lowestPackagePath, 'pubspec.yaml'), ''' +name: lowest_package +environment: + sdk: '^3.12.0' +'''); + var higherPackagePath = convertPath('/home/higher_package'); + writePubspecFile(join(higherPackagePath, 'pubspec.yaml'), ''' +name: higher_package +environment: + sdk: '^3.13.0' +'''); + var packageUris = [ + projectFolderUri, + toUri(lowestPackagePath), + toUri(higherPackagePath), + ]; + await initialize(workspaceFolders: packageUris); + + await _assertMigrationResult(uris: packageUris); + + _expectRunEvent({ + 'fromSdkVersion': '3.12', + 'toSdkVersion': '3.13', + 'targetSdk': false, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + 'cleanupCheckDurationMs': isNonNegative, + }); + } + + Future<void> test_skipped_latestVersion() async { + var latestVersion = knownSdkVersions.last; + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^$latestVersion' +'''); + await initialize(); + + await _assertMigrationResult(); + + _expectRunEvent({ + 'fromSdkVersion': '${latestVersion.major}.${latestVersion.minor}', + 'targetSdk': false, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + }); + } + + Future<void> test_skipped_noLowerBound() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: 'any' +'''); + await initialize(); + + await _assertMigrationResult(); + + _expectRunEvent({ + 'targetSdk': false, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + }); + } + + Future<void> test_skipped_noLowerBound_targetSdk() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: 'any' +'''); + await initialize(); + + await _assertMigrationResult(targetSdk: '3.13.0'); + + _expectRunEvent({ + 'toSdkVersion': '3.13', + 'targetSdk': true, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + }); + } + + Future<void> test_skipped_pastTarget() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^3.13.0' +'''); + await initialize(); + + await _assertMigrationResult(targetSdk: '3.12.0'); + + _expectRunEvent({ + 'fromSdkVersion': '3.13', + 'toSdkVersion': '3.12', + 'targetSdk': true, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + }); + } + + Future<void> test_skipped_unsupportedVersion() async { + writePubspecFile(pubspecFilePath, ''' +name: test_project +environment: + sdk: '^2.19.0' +'''); + await initialize(); + + await _assertMigrationResult(); + + _expectRunEvent({ + 'targetSdk': false, + 'prepare': true, + 'bump': true, + 'cleanup': false, + 'apply': false, + }); + } + + /// Expects that the migration sent one run event whose data, besides its + /// duration and session ID, is [expected]. + void _expectRunEvent(Map<String, Object> expected) { + var events = _migrateRunEventData.toList(); + expect(events, [ + { + 'durationMs': isNonNegative, + 'migrateSessionId': isA<int>(), + ...expected, + }, + ]); + if (events.single['cleanupCheckDurationMs'] case int cleanupCheckMs) { + expect( + cleanupCheckMs, + lessThanOrEqualTo(events.single['durationMs'] as int), + ); + } + } +} + +@reflectiveTest class MigrateDependencyConflictTest extends AbstractMigrateTest { Future<void> test_dart3BackwardsCompatibility() async { writePubspecFile(pubspecFilePath, ''' @@ -4149,3 +4499,14 @@ ); } } + +/// Analytics that keeps every event it's sent instead of reporting it. +class _RecordingAnalytics extends NoOpAnalytics { + final List<Event> events = []; + + @override + Future<http.Response>? send(Event event) { + events.add(event); + return null; + } +}
diff --git a/pkg/analysis_server/test/lsp/server_abstract.dart b/pkg/analysis_server/test/lsp/server_abstract.dart index 94cd808..0cc5112 100644 --- a/pkg/analysis_server/test/lsp/server_abstract.dart +++ b/pkg/analysis_server/test/lsp/server_abstract.dart
@@ -83,6 +83,10 @@ /// yet been responded to. final Set<RequestMessage> _pendingReverseRequests = {}; + /// The analytics the server reports to, which discards every event unless a + /// test overrides it. + late final Analytics analytics = NoOpAnalytics(); + @override AnalyticsManager get analyticsManager => server.analyticsManager; @@ -324,7 +328,7 @@ resourceProvider, serverOptions, DartSdkManager(sdkRoot.path), - AnalyticsManager(NoOpAnalytics()), + AnalyticsManager(analytics), CrashReportingAttachmentsBuilder.empty, sessionListener, httpClient: httpClient,
diff --git a/pkg/linter/test/rules/always_declare_return_types_test.dart b/pkg/linter/test/rules/always_declare_return_types_test.dart index b3bfb11f..5adb31c 100644 --- a/pkg/linter/test/rules/always_declare_return_types_test.dart +++ b/pkg/linter/test/rules/always_declare_return_types_test.dart
@@ -107,6 +107,14 @@ '''); } + test_getter_noReturnType() async { + await assertDiagnosticsFromMarkup(r''' +class C { + get [!g!] => 42; +} +'''); + } + test_instanceSetter() async { await assertNoDiagnostics(r''' class C { @@ -115,6 +123,24 @@ '''); } + test_localFunction_noReturnType() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + [!g!]() {} + g(); +} +'''); + } + + test_localFunction_withReturnType() async { + await assertNoDiagnostics(r''' +void f() { + void g() {} + g(); +} +'''); + } + test_method_expressionBody() async { await assertDiagnosticsFromMarkup(r''' class C { @@ -243,6 +269,18 @@ '''); } + test_topLevelGetter_noReturnType() async { + await assertDiagnosticsFromMarkup(r''' +get [!g!] => 42; +'''); + } + + test_topLevelGetter_withReturnType() async { + await assertNoDiagnostics(r''' +int get g => 42; +'''); + } + test_topLevelSetter() async { await assertNoDiagnostics(r''' set f(int p) {}
diff --git a/pkg/linter/test/rules/always_specify_types_test.dart b/pkg/linter/test/rules/always_specify_types_test.dart index fe8d3c8..e7147de 100644 --- a/pkg/linter/test/rules/always_specify_types_test.dart +++ b/pkg/linter/test/rules/always_specify_types_test.dart
@@ -294,6 +294,22 @@ '''); } + test_constructorTearoff_implicitInstantiation() async { + // Known false negative: the type arguments of a constructor tear-off that + // are inferred from the context are not reported. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +class C<T> { + C(); + C.named(); +} +void f() { + C<int> Function() g = C.new; + C<int> Function() h = C.named; +} +'''); + } + test_constructorTearoff_keptGeneric() async { await assertNoDiagnostics(r''' void f() { @@ -1039,6 +1055,18 @@ '''); } + test_redirectingFactory_implicitTypeArgument() async { + await assertDiagnosticsFromMarkup(r''' +class A<T> { + A.a(); + factory A() = [!B!]; +} +class B<T> extends A<T> { + B() : super.a(); +} +'''); + } + test_setLiteral() async { await assertDiagnosticsFromMarkup(r''' f() {
diff --git a/pkg/linter/test/rules/analyzer_element_model_tracking_test.dart b/pkg/linter/test/rules/analyzer_element_model_tracking_test.dart index 8e48427..b1e51d2 100644 --- a/pkg/linter/test/rules/analyzer_element_model_tracking_test.dart +++ b/pkg/linter/test/rules/analyzer_element_model_tracking_test.dart
@@ -425,6 +425,20 @@ '''); } + test_public_instancePublic_operator_noAnnotation() async { + await assertDiagnostics( + r''' +import 'package:analyzer/src/fine/annotations.dart'; + +@elementClass +class A { + int operator +(int other) => 0; +} +''', + [lint(93, 1, name: 'analyzer_element_model_tracking_zero')], + ); + } + test_public_staticPrivate_field_trackedIncludedInId() async { await assertDiagnostics( r'''
diff --git a/pkg/linter/test/rules/analyzer_v1_ast_use_test.dart b/pkg/linter/test/rules/analyzer_v1_ast_use_test.dart index 9839073..571bfba 100644 --- a/pkg/linter/test/rules/analyzer_v1_ast_use_test.dart +++ b/pkg/linter/test/rules/analyzer_v1_ast_use_test.dart
@@ -105,6 +105,23 @@ '''); } + test_constructor_annotation_unnamed() async { + // Known false negative: in `@A()` only the class name `A` is checked, not + // the unnamed constructor that the annotation invokes. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +import 'v1_ast.dart'; + +class A { + @V1Ast() + const A(); +} + +@A() +void f() {} +'''); + } + test_exportDirective_show() async { newFile('$testPackageLibPath/a.dart', r''' import 'v1_ast.dart'; @@ -147,6 +164,22 @@ '''); } + test_importDirective_hide() async { + newFile('$testPackageLibPath/a.dart', r''' +import 'v1_ast.dart'; + +@V1Ast('The V2 counterpart is B.') +class A {} + +class B {} +'''); + await assertNoDiagnostics(r''' +import 'a.dart' hide A; + +void foo(B b) {} +'''); + } + test_importDirective_show() async { newFile('$testPackageLibPath/a.dart', r''' import 'v1_ast.dart';
diff --git a/pkg/linter/test/rules/annotate_redeclares_test.dart b/pkg/linter/test/rules/annotate_redeclares_test.dart index ed8ae7f..4c6b45b 100644 --- a/pkg/linter/test/rules/annotate_redeclares_test.dart +++ b/pkg/linter/test/rules/annotate_redeclares_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -68,6 +69,33 @@ '''); } + test_getter() async { + await assertDiagnosticsFromMarkup(r''' +class A { + int get i => 0; +} + +extension type E(A a) implements A { + int get [!i!] => 0; +} +'''); + } + + test_getter_static() async { + await assertDiagnostics( + r''' +class A { + int get i => 0; +} + +extension type E(A a) implements A { + static int get i => 0; +} +''', + [error(diag.conflictingStaticAndInstance, 85, 1)], + ); + } + test_method() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -94,6 +122,33 @@ '''); } + test_method_static() async { + await assertDiagnostics( + r''' +class A { + void m() {} +} + +extension type E(A a) implements A { + static void m() {} +} +''', + [error(diag.conflictingStaticAndInstance, 78, 1)], + ); + } + + test_operator() async { + await assertDiagnosticsFromMarkup(r''' +class A { + int operator +(int other) => 0; +} + +extension type E(A a) implements A { + int operator [!+!](int other) => 0; +} +'''); + } + test_setter() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -105,4 +160,34 @@ } '''); } + + test_setter_static() async { + await assertDiagnostics( + r''' +class A { + int s = 0; +} + +extension type E(A a) implements A { + static set s(int v) {} +} +''', + [error(diag.conflictingStaticAndInstance, 76, 1)], + ); + } + + test_setter_static_inheritedSetterOnly() async { + await assertDiagnostics( + r''' +class A { + set s(int v) {} +} + +extension type E(A a) implements A { + static set s(int v) {} +} +''', + [error(diag.conflictingStaticAndInstance, 81, 1)], + ); + } }
diff --git a/pkg/linter/test/rules/avoid_catches_without_on_clauses_test.dart b/pkg/linter/test/rules/avoid_catches_without_on_clauses_test.dart index b1ba85e..fdab890 100644 --- a/pkg/linter/test/rules/avoid_catches_without_on_clauses_test.dart +++ b/pkg/linter/test/rules/avoid_catches_without_on_clauses_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -97,6 +98,38 @@ '''); } + test_missingOnClause_usedInCompleter_completeError_cascade() async { + await assertNoDiagnostics(r''' +import 'dart:async'; + +void f(Completer<int> completer) { + try {} catch (e) { + completer..completeError(e); + } +} +'''); + } + + test_missingOnClause_usedInCompleter_completeError_super() async { + await assertDiagnostics( + r''' +import 'dart:async'; + +abstract class B extends Completer<int> { + void g() { + try {} catch (e) { + super.completeError(e); + } + } +} +''', + [ + error(diag.noGenerativeConstructorsInSuperclass, 47, 14), + error(diag.abstractSuperMemberReference, 112, 13), + ], + ); + } + test_missingOnClause_usedInFlutterError_reportError() async { await assertNoDiagnostics(r''' import 'package:flutter/foundation.dart'; @@ -108,6 +141,35 @@ '''); } + test_missingOnClause_usedInFlutterError_reportError_cascade() async { + await assertDiagnostics( + r''' +import 'package:flutter/foundation.dart'; + +void f() { + try {} catch (e) { + FlutterError..reportError(FlutterErrorDetails(exception: e)); + } +} +''', + [lint(63, 5), error(diag.undefinedInstanceMemberReadNotFound, 93, 11)], + ); + } + + test_missingOnClause_usedInFlutterError_reportError_importPrefix() async { + await assertNoDiagnostics(r''' +import 'package:flutter/foundation.dart' as foundation; + +void f() { + try {} catch (e) { + foundation.FlutterError.reportError( + foundation.FlutterErrorDetails(exception: e), + ); + } +} +'''); + } + test_missingOnClause_usedInFuture_error() async { await assertNoDiagnostics(r''' void f() { @@ -118,6 +180,20 @@ '''); } + test_missingOnClause_usedInFuture_error_annotation() async { + await assertDiagnostics( + r''' +void f() { + try {} catch (e) { + @Future.error(e) + var x = 0; + } +} +''', + [lint(20, 5), error(diag.constWithNonConst, 37, 15)], + ); + } + test_missingOnClause_usedInNeverReturningFunction() async { await assertNoDiagnostics(r''' void f() { @@ -129,6 +205,49 @@ '''); } + test_missingOnClause_usedInNeverReturningFunction_cascade() async { + await assertNoDiagnostics(r''' +class A { + Never fail(Object e) => throw e; +} + +void f(A a) { + try {} catch (e) { + a..fail(e); + } +} +'''); + } + + test_missingOnClause_usedInNeverReturningFunction_importPrefix() async { + newFile('$testPackageLibPath/a.dart', r''' +Never fail(Object e) => throw e; +'''); + await assertNoDiagnostics(r''' +import 'a.dart' as a; + +void f() { + try {} catch (e) { + a.fail(e); + } +} +'''); + } + + test_missingOnClause_usedInNeverReturningFunction_method() async { + await assertNoDiagnostics(r''' +class A { + Never fail(Object e) => throw e; +} + +void f(A a) { + try {} catch (e) { + a.fail(e); + } +} +'''); + } + test_missingOnClause_usedInNeverReturningFunctionExpression() async { await assertNoDiagnostics(r''' void f() { @@ -140,6 +259,19 @@ '''); } + test_missingOnClause_usedInThrownAssignment() async { + await assertDiagnostics( + r''' +void f(Object o) { + try {} catch (e) { + throw e = o; + } +} +''', + [error(diag.assignmentToFinalLocal, 50, 1)], + ); + } + test_missingOnClause_usedInThrownCascadedFunctionInvocation() async { await assertNoDiagnostics(r''' void f() {
diff --git a/pkg/linter/test/rules/avoid_equals_and_hash_code_on_mutable_classes_test.dart b/pkg/linter/test/rules/avoid_equals_and_hash_code_on_mutable_classes_test.dart index e2d1b0c..6e4f8e5 100644 --- a/pkg/linter/test/rules/avoid_equals_and_hash_code_on_mutable_classes_test.dart +++ b/pkg/linter/test/rules/avoid_equals_and_hash_code_on_mutable_classes_test.dart
@@ -130,6 +130,25 @@ '''); } + test_mutableClass_hashCodeMethod() async { + await assertDiagnostics( + r''' +class A { + void hashCode() {} +} +''', + [lint(12, 4), error(diag.conflictingMethodAndField, 17, 8)], + ); + } + + test_mutableClass_hashCodeSetter() async { + await assertDiagnosticsFromMarkup(r''' +class A { + [!set!] hashCode(int value) {} +} +'''); + } + test_subtypeOfImmutableClass() async { await assertNoDiagnostics(r''' import 'package:meta/meta.dart';
diff --git a/pkg/linter/test/rules/avoid_futureor_void_test.dart b/pkg/linter/test/rules/avoid_futureor_void_test.dart index 4a28cbe..4ad6dd1 100644 --- a/pkg/linter/test/rules/avoid_futureor_void_test.dart +++ b/pkg/linter/test/rules/avoid_futureor_void_test.dart
@@ -55,6 +55,15 @@ '''); } + test_extendsClause() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A<T> {} +class B extends A<[!FutureOr<void>!]> {} +'''); + } + test_extension_bound() async { await assertDiagnosticsFromMarkup(r''' import 'dart:async'; @@ -87,6 +96,16 @@ '''); } + test_field() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A { + [!FutureOr<void>!] f = 1; +} +'''); + } + test_function_bound() async { await assertDiagnosticsFromMarkup(r''' import 'dart:async'; @@ -140,6 +159,25 @@ '''); } + test_getter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A { + [!FutureOr<void>!] get g => 1; +} +'''); + } + + test_implementsClause() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A<T> {} +class B implements A<[!FutureOr<void>!]> {} +'''); + } + test_isExpression() async { await assertDiagnosticsFromMarkup(r''' import 'dart:async'; @@ -149,6 +187,69 @@ '''); } + test_localFunction() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +void f() { + [!FutureOr<void>!] g() {} + g; +} +'''); + } + + test_localFunction_parameter_functionTypeParameter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +void f() { + void g(void Function([!FutureOr<void>!]) p) {} + g; +} +'''); + } + + test_localVariable() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +void f() { + [!FutureOr<void>!] v = 1; + v; +} +'''); + } + + test_method() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A { + [!FutureOr<void>!] m() {} +} +'''); + } + + test_method_parameter_functionTypeParameter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A { + void m(void Function([!FutureOr<void>!]) p) {} +} +'''); + } + + test_method_parameter_ok() async { + await assertNoDiagnostics(r''' +import 'dart:async'; + +class A { + void m(FutureOr<void> p) {} +} +'''); + } + test_mixin_bound() async { await assertDiagnosticsFromMarkup(r''' import 'dart:async'; @@ -157,6 +258,15 @@ '''); } + test_mixinOnClause() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A<T> {} +mixin M on A<[!FutureOr<void>!]> {} +'''); + } + test_objectPattern() async { await assertDiagnosticsFromMarkup(r''' import 'dart:async'; @@ -194,6 +304,102 @@ '''); } + test_operator() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A { + [!FutureOr<void>!] operator +(int other) {} +} +'''); + } + + test_operator_parameter_functionTypeParameter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A { + void operator +(void Function([!FutureOr<void>!]) other) {} +} +'''); + } + + test_primaryConstructor_parameter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A(final [!FutureOr<void>!] f); +'''); + } + + test_setter_parameter_functionTypeParameter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +class A { + set s(void Function([!FutureOr<void>!]) v) {} +} +'''); + } + + test_setter_parameter_ok() async { + await assertNoDiagnostics(r''' +import 'dart:async'; + +class A { + set s(FutureOr<void> v) {} +} +'''); + } + + test_topLevelFunction() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +[!FutureOr<void>!] f() {} +'''); + } + + test_topLevelFunction_parameter_functionTypeParameter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +void f(void Function([!FutureOr<void>!]) p) {} +'''); + } + + test_topLevelGetter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +[!FutureOr<void>!] get g => 1; +'''); + } + + test_topLevelSetter_parameter_functionTypeParameter() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +set s(void Function([!FutureOr<void>!]) v) {} +'''); + } + + test_topLevelSetter_parameter_ok() async { + await assertNoDiagnostics(r''' +import 'dart:async'; + +set s(FutureOr<void> v) {} +'''); + } + + test_topLevelVariable() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +[!FutureOr<void>!] v = 1; +'''); + } + test_typeAlias_body() async { await assertNoDiagnostics(r''' import 'dart:async'; @@ -217,4 +423,13 @@ typedef F<X extends [!FutureOr<void>!]> = int; '''); } + + test_withClause() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; + +mixin M<T> {} +class B with M<[!FutureOr<void>!]> {} +'''); + } }
diff --git a/pkg/linter/test/rules/avoid_positional_boolean_parameters_test.dart b/pkg/linter/test/rules/avoid_positional_boolean_parameters_test.dart index ebdcdbb..e4c2f13 100644 --- a/pkg/linter/test/rules/avoid_positional_boolean_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_positional_boolean_parameters_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -152,6 +153,26 @@ '''); } + test_getter_functionType() async { + await assertDiagnosticsFromMarkup(r''' +class A { + bool Function(bool, [!bool!]) get g => (a, b) => a; +} +'''); + } + + test_getter_overrideExtends_functionType() async { + await assertDiagnosticsFromMarkup(r''' +class A { + bool Function(bool, [!bool!]) get g => (a, b) => a; +} +class B extends A { + @override + bool Function(bool, bool) get g => (a, b) => a; +} +'''); + } + test_instanceMethod_functionTypedParameter() async { await assertDiagnosticsFromMarkup(r''' class C { @@ -239,6 +260,24 @@ '''); } + test_localFunction_positional_multiple() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + // ignore: unused_element + void g(bool a, [!bool b!]) {} +} +'''); + } + + test_localFunctionPrivate_positional_multiple() async { + await assertNoDiagnostics(r''' +void f() { + // ignore: unused_element + void _g(bool a, bool b) {} +} +'''); + } + test_operator_indexAssignment() async { await assertNoDiagnostics(r''' class C { @@ -255,6 +294,18 @@ '''); } + test_operator_overrideExtends_functionType() async { + await assertDiagnosticsFromMarkup(r''' +class A { + A operator +(bool Function(bool, [!bool!]) v) => this; +} +class B extends A { + @override + A operator +(bool Function(bool, bool) v) => this; +} +'''); + } + test_operator_plus() async { await assertNoDiagnostics(r''' class C { @@ -264,6 +315,24 @@ '''); } + test_setter_overrideExtends_functionType() async { + // Known false positive: the formal parameter type of `B.g` is fixed by the + // overridden setter `A.g`, but the function type in it is still reported. + // See https://github.com/dart-lang/sdk/issues/64219. + await assertDiagnostics( + r''' +class A { + set g(bool Function(bool, bool) v) {} +} +class B extends A { + @override + set g(bool Function(bool, bool) v) {} +} +''', + [lint(38, 4), lint(112, 4)], + ); + } + test_staticMethod_namedWithDefault() async { await assertNoDiagnostics(r''' class B { @@ -305,6 +374,15 @@ '''); } + test_topLevelSetter_positional_multiple() async { + await assertDiagnostics( + r''' +set f(bool a, bool b) {} +''', + [error(diag.wrongNumberOfParametersForSetter, 4, 1)], + ); + } + test_typedef_named() async { await assertNoDiagnostics(r''' typedef T = Function({bool p});
diff --git a/pkg/linter/test/rules/avoid_private_typedef_functions_test.dart b/pkg/linter/test/rules/avoid_private_typedef_functions_test.dart index d0280bb..c5cd8da 100644 --- a/pkg/linter/test/rules/avoid_private_typedef_functions_test.dart +++ b/pkg/linter/test/rules/avoid_private_typedef_functions_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -17,6 +18,17 @@ @override String get lintRule => LintNames.avoid_private_typedef_functions; + test_constructorReference() async { + await assertDiagnostics( + r''' +typedef _F = void Function(); +_F? v; +var x = new _F(); +''', + [error(diag.newWithNonType, 49, 2)], + ); + } + test_nonFunctionTypeAlias() async { await assertNoDiagnostics(r''' typedef _Td = List<String>;
diff --git a/pkg/linter/test/rules/avoid_renaming_method_parameters_test.dart b/pkg/linter/test/rules/avoid_renaming_method_parameters_test.dart index 9735664..3172ded 100644 --- a/pkg/linter/test/rules/avoid_renaming_method_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_renaming_method_parameters_test.dart
@@ -113,6 +113,17 @@ '''); } + test_operator_renamed() async { + await assertDiagnosticsFromMarkup(r''' +class A { + int operator +(int p) => 0; +} +class B extends A { + int operator +(int [!q!]) => 0; +} +'''); + } + test_optionalPositional_renamed() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -209,6 +220,20 @@ '''); } + test_setter_renamed() async { + // Known false negative: the overridden member is looked up by the getter + // name `s`, so the overridden setter `s=` is not found. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +class A { + set s(int p) {} +} +class B extends A { + set s(int q) {} +} +'''); + } + test_wildcard_allowed() async { await assertNoDiagnostics(r''' class A {
diff --git a/pkg/linter/test/rules/avoid_returning_this_test.dart b/pkg/linter/test/rules/avoid_returning_this_test.dart index da99011..1715572 100644 --- a/pkg/linter/test/rules/avoid_returning_this_test.dart +++ b/pkg/linter/test/rules/avoid_returning_this_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -156,6 +157,20 @@ '''); } + test_methodReturnsThis_containsLocalFunctionWithBlockBody() async { + await assertDiagnosticsFromMarkup(r''' +class A { + A m() { + int f() { + return 1; + } + f(); + return [!this!]; + } +} +'''); + } + test_methodReturnsThis_inEnum() async { await assertDiagnosticsFromMarkup(r''' enum A { @@ -209,4 +224,15 @@ } '''); } + + test_setterReturnsThis_arrow() async { + await assertDiagnostics( + r''' +class A { + A set s(int _) => this; +} +''', + [error(diag.nonVoidReturnForSetter, 12, 1), lint(18, 1)], + ); + } }
diff --git a/pkg/linter/test/rules/avoid_shadowing_type_parameters_test.dart b/pkg/linter/test/rules/avoid_shadowing_type_parameters_test.dart index a7cad67..016dfb0 100644 --- a/pkg/linter/test/rules/avoid_shadowing_type_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_shadowing_type_parameters_test.dart
@@ -18,6 +18,17 @@ @override String get lintRule => LintNames.avoid_shadowing_type_parameters; + test_closure_shadowingClass() async { + await assertDiagnosticsFromMarkup(r''' +class C<T> { + void f() { + var g = <[!T!]>() {}; + g<int>(); + } +} +'''); + } + test_enclosingElementsWithoutTypeParameters() async { // Make sure we don't hit any null pointers when none of a function or // method's ancestors have type parameters. @@ -84,6 +95,15 @@ '''); } + test_localFunction_shadowingClosure() async { + await assertDiagnosticsFromMarkup(r''' +var f = <T>() { + void g<[!T!]>() {} + g<int>(); +}; +'''); + } + test_localFunction_shadowingFunction() async { await assertDiagnosticsFromMarkup(r''' void f<T>() {
diff --git a/pkg/linter/test/rules/avoid_slow_async_io_test.dart b/pkg/linter/test/rules/avoid_slow_async_io_test.dart index 6db12ee..4292e9f 100644 --- a/pkg/linter/test/rules/avoid_slow_async_io_test.dart +++ b/pkg/linter/test/rules/avoid_slow_async_io_test.dart
@@ -112,6 +112,17 @@ '''); } + test_file_lastModified_unqualified() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:io'; +abstract class A implements File { + void f() { + [!lastModified()!]; + } +} +'''); + } + test_file_lastModifiedSync() async { await assertNoDiagnostics(r''' import 'dart:io';
diff --git a/pkg/linter/test/rules/avoid_types_as_parameter_names_test.dart b/pkg/linter/test/rules/avoid_types_as_parameter_names_test.dart index f78ebf3..6601d62 100644 --- a/pkg/linter/test/rules/avoid_types_as_parameter_names_test.dart +++ b/pkg/linter/test/rules/avoid_types_as_parameter_names_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -35,6 +36,24 @@ '''); } + test_classTypeParameter_operatorFunctionTypedParameter() async { + await assertNoDiagnostics(r''' +// @dart = 3.14 +class A<X> { + int operator +(int g<X>()) => 0; +} +'''); + } + + test_classTypeParameter_setterFunctionTypedParameter() async { + await assertNoDiagnostics(r''' +// @dart = 3.14 +class A<X> { + set s(void g<X>()) {} +} +'''); + } + test_classTypeParameter_staticMethodTypeParameter() async { await assertNoDiagnostics(r''' class A<X> { @@ -231,12 +250,33 @@ '''); } + test_typeParameter_closure() async { + await assertDiagnosticsFromMarkup(r''' +var f = <[!int!]>() {}; +'''); + } + + test_typeParameter_extension() async { + // Known false negative: the scope walk does not stop at extensions, so + // their type parameters are never checked. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +extension E<int> on String {} +'''); + } + test_typeParameter_function() async { await assertDiagnosticsFromMarkup(r''' void f<[!int!]>() {} '''); } + test_typeParameter_genericFunctionType() async { + await assertDiagnosticsFromMarkup(r''' +void Function<[!int!]>()? f; +'''); + } + test_typeParameter_instanceMethod_class() async { await assertDiagnosticsFromMarkup(r''' class A<X> { @@ -247,6 +287,82 @@ '''); } + test_typeParameter_localFunction() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + void g<[!int!]>() {} + g<String>(); +} +'''); + } + + test_typeParameter_localFunction_enclosingTypeParameter() async { + await assertDiagnosticsFromMarkup(r''' +void f<T>() { + void g<[!T!]>() {} + g<int>(); +} +'''); + } + + test_typeParameter_mixin() async { + // Known false negative: the scope walk does not stop at mixins, so their + // type parameters are never checked. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +mixin M<int> {} +'''); + } + + test_typeParameter_operator() async { + await assertDiagnostics( + r''' +class A { + int operator +<int>(other) => 0; +} +''', + [ + error(diag.typeParameterOnOperator, 26, 5), + lint(27, 3), + error(diag.returnOfInvalidTypeFromMethod, 42, 1), + ], + ); + } + + test_typeParameter_operatorFunctionTypedParameter_extension() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.14 +extension E on int { + int operator +(int g<[!int!]>()) => 0; +} +'''); + } + + test_typeParameter_setterFunctionTypedParameter() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.14 +class A { + set s(void g<[!int!]>()) {} +} +'''); + } + + test_typeParameter_setterFunctionTypedParameter_extension() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.14 +extension E on int { + set s(void g<[!int!]>()) {} +} +'''); + } + + test_typeParameter_topLevelSetterFunctionTypedParameter() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.14 +set s(void g<[!int!]>()) {} +'''); + } + test_typeParameter_wildcard() async { await assertNoDiagnostics(r''' class C<_> {
diff --git a/pkg/linter/test/rules/avoid_unused_constructor_parameters_test.dart b/pkg/linter/test/rules/avoid_unused_constructor_parameters_test.dart index 5e288e7..87e803b 100644 --- a/pkg/linter/test/rules/avoid_unused_constructor_parameters_test.dart +++ b/pkg/linter/test/rules/avoid_unused_constructor_parameters_test.dart
@@ -169,6 +169,18 @@ '''); } + test_unused_mentionedInCommentReference() async { + await assertDiagnosticsFromMarkup(r''' +class C { + C([!int a!]) { + /// [a] + void f() {} + f(); + } +} +'''); + } + test_unused_optionalPositional() async { await assertDiagnosticsFromMarkup(r''' class C { @@ -201,6 +213,56 @@ '''); } + test_usedInConstructorBody_assignment() async { + await assertNoDiagnostics(r''' +class C { + C(int a) { + a = 1; + } +} +'''); + } + + test_usedInConstructorBody_callInvocation() async { + await assertNoDiagnostics(r''' +class C { + C(void Function() a) { + a(); + } +} +'''); + } + + test_usedInConstructorBody_compoundAssignment() async { + await assertNoDiagnostics(r''' +class C { + C(int a) { + a += 1; + } +} +'''); + } + + test_usedInConstructorBody_forEachTarget() async { + await assertNoDiagnostics(r''' +class C { + C(int a) { + for (a in [1]) {} + } +} +'''); + } + + test_usedInConstructorBody_increment() async { + await assertNoDiagnostics(r''' +class C { + C(int a) { + a++; + } +} +'''); + } + test_usedInConstructorBody_primary() async { await assertNoDiagnostics(r''' class C({int p = 0}) {
diff --git a/pkg/linter/test/rules/close_sinks_test.dart b/pkg/linter/test/rules/close_sinks_test.dart index d036c94..00c2c76 100644 --- a/pkg/linter/test/rules/close_sinks_test.dart +++ b/pkg/linter/test/rules/close_sinks_test.dart
@@ -57,6 +57,19 @@ '''); } + test_field_closed_cascadeOnThis() async { + await assertNoDiagnostics(r''' +import 'dart:io'; +class C { + IOSink sink = File('').openWrite(); + + void m() { + this..sink.close(); + } +} +'''); + } + test_field_closed_explicitThis() async { await assertNoDiagnostics(r''' import 'dart:io'; @@ -208,6 +221,82 @@ '''); } + test_field_sameNameAsAssignedProperty_cascade() async { + // Known false negative: the assignment to the unrelated `B.sink` is + // matched by name, so the unclosed `A.sink` is not reported. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +import 'dart:io'; +class A { + IOSink sink = File('').openWrite(); +} +class B { + IOSink? sink; +} +void f(B b, IOSink other) { + b..sink = other; +} +'''); + } + + test_field_sameNameAsAssignedProperty_parenthesizedReceiver() async { + // Known false negative: the assignment to the unrelated `B.sink` is + // matched by name, so the unclosed `A.sink` is not reported. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +import 'dart:io'; +class A { + IOSink sink = File('').openWrite(); +} +class B { + IOSink? sink; +} +void f(B b, IOSink other) { + (b).sink = other; +} +'''); + } + + test_field_sameNameAsAssignedProperty_simpleReceiver() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:io'; +class A { + IOSink [!sink = File('').openWrite()!]; +} +class B { + IOSink? sink; +} +void f(B b, IOSink other) { + b.sink = other; +} +'''); + } + + test_localVariable_assigned_compound() async { + await assertNoDiagnostics(r''' +void f(S other) { + var sink = S(); + sink += other; +} +class S implements Sink<int> { + @override + void close() {} + S operator +(Object other) => this; +} +'''); + } + + test_localVariable_assigned_ifNull() async { + await assertNoDiagnostics(r''' +import 'dart:io'; +void f(IOSink? other) { + IOSink? sink = g(); + sink ??= other; +} +IOSink? g() => null; +'''); + } + test_localVariable_closed() async { await assertNoDiagnostics(r''' import 'dart:io'; @@ -218,6 +307,34 @@ '''); } + test_localVariable_closed_inInitializer_cascade() async { + await assertNoDiagnostics(r''' +import 'dart:io'; +void f() { + var sink = File('').openWrite()..close(); + sink.toString(); +} +'''); + } + + test_localVariable_closed_inInitializer_importPrefixed() async { + // Known false negative: the unrelated `prefix.close()` is matched by + // name, so the unclosed `sink` is not reported. + // See https://github.com/dart-lang/sdk/issues/65178. + newFile('$testPackageLibPath/a.dart', r''' +int close() => 0; +'''); + await assertNoDiagnostics(r''' +import 'dart:io'; +import 'a.dart' as prefix; +void f() { + var sink = g(prefix.close()); + sink.toString(); +} +IOSink g(int i) => throw 0; +'''); + } + test_localVariable_inFunction_notInitialized() async { await assertDiagnosticsFromMarkup(r''' import 'dart:io'; @@ -239,6 +356,57 @@ '''); } + test_localVariable_passedToCascadeMethod() async { + await assertNoDiagnostics(r''' +import 'dart:io'; +void f(C c) { + var sink = File('').openWrite(); + c..m(sink); +} +class C { + void m(IOSink sink) {} +} +'''); + } + + test_localVariable_passedToFunction() async { + await assertNoDiagnostics(r''' +import 'dart:io'; +void f() { + var sink = File('').openWrite(); + g(sink); +} +void g(IOSink sink) {} +'''); + } + + test_localVariable_passedToImportPrefixedFunction() async { + newFile('$testPackageLibPath/a.dart', r''' +void g(Object o) {} +'''); + await assertNoDiagnostics(r''' +import 'dart:io'; +import 'a.dart' as prefix; +void f() { + var sink = File('').openWrite(); + prefix.g(sink); +} +'''); + } + + test_localVariable_passedToMethod() async { + await assertNoDiagnostics(r''' +import 'dart:io'; +void f(C c) { + var sink = File('').openWrite(); + c.m(sink); +} +class C { + void m(IOSink sink) {} +} +'''); + } + test_socket_destroyed() async { await assertNoDiagnostics(r''' import 'dart:io';
diff --git a/pkg/linter/test/rules/comment_references_test.dart b/pkg/linter/test/rules/comment_references_test.dart index fff48d6..80b1493 100644 --- a/pkg/linter/test/rules/comment_references_test.dart +++ b/pkg/linter/test/rules/comment_references_test.dart
@@ -149,6 +149,15 @@ '''); } + test_operator_defined() async { + await assertNoDiagnostics(r''' +class C { + /// [operator +] + int operator +(int other) => 0; +} +'''); + } + test_operator_index_prefixed_unknown() async { await assertDiagnosticsFromMarkup(r''' /// Text [[!C.[]!]]. @@ -156,6 +165,20 @@ '''); } + test_operator_prefixed_undefined() async { + await assertDiagnosticsFromMarkup(r''' +/// [[!C.operator +!]] +class C {} +'''); + } + + test_operator_undefined() async { + await assertDiagnosticsFromMarkup(r''' +/// [operator [!+!]] +class C {} +'''); + } + test_parameter() async { await assertNoDiagnostics(r''' class A {
diff --git a/pkg/linter/test/rules/constant_identifier_names_test.dart b/pkg/linter/test/rules/constant_identifier_names_test.dart index 34b5c75..db6d45d 100644 --- a/pkg/linter/test/rules/constant_identifier_names_test.dart +++ b/pkg/linter/test/rules/constant_identifier_names_test.dart
@@ -156,6 +156,23 @@ '''); } + test_localConstant() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + const [!DEBUG!] = 1; + DEBUG; +} +'''); + } + + test_localConstant_forParts() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + for (const [!DEBUG!] = 1; DEBUG > 2;) {} +} +'''); + } + test_recordFieldDestructured() async { await assertDiagnosticsFromMarkup(r''' f(Object o) {
diff --git a/pkg/linter/test/rules/deprecated_member_use_from_same_package_test.dart b/pkg/linter/test/rules/deprecated_member_use_from_same_package_test.dart index ce9f264..a5452d0 100644 --- a/pkg/linter/test/rules/deprecated_member_use_from_same_package_test.dart +++ b/pkg/linter/test/rules/deprecated_member_use_from_same_package_test.dart
@@ -42,6 +42,18 @@ '''); } + test_deprecatedClass_usedInAnnotation() async { + await assertDiagnosticsFromMarkup(r''' +@deprecated +class A { + const A(); +} + +@[!A!]() +void f() {} +'''); + } + test_deprecatedClass_usedInClassTypeAlias() async { await assertDiagnosticsFromMarkup(r''' @deprecated @@ -293,6 +305,44 @@ ); } + test_deprecatedConstructor_usedInAnnotation_named() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + const A.named(); +} + +@A.[!named!]() +void f() {} +'''); + } + + test_deprecatedConstructor_usedInAnnotation_unnamed() async { + // Known false negative: in `@A()` only the class name `A` is checked, not + // the unnamed constructor that the annotation invokes. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +class A { + @deprecated + const A(); +} + +@A() +void f() {} +'''); + } + + test_deprecatedConstructor_usedInDotShorthand() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + A.named(); +} + +A f() => .[!named!](); +'''); + } + test_deprecatedConstructor_usedInRedirectingConstructorInitializer() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -327,6 +377,17 @@ '''); } + test_deprecatedConstructor_usedInTearOff() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + A.named(); +} + +var f = [!A.named!]; +'''); + } + test_deprecatedDefaultParameterOfFunction() async { await assertDiagnosticsFromMarkup(r''' void f({@deprecated int p = 1}) {} @@ -470,6 +531,29 @@ '''); } + test_deprecatedField_usedInCascade() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + int f = 0; +} + +void g(A a) { + a..[!f!]; +} +'''); + } + + test_deprecatedField_usedInConstructorInitializer() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + int f; + A() : [!f!] = 0; +} +'''); + } + test_deprecatedField_usedInDeprecatedClass() async { await assertNoDiagnostics(r''' class A { @@ -502,6 +586,29 @@ '''); } + test_deprecatedField_usedInDotShorthand() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + static A f = A(); +} + +A g() => .[!f!]; +'''); + } + + test_deprecatedField_usedInForEach() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + int f = 0; + void g() { + for ([!f!] in [0]) {} + } +} +'''); + } + test_deprecatedField_usedInPostfix() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -580,6 +687,48 @@ '''); } + test_deprecatedIndexOperator_usedInCascade() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + int operator [](int i) => 0; +} + +void f(A a) { + a[!..[0]!]; +} +'''); + } + + test_deprecatedIndexOperator_usedInCascade_chain() async { + await assertDiagnostics( + r''' +class A { + @deprecated + A operator [](int i) => this; +} + +void f(A a) { + a..[0][0]; +} +''', + [lint(76, 5), lint(76, 8)], + ); + } + + test_deprecatedIndexOperator_usedInCascadeAssignment() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + void operator []=(int i, int v) {} +} + +void f(A a) { + a[!..[0]!] = 1; +} +'''); + } + test_deprecatedLibrary_export() async { newFile('$testPackageLibPath/lib.dart', r''' @deprecated @@ -635,6 +784,16 @@ ); } + test_deprecatedLocalVariable_usedInForEach() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + @deprecated + var a = 0; + for ([!a!] in [0]) {} +} +'''); + } + test_deprecatedMethod() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -648,6 +807,18 @@ '''); } + test_deprecatedMethod_usedInCommentReference() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + void m() {} +} + +/// [A.[!m!]] +void f() {} +'''); + } + test_deprecatedMethod_usedInDeprecatedConstructor() async { await assertNoDiagnostics(r''' class A { @@ -677,6 +848,17 @@ '''); } + test_deprecatedMethod_usedInDotShorthand() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + static A m() => A(); +} + +A f() => .[!m!](); +'''); + } + test_deprecatedMethod_usedInPrimaryConstructorBody() async { await assertDiagnosticsFromMarkup(r''' @deprecated @@ -714,6 +896,23 @@ '''); } + test_deprecatedNamedConstructor_usedInRedirectingConstructorInitializer() async { + // Known false positive: `this.a()` is reported twice, once for the whole + // invocation, and once for the constructor name `a`, which is not skipped + // as it is in `super.a()`. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnostics( + r''' +class A { + @deprecated + A.a(); + A.b() : this.a(); +} +''', + [lint(43, 8), lint(48, 1)], + ); + } + test_deprecatedNamedConstructor_usedInSuperConstructorCall() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -762,6 +961,46 @@ '''); } + test_deprecatedOperator_binary() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + A operator +(A other) => this; +} + +void f(A a) { + [!a + a!]; +} +'''); + } + + test_deprecatedOperator_unary() async { + await assertDiagnosticsFromMarkup(r''' +class A { + @deprecated + A operator -() => this; +} + +void f(A a) { + [!-a!]; +} +'''); + } + + test_deprecatedOperator_usedInCascadeCompoundAssignment() async { + await assertDiagnosticsFromMarkup(r''' +class A { + A f = A(); + @deprecated + A operator +(int other) => this; +} + +void f(A a) { + a[!..f += 1!]; +} +'''); + } + test_deprecatedOperator_usedInCompoundAssignment() async { await assertDiagnosticsFromMarkup(r''' class C {
diff --git a/pkg/linter/test/rules/diagnostic_describe_all_properties_test.dart b/pkg/linter/test/rules/diagnostic_describe_all_properties_test.dart index ed78cc6..2fe6a8d 100644 --- a/pkg/linter/test/rules/diagnostic_describe_all_properties_test.dart +++ b/pkg/linter/test/rules/diagnostic_describe_all_properties_test.dart
@@ -182,6 +182,110 @@ '''); } + test_reference_assignmentTarget() async { + await assertNoDiagnostics(r''' +import 'package:flutter/foundation.dart'; +class MyWidget with Diagnosticable { + String p = ''; + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + p = ''; + } +} +'''); + } + + test_reference_cascadeProperty() async { + await assertNoDiagnostics(r''' +import 'package:flutter/foundation.dart'; +class MyWidget with Diagnosticable { + String p = ''; + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + this..p; + } +} +'''); + } + + test_reference_constructorName() async { + // Known false negative: `A.p()` is matched by name, so the field `p` + // counts as described. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +import 'package:flutter/foundation.dart'; +class MyWidget with Diagnosticable { + String p = ''; + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + A.p(); + } +} + +class A { + A.p(); +} +'''); + } + + test_reference_dotShorthand() async { + // Known false negative: `.p` is matched by name, so the field `p` + // counts as described. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +import 'package:flutter/foundation.dart'; +class MyWidget with Diagnosticable { + String p = ''; + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + A a = .p; + a; + } +} + +class A { + static A p = A(); +} +'''); + } + + test_reference_method() async { + // Known false negative: `x.p()` is matched by name, so the field `p` + // counts as described. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +import 'package:flutter/foundation.dart'; +class MyWidget with Diagnosticable { + String p = ''; + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + x.p(); + } +} + +class A { + void p() {} +} + +A x = A(); +'''); + } + + test_reference_namedArgumentLabel() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/foundation.dart'; +class MyWidget with Diagnosticable { + String [!p!] = ''; + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + g(p: 0); + } +} + +void g({int? p}) {} +'''); + } + test_staticField_string() async { await assertNoDiagnostics(r''' import 'package:flutter/foundation.dart';
diff --git a/pkg/linter/test/rules/discarded_futures_test.dart b/pkg/linter/test/rules/discarded_futures_test.dart index c4100af..03bfbf6 100644 --- a/pkg/linter/test/rules/discarded_futures_test.dart +++ b/pkg/linter/test/rules/discarded_futures_test.dart
@@ -118,6 +118,21 @@ '''); } + Future<void> test_binaryOperator_awaitNotRequired() async { + await assertNoDiagnostics(r''' +import 'package:meta/meta.dart'; + +class C { + @awaitNotRequired + Future<int> operator +(int other) async => 1; +} + +void f(C c) { + c + 1; +} +'''); + } + Future<void> test_cascade_ok_future() async { await assertNoDiagnostics(r''' void foo() { @@ -413,6 +428,18 @@ '''); } + Future<void> test_getter_unqualified() async { + await assertDiagnosticsFromMarkup(r''' +class C { + Future<int> get g async => 1; + + void f() { + [!g!]; + } +} +'''); + } + Future<void> test_ifNull_ok_future() async { await assertNoDiagnostics(r''' void foo() { @@ -595,6 +622,43 @@ '''); } + Future<void> test_prefixIncrement() async { + await assertDiagnosticsFromMarkup(r''' +class A { + Future<A> operator +(int other) async => this; +} + +class B { + A get p => A(); + set p(Future<A> v) {} +} + +void f(B b) { + [!++b.p!]; +} +'''); + } + + Future<void> test_prefixIncrement_awaitNotRequired() async { + await assertNoDiagnostics(r''' +import 'package:meta/meta.dart'; + +class A { + @awaitNotRequired + Future<A> operator +(int other) async => this; +} + +class B { + A get p => A(); + set p(Future<A> v) {} +} + +void f(B b) { + ++b.p; +} +'''); + } + Future<void> test_propertyAccess() async { await assertNoDiagnostics(r''' void foo() { @@ -714,6 +778,21 @@ '''); } + Future<void> test_unaryOperator_awaitNotRequired() async { + await assertNoDiagnostics(r''' +import 'package:meta/meta.dart'; + +class C { + @awaitNotRequired + Future<int> operator -() async => 1; +} + +void f(C c) { + -c; +} +'''); + } + Future<void> test_variable_assignment() async { await assertDiagnosticsFromMarkup(r''' var handler = <String, Function>{};
diff --git a/pkg/linter/test/rules/hash_and_equals_test.dart b/pkg/linter/test/rules/hash_and_equals_test.dart index ef66858..1e38163 100644 --- a/pkg/linter/test/rules/hash_and_equals_test.dart +++ b/pkg/linter/test/rules/hash_and_equals_test.dart
@@ -115,6 +115,17 @@ ); } + test_hashCode_method() async { + await assertDiagnostics( + r''' +class C { + int hashCode() => 1; +} +''', + [error(diag.conflictingMethodAndField, 16, 8), lint(16, 8)], + ); + } + test_hashCode_noEqualsEquals() async { await assertDiagnosticsFromMarkup(r''' class C { @@ -124,6 +135,14 @@ '''); } + test_hashCode_setter() async { + await assertDiagnosticsFromMarkup(r''' +class C { + set [!hashCode!](int value) {} +} +'''); + } + test_hashCodeField_missingEqualsEquals() async { await assertDiagnosticsFromMarkup(r''' class C {
diff --git a/pkg/linter/test/rules/no_leading_underscores_for_library_prefixes_test.dart b/pkg/linter/test/rules/no_leading_underscores_for_library_prefixes_test.dart index 9efa0e8..6d1116b 100644 --- a/pkg/linter/test/rules/no_leading_underscores_for_library_prefixes_test.dart +++ b/pkg/linter/test/rules/no_leading_underscores_for_library_prefixes_test.dart
@@ -45,6 +45,17 @@ ''', code: diag.noLeadingUnderscoresForLibraryPrefixes); } + test_notShadow_field_namedType() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:math' as [!_foo!]; + +class C { + int? foo; + void f(_foo.Random r) {} +} +''', code: diag.noLeadingUnderscoresForLibraryPrefixes); + } + test_notShadow_noConflict() async { await assertDiagnosticsFromMarkup(''' import 'dart:math' as [!_foo!]; @@ -78,6 +89,68 @@ ''', code: diag.noLeadingUnderscoresForLibraryPrefixesShadowed); } + test_shadow_field_annotation() async { + newFile('$testPackageLibPath/a.dart', r''' +class A { + const A(); +} +'''); + await assertDiagnosticsFromMarkup(r''' +import 'a.dart' as [!_foo!]; + +class C { + int? foo; + + @_foo.A() + void f() {} +} +''', code: diag.noLeadingUnderscoresForLibraryPrefixesShadowed); + } + + test_shadow_field_assignment() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:io' as [!_foo!]; + +class C { + int? foo; + void f() { + _foo.exitCode = 0; + } +} +''', code: diag.noLeadingUnderscoresForLibraryPrefixesShadowed); + } + + test_shadow_field_invocation() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:math' as [!_foo!]; + +class C { + int? foo; + void f() { + _foo.sqrt(1); + } +} +''', code: diag.noLeadingUnderscoresForLibraryPrefixesShadowed); + } + + test_shadow_field_staticQualifier() async { + newFile('$testPackageLibPath/a.dart', r''' +class A { + static int x = 0; +} +'''); + await assertDiagnosticsFromMarkup(r''' +import 'a.dart' as [!_foo!]; + +class C { + int? foo; + void f() { + _foo.A.x; + } +} +''', code: diag.noLeadingUnderscoresForLibraryPrefixesShadowed); + } + test_shadow_parameter() async { await assertDiagnosticsFromMarkup(''' import 'dart:math' as [!_foo!];
diff --git a/pkg/linter/test/rules/no_leading_underscores_for_local_identifiers_test.dart b/pkg/linter/test/rules/no_leading_underscores_for_local_identifiers_test.dart index 053f186..e3a60e8 100644 --- a/pkg/linter/test/rules/no_leading_underscores_for_local_identifiers_test.dart +++ b/pkg/linter/test/rules/no_leading_underscores_for_local_identifiers_test.dart
@@ -95,6 +95,14 @@ '''); } + test_forElement_variable() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + [for (var [!_i!] = 0; ;) 0]; +} +'''); + } + test_forLoop_firstVariable() async { await assertDiagnosticsFromMarkup(r''' void f() { @@ -418,6 +426,17 @@ ''', code: diag.noLeadingUnderscoresForLocalIdentifiersShadowed); } + test_shadow_localFunction() async { + await assertDiagnosticsFromMarkup(''' +void f() { + int foo = 1; + void [!_foo!]() {} + _foo(); + foo; +} +''', code: diag.noLeadingUnderscoresForLocalIdentifiersShadowed); + } + test_shadow_member() async { await assertDiagnosticsFromMarkup(''' class A {
diff --git a/pkg/linter/test/rules/no_logic_in_create_state_test.dart b/pkg/linter/test/rules/no_logic_in_create_state_test.dart index 92bb149..a1b8cf3 100644 --- a/pkg/linter/test/rules/no_logic_in_create_state_test.dart +++ b/pkg/linter/test/rules/no_logic_in_create_state_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -257,6 +258,19 @@ '''); } + test_getter() async { + await assertDiagnostics( + r''' +import 'package:flutter/widgets.dart'; + +abstract class C extends StatefulWidget { + State get createState => throw 0; +} +''', + [error(diag.conflictingFieldAndMethod, 94, 11), lint(109, 7)], + ); + } + test_instantiateTopLevel_returnTopLevel() async { await assertDiagnosticsFromMarkup(r''' import 'package:flutter/widgets.dart'; @@ -304,4 +318,17 @@ var global = MyState(); '''); } + + test_setter() async { + await assertDiagnostics( + r''' +import 'package:flutter/widgets.dart'; + +abstract class C extends StatefulWidget { + set createState(int v) => print(v); +} +''', + [error(diag.conflictingFieldAndMethod, 88, 11), lint(110, 8)], + ); + } }
diff --git a/pkg/linter/test/rules/no_raw_types_test.dart b/pkg/linter/test/rules/no_raw_types_test.dart index 4bb11aa..65cc523 100644 --- a/pkg/linter/test/rules/no_raw_types_test.dart +++ b/pkg/linter/test/rules/no_raw_types_test.dart
@@ -151,7 +151,7 @@ test_localVariable_extensionType_missingTypeArg() async { await assertDiagnosticsFromMarkup(r''' extension type E<T>(int i) {} - + void f() { [!E!] e = E(1); } @@ -161,7 +161,7 @@ test_localVariable_extensionType_withTypeArg() async { await assertNoDiagnostics(r''' extension type E<T>(int i) {} - + void f() { E<int> e = E<int>(1); } @@ -285,6 +285,48 @@ '''); } + test_redirectingFactoryConstructor_missingTypeArg() async { + await assertDiagnosticsFromMarkup(r''' +class A { + A(); + factory A.b() = [!B!]; +} +class B<T> implements A {} +'''); + } + + test_redirectingFactoryConstructor_typeAlias_fullyInstantiated() async { + await assertNoDiagnostics(r''' +class A { + A(); + factory A.b() = G; +} +class B<T> implements A {} +typedef G = B<dynamic>; +'''); + } + + test_redirectingFactoryConstructor_typeAlias_missingTypeArg() async { + await assertDiagnosticsFromMarkup(r''' +class A { + A(); + factory A.b() = [!E!]; +} +class B<T> implements A {} +typedef E<T> = B<T>; +'''); + } + + test_redirectingFactoryConstructor_withTypeArg() async { + await assertNoDiagnostics(r''' +class A { + A(); + factory A.b() = B<int>; +} +class B<T> implements A {} +'''); + } + test_returnType_missingTypeArg() async { await assertDiagnosticsFromMarkup(r''' [!List!] f(int a) => [1, 2, 3];
diff --git a/pkg/linter/test/rules/no_wildcard_variable_uses_test.dart b/pkg/linter/test/rules/no_wildcard_variable_uses_test.dart index 23fc994..840482f 100644 --- a/pkg/linter/test/rules/no_wildcard_variable_uses_test.dart +++ b/pkg/linter/test/rules/no_wildcard_variable_uses_test.dart
@@ -17,6 +17,16 @@ @override String get lintRule => LintNames.no_wildcard_variable_uses; + test_commentReference_param() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.4 +// (pre wildcard-variables) + +/// [[!_!]]. +void f(int _) {} +'''); + } + test_constructor() async { await assertNoDiagnostics(r''' // @dart = 3.4 @@ -117,6 +127,72 @@ '''); } + test_param_assignment() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.4 +// (pre wildcard-variables) + +void f(int _) { + [!_!] = 1; +} +'''); + } + + test_param_call() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.4 +// (pre wildcard-variables) + +void f(void Function() _) { + [!_!](); +} +'''); + } + + test_param_compoundAssignment() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.4 +// (pre wildcard-variables) + +void f(int _) { + [!_!] += 1; +} +'''); + } + + test_param_forIn() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.4 +// (pre wildcard-variables) + +void f(int _) { + for ([!_!] in [1]) {} +} +'''); + } + + test_param_increment() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.4 +// (pre wildcard-variables) + +void f(int _) { + [!_!]++; +} +'''); + } + + test_param_receiver() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.4 +// (pre wildcard-variables) + +void f(int _) { + [!_!].isEven; +} +'''); + } + test_topLevelFunction() async { await assertNoDiagnostics(r''' // @dart = 3.4
diff --git a/pkg/linter/test/rules/non_constant_identifier_names_test.dart b/pkg/linter/test/rules/non_constant_identifier_names_test.dart index b270efa..84f54c5 100644 --- a/pkg/linter/test/rules/non_constant_identifier_names_test.dart +++ b/pkg/linter/test/rules/non_constant_identifier_names_test.dart
@@ -646,6 +646,31 @@ ); } + test_instanceGetter_upper() async { + await assertDiagnosticsFromMarkup(r''' +class A { + int get [!Foo!] => 0; +} +'''); + } + + test_instanceSetter_upper() async { + await assertDiagnosticsFromMarkup(r''' +class A { + set [!Foo!](int _) {} +} +'''); + } + + test_localFunction_upper() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + void [!Foo!]() {} + Foo(); +} +'''); + } + test_localVariable_const_allCaps() async { await assertNoDiagnostics(r''' void f() { @@ -770,6 +795,18 @@ '''); } + test_topLevelGetter_upper() async { + await assertDiagnosticsFromMarkup(r''' +int get [!Foo!] => 0; +'''); + } + + test_topLevelSetter_upper() async { + await assertDiagnosticsFromMarkup(r''' +set [!Foo!](int _) {} +'''); + } + test_topLevelVariable_constant_upper() async { await assertNoDiagnostics(r''' const ZZZ = 4;
diff --git a/pkg/linter/test/rules/omit_local_variable_types_test.dart b/pkg/linter/test/rules/omit_local_variable_types_test.dart index ea4562a..efc836e 100644 --- a/pkg/linter/test/rules/omit_local_variable_types_test.dart +++ b/pkg/linter/test/rules/omit_local_variable_types_test.dart
@@ -225,6 +225,20 @@ } /// https://github.com/dart-lang/linter/issues/3016 + test_typeNeededForInference_importPrefixed() async { + newFile('$testPackageLibPath/a.dart', r''' +T f<T>() => throw 0; +'''); + await assertNoDiagnostics(r''' +import 'a.dart' as a; +void g() { + int x = a.f(); + x; +} +'''); + } + + /// https://github.com/dart-lang/linter/issues/3016 test_typeParamProvided() async { await assertDiagnosticsFromMarkup(r''' T bar<T>(dynamic d) => d;
diff --git a/pkg/linter/test/rules/omit_obvious_local_variable_types_test.dart b/pkg/linter/test/rules/omit_obvious_local_variable_types_test.dart index 1f483d1..dd8584a 100644 --- a/pkg/linter/test/rules/omit_obvious_local_variable_types_test.dart +++ b/pkg/linter/test/rules/omit_obvious_local_variable_types_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -69,6 +70,60 @@ '''); } + test_dotShorthand_hashCode() async { + await assertDiagnostics( + r''' +class A { + static A get hashCode => A(); +} +void f() { + A x = .hashCode; + x; +} +''', + [error(diag.conflictingStaticAndInstance, 25, 8)], + ); + } + + test_dotShorthand_hashCode_unresolved() async { + await assertDiagnostics( + r''' +void f() { + int x = .hashCode; + x; +} +''', + [error(diag.undefinedStaticMemberReadNotFoundDotShorthand, 22, 8)], + ); + } + + test_dotShorthand_toString() async { + await assertDiagnostics( + r''' +class A { + static A toString() => A(); +} +void f() { + A x = .toString(); + x; +} +''', + [error(diag.conflictingStaticAndInstance, 21, 8)], + ); + } + + test_dotShorthand_toString_unresolved() async { + await assertDiagnostics( + r''' +void f() { + String x = .toString(); + x; +} +''', + [error(diag.undefinedStaticMemberReadNotFoundDotShorthand, 25, 8)], + ); + } + test_forEach_inferredList() async { await assertDiagnosticsFromMarkup(r''' f() {
diff --git a/pkg/linter/test/rules/parameter_assignments_test.dart b/pkg/linter/test/rules/parameter_assignments_test.dart index 79f3f8b..9df0eba 100644 --- a/pkg/linter/test/rules/parameter_assignments_test.dart +++ b/pkg/linter/test/rules/parameter_assignments_test.dart
@@ -382,6 +382,17 @@ '''); } + test_operator_assignment() async { + await assertDiagnosticsFromMarkup(r''' +class A { + int operator +(int other) { + [!other = 5!]; + return other; + } +} +'''); + } + test_postfixOperation() async { await assertDiagnosticsFromMarkup(r''' void f(int p) { @@ -433,4 +444,12 @@ } '''); } + + test_topLevelSetter_assignment() async { + await assertDiagnosticsFromMarkup(r''' +set x(int value) { + [!value = 5!]; +} +'''); + } }
diff --git a/pkg/linter/test/rules/prefer_asserts_in_initializer_lists_test.dart b/pkg/linter/test/rules/prefer_asserts_in_initializer_lists_test.dart index dd9b476..6a94d97 100644 --- a/pkg/linter/test/rules/prefer_asserts_in_initializer_lists_test.dart +++ b/pkg/linter/test/rules/prefer_asserts_in_initializer_lists_test.dart
@@ -52,6 +52,20 @@ '''); } + test_assertContainsInstanceMethod_cascade() async { + // Known false negative: `m` is invoked on `other`, not on `this`, but any + // reference to an instance method of `A` is treated as needing `this`. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +class A { + bool m() => true; + A(A other) { + assert((other..m()) == other); + } +} +'''); + } + test_assertContainsInstanceMethod_explicitThis_inSubexpression() async { await assertNoDiagnostics(r''' class C { @@ -85,6 +99,34 @@ '''); } + test_assertContainsInstanceProperty_assigned() async { + await assertNoDiagnostics(r''' +class A { + int x = 0; + A() { + assert(() { + x = 1; + return true; + }()); + } +} +'''); + } + + test_assertContainsInstanceProperty_compoundAssigned() async { + await assertNoDiagnostics(r''' +class A { + int x = 0; + A() { + assert(() { + x += 1; + return true; + }()); + } +} +'''); + } + test_assertContainsInstanceProperty_explicitThis() async { await assertNoDiagnostics(r''' class C { @@ -96,6 +138,34 @@ '''); } + test_assertContainsInstanceProperty_forInTarget() async { + await assertNoDiagnostics(r''' +class A { + int x = 0; + A() { + assert(() { + for (x in [1]) {} + return true; + }()); + } +} +'''); + } + + test_assertContainsInstanceProperty_incremented() async { + await assertNoDiagnostics(r''' +class A { + int x = 0; + A() { + assert(() { + x++; + return true; + }()); + } +} +'''); + } + test_assertContainsInstancePropertyOfMixin() async { await assertNoDiagnostics(r''' mixin M {
diff --git a/pkg/linter/test/rules/prefer_const_declarations_test.dart b/pkg/linter/test/rules/prefer_const_declarations_test.dart index 98cde68..b73d624 100644 --- a/pkg/linter/test/rules/prefer_const_declarations_test.dart +++ b/pkg/linter/test/rules/prefer_const_declarations_test.dart
@@ -54,6 +54,16 @@ '''); } + test_forLoopVariable_final_intLiteral() async { + // Known false negative: `for` loop variable declarations are not visited. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +void f() { + for (final a = 1; a < 2;) {} +} +'''); + } + test_instanceField_final_listLiteral_const() async { await assertNoDiagnostics(r''' class C { @@ -70,6 +80,15 @@ '''); } + test_localVariable_final_annotated() async { + await assertDiagnosticsFromMarkup(r''' +const a = 0; +void f() { + [!@a final b = 1!]; +} +'''); + } + test_localVariable_final_constructorInvocation_const() async { await assertDiagnosticsFromMarkup(r''' void f() { @@ -185,6 +204,14 @@ '''); } + test_localVariable_late_final() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + [!late final a = 1!]; +} +'''); + } + test_localVariable_listLiteral_final_typed() async { await assertNoDiagnostics(r''' void f() { @@ -271,6 +298,16 @@ '''); } + test_staticField_final_annotated_multiple() async { + await assertDiagnosticsFromMarkup(r''' +const a = 0; +class C { + @a + static [!final b = 1, c = 2!]; +} +'''); + } + test_staticField_final_listLiteral() async { await assertDiagnosticsFromMarkup(r''' class C { @@ -295,6 +332,14 @@ '''); } + test_staticField_late_final() async { + await assertDiagnosticsFromMarkup(r''' +class C { + static [!late final a = 1!]; +} +'''); + } + test_staticFunctionTearoff_inference() async { await assertDiagnosticsFromMarkup(r''' void f() { @@ -351,6 +396,14 @@ '''); } + test_topLevelVariable_final_annotated_multiple() async { + await assertDiagnosticsFromMarkup(r''' +const a = 0; +@a +[!final b = 1, c = 2!]; +'''); + } + test_topLevelVariable_final_doubleLiteral() async { await assertDiagnosticsFromMarkup(r''' [!final x = 1.3!]; @@ -394,6 +447,12 @@ '''); } + test_topLevelVariable_late_final() async { + await assertDiagnosticsFromMarkup(r''' +[!late final a = 1!]; +'''); + } + test_topLevelVariable_listLiteral_const() async { await assertNoDiagnostics(r''' const x = const [];
diff --git a/pkg/linter/test/rules/prefer_constructors_over_static_methods_test.dart b/pkg/linter/test/rules/prefer_constructors_over_static_methods_test.dart index 9dd0bfb..b6102c0 100644 --- a/pkg/linter/test/rules/prefer_constructors_over_static_methods_test.dart +++ b/pkg/linter/test/rules/prefer_constructors_over_static_methods_test.dart
@@ -17,6 +17,21 @@ @override String get lintRule => LintNames.prefer_constructors_over_static_methods; + test_annotationInBody_ok() async { + await assertNoDiagnostics(r''' +class A { + const A(); + + static A f(A a) { + @A() + var x = 1; + print(x); + return a; + } +} +'''); + } + test_extensionMethod() async { await assertNoDiagnostics(r''' class A {
diff --git a/pkg/linter/test/rules/prefer_final_locals_test.dart b/pkg/linter/test/rules/prefer_final_locals_test.dart index cf75df7..016c884 100644 --- a/pkg/linter/test/rules/prefer_final_locals_test.dart +++ b/pkg/linter/test/rules/prefer_final_locals_test.dart
@@ -329,6 +329,43 @@ '''); } + test_forElement_notInFunction() async { + // Known false negative: variables outside of a function body are skipped, + // even though `i` is never reassigned. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +var a = [for (var i = 0; ;) i]; +'''); + } + + test_forElement_notReassigned() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + [for ([!var!] i = 0; ;) i]; +} +'''); + } + + test_forLoop_notReassigned() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + for ([!var!] i = 0; ;) { + print(i); + } +} +'''); + } + + test_forLoop_reassigned() async { + await assertNoDiagnostics(r''' +void f() { + for (var i = 0; ; i++) { + print(i); + } +} +'''); + } + test_ifPatternList() async { await assertDiagnosticsFromMarkup(r''' f(Object o) {
diff --git a/pkg/linter/test/rules/prefer_final_parameters_test.dart b/pkg/linter/test/rules/prefer_final_parameters_test.dart index 1ab77ab..6bde45a 100644 --- a/pkg/linter/test/rules/prefer_final_parameters_test.dart +++ b/pkg/linter/test/rules/prefer_final_parameters_test.dart
@@ -159,6 +159,29 @@ '''); } + test_localFunction() async { + await assertDiagnosticsFromMarkup(r''' +// @dart=3.12 +void f() { + void g([!int a!]) {} + g(1); +} +'''); + } + + test_localFunction_reassigned() async { + await assertNoDiagnostics(r''' +// @dart=3.12 +void f() { + void g(int a) { + a++; + } + + g(1); +} +'''); + } + test_method() async { await assertDiagnosticsFromMarkup(r''' // @dart=3.12 @@ -415,6 +438,13 @@ void f(int _){ } '''); } + + test_topLevelSetter() async { + await assertDiagnosticsFromMarkup(r''' +// @dart=3.12 +set s([!int v!]) {} +'''); + } } @reflectiveTest
diff --git a/pkg/linter/test/rules/prefer_initializing_formals_test.dart b/pkg/linter/test/rules/prefer_initializing_formals_test.dart index 1344155..ab5a3d5 100644 --- a/pkg/linter/test/rules/prefer_initializing_formals_test.dart +++ b/pkg/linter/test/rules/prefer_initializing_formals_test.dart
@@ -59,6 +59,17 @@ '''); } + test_assignedInBody_compound() async { + await assertDiagnosticsFromMarkup(r''' +class C { + int a = 0; + C(int a) { + [!this.a += a!]; + } +} +'''); + } + test_assignedInBody_justSetters() async { await assertNoDiagnostics(r''' class C { @@ -257,6 +268,30 @@ '''); } + test_assignedInInitializer_parameterAssigned() async { + await assertNoDiagnostics(r''' +class C { + int a; + C(int a) : a = a { + a = 2; + } +} +'''); + } + + test_assignedInInitializer_parameterInLocalFunctionDocComment() async { + await assertDiagnosticsFromMarkup(r''' +class C { + int a; + C(int a) : [!a = a!] { + /// [a]. + void g() {} + g(); + } +} +'''); + } + test_assignedInInitializer_privateToPrivate() async { // This code has an error because it's using a private named parameter that // doesn't refer to a field. But we still want the lint to fire because the
diff --git a/pkg/linter/test/rules/prefer_void_to_null_test.dart b/pkg/linter/test/rules/prefer_void_to_null_test.dart index 9e0dc0a..e074ee0 100644 --- a/pkg/linter/test/rules/prefer_void_to_null_test.dart +++ b/pkg/linter/test/rules/prefer_void_to_null_test.dart
@@ -151,6 +151,18 @@ '''); } + test_functionTypeParameter_null_named() async { + await assertNoDiagnostics(r''' +void f(void Function({Null x}) g) {} +'''); + } + + test_functionTypeParameter_null_optionalPositional() async { + await assertNoDiagnostics(r''' +void f(void Function([Null]) g) {} +'''); + } + test_instanceField_futureOfNull() async { await assertDiagnosticsFromMarkup(r''' class C { @@ -335,6 +347,18 @@ '''); } + test_operatorReturnType_overrideChangingType() async { + await assertNoDiagnostics(r''' +class A { + Object? operator +(int other) => null; +} +class B extends A { + @override + Null operator +(int other) => null; +} +'''); + } + test_topLevelFunction_parameterType_null() async { await assertDiagnosticsFromMarkup(r''' void f([!Null!] x) {}
diff --git a/pkg/linter/test/rules/provide_deprecation_message_test.dart b/pkg/linter/test/rules/provide_deprecation_message_test.dart index 0d63ad3..d3a6948 100644 --- a/pkg/linter/test/rules/provide_deprecation_message_test.dart +++ b/pkg/linter/test/rules/provide_deprecation_message_test.dart
@@ -24,10 +24,26 @@ '''); } + test_withMessage_prefixed() async { + await assertNoDiagnostics(r''' +import 'dart:core' as core; +@core.Deprecated("Text.") +class C {} +'''); + } + test_withoutMessage() async { await assertDiagnosticsFromMarkup(r''' [!@deprecated!] class C {} '''); } + + test_withoutMessage_prefixed() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:core' as core; +[!@core.deprecated!] +class C {} +'''); + } }
diff --git a/pkg/linter/test/rules/public_member_api_docs_test.dart b/pkg/linter/test/rules/public_member_api_docs_test.dart index 03b7758..5ed9b81 100644 --- a/pkg/linter/test/rules/public_member_api_docs_test.dart +++ b/pkg/linter/test/rules/public_member_api_docs_test.dart
@@ -193,6 +193,39 @@ '''); } + test_field_docOnDeclaration_ok() async { + await assertNoDiagnostics(r''' +/// Doc. +class C { + /// Doc. + int x = 0, y = 1; +} +'''); + } + + test_getterAndSetter_getterDoc_ok() async { + await assertNoDiagnostics(r''' +/// Doc. +class C { + /// Doc. + int get x => 0; + + set x(int value) {} +} +'''); + } + + test_getterAndSetter_noDoc() async { + await assertDiagnosticsFromMarkup(r''' +/// Doc. +class C { + int get /*[0*/x/*0]*/ => 0; + + set /*[1*/x/*1]*/(int value) {} +} +'''); + } + /// https://github.com/dart-lang/linter/issues/4521 test_internalClass() async { await assertDiagnostics( @@ -302,6 +335,15 @@ '''); } + test_method_inClass() async { + await assertDiagnosticsFromMarkup(r''' +/// Doc. +class C { + void [!m!]() {} +} +'''); + } + test_mixin_method() async { await assertDiagnosticsFromMarkup(r''' /// A mixin M. @@ -319,6 +361,15 @@ }'''); } + test_operator() async { + await assertDiagnosticsFromMarkup(r''' +/// Doc. +class C { + int operator [!+!](int other) => 0; +} +'''); + } + test_partFile() async { newFile('$testPackageRootPath/test/a.dart', r''' part 'test.dart'; @@ -544,6 +595,47 @@ '''); } + test_setter_noGetter() async { + // Known false negative: a setter is checked only together with an + // undocumented getter with the same name. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +/// Doc. +class C { + set x(int value) {} +} +'''); + } + + test_topLevelFunction() async { + await assertDiagnosticsFromMarkup(r''' +void [!f!]() {} +'''); + } + + test_topLevelFunction_main_ok() async { + await assertNoDiagnostics(r''' +void main() {} +'''); + } + + test_topLevelGetterAndSetter_getterDoc_ok() async { + await assertNoDiagnostics(r''' +/// Doc. +int get x => 0; + +set x(int value) {} +'''); + } + + test_topLevelGetterAndSetter_noDoc() async { + await assertDiagnosticsFromMarkup(r''' +int get /*[0*/x/*0]*/ => 0; + +set /*[1*/x/*1]*/(int value) {} +'''); + } + test_topLevelMembers() async { await assertDiagnosticsFromMarkup(r''' int /*[0*/g/*0]*/ = 1; @@ -559,6 +651,22 @@ int get _z => 0; '''); } + + test_topLevelSetter_noGetter() async { + // Known false negative: a setter is checked only together with an + // undocumented getter with the same name. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +set x(int value) {} +'''); + } + + test_topLevelVariable_docOnDeclaration_ok() async { + await assertNoDiagnostics(r''' +/// Doc. +int x = 0, y = 1; +'''); + } } @reflectiveTest
diff --git a/pkg/linter/test/rules/slash_for_doc_comments_test.dart b/pkg/linter/test/rules/slash_for_doc_comments_test.dart index 9407c61..39eee8b 100644 --- a/pkg/linter/test/rules/slash_for_doc_comments_test.dart +++ b/pkg/linter/test/rules/slash_for_doc_comments_test.dart
@@ -60,6 +60,15 @@ '''); } + test_extensionType() async { + // Known false negative: extension type declarations are not visited. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +/** A. */ +extension type A(int it) {} +'''); + } + test_field() async { await assertDiagnosticsFromMarkup(r''' class C { @@ -69,6 +78,15 @@ '''); } + test_getter() async { + await assertDiagnosticsFromMarkup(r''' +class A { + [!/** g */!] + int get g => 0; +} +'''); + } + test_library() async { await assertDiagnosticsFromMarkup(r''' [!/** l */!] @@ -131,6 +149,15 @@ '''); } + test_operator() async { + await assertDiagnosticsFromMarkup(r''' +class A { + [!/** + */!] + A operator +(A other) => this; +} +'''); + } + test_primaryConstructorBody() async { await assertDiagnosticsFromMarkup(r''' class C() { @@ -140,6 +167,15 @@ '''); } + test_setter() async { + await assertDiagnosticsFromMarkup(r''' +class A { + [!/** s */!] + set s(int value) {} +} +'''); + } + test_threeSlashes_class() async { await assertNoDiagnostics(r''' /// OK @@ -154,6 +190,20 @@ '''); } + test_topLevelGetter() async { + await assertDiagnosticsFromMarkup(r''' +[!/** g */!] +int get g => 0; +'''); + } + + test_topLevelSetter() async { + await assertDiagnosticsFromMarkup(r''' +[!/** s */!] +set s(int value) {} +'''); + } + test_topLevelVariable() async { await assertDiagnosticsFromMarkup(r''' [!/** x */!]
diff --git a/pkg/linter/test/rules/sort_child_properties_last_test.dart b/pkg/linter/test/rules/sort_child_properties_last_test.dart index f1fa505..7cca86e 100644 --- a/pkg/linter/test/rules/sort_child_properties_last_test.dart +++ b/pkg/linter/test/rules/sort_child_properties_last_test.dart
@@ -20,6 +20,19 @@ @override String get lintRule => LintNames.sort_child_properties_last; + test_annotation() async { + await assertNoDiagnostics(r''' +import 'package:flutter/widgets.dart'; +class W extends StatelessWidget { + final Widget? child; + final int? x; + const W({this.child, this.x}); +} +@W(child: Text(''), x: 0) +void f() {} +'''); + } + test_childArgumentBeforeKeyArgument() async { await assertDiagnosticsFromMarkup(r''' import 'package:flutter/widgets.dart';
diff --git a/pkg/linter/test/rules/specify_nonobvious_local_variable_types_test.dart b/pkg/linter/test/rules/specify_nonobvious_local_variable_types_test.dart index e765cf4..821af3c 100644 --- a/pkg/linter/test/rules/specify_nonobvious_local_variable_types_test.dart +++ b/pkg/linter/test/rules/specify_nonobvious_local_variable_types_test.dart
@@ -308,6 +308,228 @@ '''); } + test_nonObviousType_constructor_rawGeneric() async { + await assertDiagnosticsFromMarkup(r''' +class A<T> {} +void f() { + [!var x = A()!]; + x; +} +'''); + } + + test_nonObviousType_hashCode_importPrefix() async { + // Known false negative: any `x.hashCode` is treated as obvious by name, + // so a top-level getter `hashCode` read through an import prefix is not + // reported. + // See https://github.com/dart-lang/sdk/issues/65178. + newFile('$testPackageLibPath/a.dart', r''' +int get hashCode => 1; +'''); + await assertNoDiagnostics(r''' +import 'a.dart' as a; + +void f() { + var x = a.hashCode; + x; +} +'''); + } + + test_nonObviousType_negativeVariable() async { + await assertDiagnosticsFromMarkup(r''' +void f(int a) { + [!var x = -a!]; + x; +} +'''); + } + + test_nonObviousType_recordNamedField() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + [!var x = (a: 1)!]; + x; +} +'''); + } + + test_nonObviousType_toString_importPrefix() async { + // Known false negative: any `x.toString()` is treated as obvious by name, + // so a top-level function `toString` invoked through an import prefix is + // not reported. + // See https://github.com/dart-lang/sdk/issues/65178. + newFile('$testPackageLibPath/a.dart', r''' +String toString() => ''; +'''); + await assertNoDiagnostics(r''' +import 'a.dart' as a; + +void f() { + var x = a.toString(); + x; +} +'''); + } + + test_obviousType_conditional() async { + await assertNoDiagnostics(r''' +void f(bool b) { + var x = b ? 1 : 2; + x; +} +'''); + } + + test_obviousType_constructor_nonGeneric() async { + await assertNoDiagnostics(r''' +class A {} +void f() { + var x = A(); + x; +} +'''); + } + + test_obviousType_constructor_typeArguments() async { + await assertNoDiagnostics(r''' +class A<T> {} +void f() { + var x = A<int>(); + x; +} +'''); + } + + test_obviousType_equality() async { + await assertNoDiagnostics(r''' +void f(int a) { + var x = a == 1; + x; +} +'''); + } + + test_obviousType_hashCode_receiver() async { + await assertNoDiagnostics(r''' +void f(int a) { + var x = a.hashCode; + x; +} +'''); + } + + test_obviousType_inequality() async { + await assertNoDiagnostics(r''' +void f(int a) { + var x = a != 1; + x; +} +'''); + } + + test_obviousType_list_ifElement() async { + await assertNoDiagnostics(r''' +void f(bool b) { + var x = [if (b) 1]; + x; +} +'''); + } + + test_obviousType_list_spread() async { + await assertNoDiagnostics(r''' +void f() { + var x = [...[1]]; + x; +} +'''); + } + + test_obviousType_map() async { + await assertNoDiagnostics(r''' +void f() { + var x = {1: 2}; + x; +} +'''); + } + + test_obviousType_negativeDouble() async { + await assertNoDiagnostics(r''' +void f() { + var x = -1.0; + x; +} +'''); + } + + test_obviousType_negativeInt() async { + await assertNoDiagnostics(r''' +void f() { + var x = -1; + x; +} +'''); + } + + test_obviousType_parameter() async { + await assertNoDiagnostics(r''' +void f(int a) { + var x = a; + x; +} +'''); + } + + test_obviousType_toString_receiver() async { + await assertNoDiagnostics(r''' +void f(int a) { + var x = a.toString(); + x; +} +'''); + } + + test_obviousType_toString_unqualified() async { + await assertNoDiagnostics(r''' +class A { + void m() { + var x = toString(); + x; + } +} +'''); + } + + test_pattern_caseInIfStatementInSwitchBody() async { + // Reported only because the switch statement case visitor descends into + // the case body; see `test_pattern_ifCase` for the same `if-case` outside + // of a switch. + await assertDiagnosticsFromMarkup(r''' +void f(Object o) { + switch (o) { + case int(): + if (o case [!var a!]) { + a; + } + } +} +'''); + } + + test_pattern_ifCase() async { + // Known false negative: `if-case` statements are not visited. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +void f(Object o) { + if (o case var a) { + a; + } +} +'''); + } + test_pattern_list_destructured() async { await assertNoDiagnostics(r''' f() { @@ -346,6 +568,34 @@ '''); } + test_pattern_recordDeclaration() async { + await assertDiagnosticsFromMarkup(r''' +void f((int, int) r) { + var ([!a!], int b) = r; + a + b; +} +'''); + } + + test_pattern_switchExpression() async { + await assertDiagnosticsFromMarkup(r''' +int f(Object o) => switch (o) { + [!var a!] => a.hashCode, +}; +'''); + } + + test_pattern_switchStatement() async { + await assertDiagnosticsFromMarkup(r''' +void f(Object o) { + switch (o) { + case [!var a!]: + a; + } +} +'''); + } + test_switch_pattern_object() async { await assertNoDiagnostics(r''' class A {
diff --git a/pkg/linter/test/rules/specify_nonobvious_property_types_test.dart b/pkg/linter/test/rules/specify_nonobvious_property_types_test.dart index b1a5ae0..ac9dd11 100644 --- a/pkg/linter/test/rules/specify_nonobvious_property_types_test.dart +++ b/pkg/linter/test/rules/specify_nonobvious_property_types_test.dart
@@ -376,6 +376,31 @@ '''); } + test_late_instance_range() async { + await assertDiagnosticsFromMarkup(r''' +class A { + [!late var a = f()!]; +} +int f() => 1; +'''); + } + + test_late_static_range() async { + await assertDiagnosticsFromMarkup(r''' +class A { + static [!late final a = f()!]; +} +int f() => 1; +'''); + } + + test_late_topLevel_range() async { + await assertDiagnosticsFromMarkup(r''' +[!late var a = f()!]; +int f() => 1; +'''); + } + test_literal_bool_instance() async { await assertNoDiagnostics(r''' class A {
diff --git a/pkg/linter/test/rules/type_annotate_public_apis_test.dart b/pkg/linter/test/rules/type_annotate_public_apis_test.dart index da2774e2..e1cbe92 100644 --- a/pkg/linter/test/rules/type_annotate_public_apis_test.dart +++ b/pkg/linter/test/rules/type_annotate_public_apis_test.dart
@@ -190,6 +190,16 @@ '''); } + test_instanceConstructor_fieldFormalParameter_nestedParameterMissingType() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.14 +class A { + void Function(int) f; + A(void this.f([!x!])); +} +'''); + } + test_instanceConstructor_namedParameterHasType() async { await assertNoDiagnostics(r''' class A {
diff --git a/pkg/linter/test/rules/unawaited_futures_test.dart b/pkg/linter/test/rules/unawaited_futures_test.dart index cc1f6f4..81cd2de 100644 --- a/pkg/linter/test/rules/unawaited_futures_test.dart +++ b/pkg/linter/test/rules/unawaited_futures_test.dart
@@ -45,6 +45,21 @@ '''); } + Future<void> test_binaryOperator_awaitNotRequired() async { + await assertNoDiagnostics(r''' +import 'package:meta/meta.dart'; + +class C { + @awaitNotRequired + Future<int> operator +(int other) async => 1; +} + +Future<void> f(C c) async { + c + 1; +} +'''); + } + test_boundToFuture_unawaited() async { await assertNoDiagnostics(r''' void f<T extends Future<void>>(T p) async { @@ -262,6 +277,18 @@ '''); } + Future<void> test_getter_unqualified() async { + await assertDiagnosticsFromMarkup(r''' +class C { + Future<int> get g async => 1; + + Future<void> f() async { + [!g!]; + } +} +'''); + } + test_instanceProperty_unawaited() async { await assertDiagnosticsFromMarkup(r''' void f(C c) async { @@ -357,6 +384,43 @@ '''); } + Future<void> test_prefixIncrement() async { + await assertDiagnosticsFromMarkup(r''' +class A { + Future<A> operator +(int other) async => this; +} + +class B { + A get p => A(); + set p(Future<A> v) {} +} + +Future<void> f(B b) async { + [!++b.p!]; +} +'''); + } + + Future<void> test_prefixIncrement_awaitNotRequired() async { + await assertNoDiagnostics(r''' +import 'package:meta/meta.dart'; + +class A { + @awaitNotRequired + Future<A> operator +(int other) async => this; +} + +class B { + A get p => A(); + set p(Future<A> v) {} +} + +Future<void> f(B b) async { + ++b.p; +} +'''); + } + test_typeDef() async { await assertDiagnosticsFromMarkup(r''' typedef T = Future<void>; @@ -366,6 +430,21 @@ '''); } + Future<void> test_unaryOperator_awaitNotRequired() async { + await assertNoDiagnostics(r''' +import 'package:meta/meta.dart'; + +class C { + @awaitNotRequired + Future<int> operator -() async => 1; +} + +Future<void> f(C c) async { + -c; +} +'''); + } + test_undefinedIdentifier() async { await assertDiagnostics( r'''
diff --git a/pkg/linter/test/rules/unnecessary_async_test.dart b/pkg/linter/test/rules/unnecessary_async_test.dart index 82987f3..7d0ad74 100644 --- a/pkg/linter/test/rules/unnecessary_async_test.dart +++ b/pkg/linter/test/rules/unnecessary_async_test.dart
@@ -68,6 +68,22 @@ '''); } + test_getter_future_returnFuture() async { + await assertDiagnosticsFromMarkup(r''' +class A { + Future<int> get g [!async!] => Future.value(0); +} +'''); + } + + test_getter_void_noAwait() async { + await assertDiagnosticsFromMarkup(r''' +class A { + void get g [!async!] {} +} +'''); + } + test_localFunction_void_hasAwait() async { await assertNoDiagnostics(r''' void foo() { @@ -157,6 +173,25 @@ '''); } + test_operator_future_returnFuture() async { + await assertDiagnosticsFromMarkup(r''' +class A { + Future<int> operator +(int other) [!async!] => Future.value(0); +} +'''); + } + + test_setter_noAwait() async { + await assertDiagnostics( + r''' +class A { + set s(int v) async {} +} +''', + [error(diag.invalidModifierOnSetter, 25, 5), lint(25, 5)], + ); + } + test_topLevelFunction_block_future_intNullable_returnNullable() async { await assertNoDiagnostics(r''' Future<int?> f(int? x) async { @@ -196,6 +231,16 @@ '''); } + test_topLevelFunction_blockBody_future_int_returnFuture_nestedLocalFunction() async { + await assertDiagnosticsFromMarkup(r''' +Future<int> f() [!async!] { + int g() => 0; + g(); + return Future.value(0); +} +'''); + } + test_topLevelFunction_blockBody_future_int_returnValue() async { await assertNoDiagnostics(r''' Future<int> f() async { @@ -397,6 +442,18 @@ '''); } + test_topLevelFunction_blockBody_void_hasAwait_nestedLocalFunction() async { + await assertDiagnosticsFromMarkup(r''' +void f() [!async!] { + void g() async { + await 0; + } + + g(); +} +'''); + } + test_topLevelFunction_blockBody_void_noAwait() async { await assertDiagnosticsFromMarkup(r''' void f() [!async!] {} @@ -444,4 +501,13 @@ int get value => 0; '''); } + + test_topLevelSetter_noAwait() async { + await assertDiagnostics( + r''' +set s(int v) async {} +''', + [error(diag.invalidModifierOnSetter, 13, 5), lint(13, 5)], + ); + } }
diff --git a/pkg/linter/test/rules/unnecessary_await_in_return_test.dart b/pkg/linter/test/rules/unnecessary_await_in_return_test.dart index 77b0caa..cf49c40 100644 --- a/pkg/linter/test/rules/unnecessary_await_in_return_test.dart +++ b/pkg/linter/test/rules/unnecessary_await_in_return_test.dart
@@ -93,6 +93,16 @@ '''); } + test_asyncBlock_awaited_getter() async { + await assertDiagnosticsFromMarkup(r''' +class A { + Future<int> get g async { + return [!await!] Future.value(1); + } +} +'''); + } + test_asyncBlock_awaited_instanceMethod() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -132,6 +142,50 @@ '''); } + test_asyncBlock_awaited_localFunction() async { + await assertDiagnosticsFromMarkup(r''' +void f() { + Future<int> g() async { + return [!await!] Future.value(1); + } + + g(); +} +'''); + } + + test_asyncBlock_awaited_localFunction_inTry() async { + await assertDiagnosticsFromMarkup(r''' +Future<void> f() async { + try { + Future<int> g() async { + return [!await!] Future.value(1); + } + + g(); + } finally {} +} +'''); + } + + test_asyncBlock_awaited_operator() async { + await assertDiagnosticsFromMarkup(r''' +class A { + Future<int> operator +(int other) async { + return [!await!] Future.value(1); + } +} +'''); + } + + test_asyncBlock_awaited_topLevelGetter() async { + await assertDiagnosticsFromMarkup(r''' +Future<int> get g async { + return [!await!] Future.value(1); +} +'''); + } + test_asyncBlock_notAwaited() async { await assertNoDiagnostics(r''' Future<int> f() async {
diff --git a/pkg/linter/test/rules/unnecessary_nullable_for_final_variable_declarations_test.dart b/pkg/linter/test/rules/unnecessary_nullable_for_final_variable_declarations_test.dart index a37964b..d6397b9 100644 --- a/pkg/linter/test/rules/unnecessary_nullable_for_final_variable_declarations_test.dart +++ b/pkg/linter/test/rules/unnecessary_nullable_for_final_variable_declarations_test.dart
@@ -18,6 +18,16 @@ String get lintRule => LintNames.unnecessary_nullable_for_final_variable_declarations; + test_forLoopVariable_nullableType() async { + // Known false negative: `for` loop variable declarations are not visited. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +void f() { + for (final int? a = 1; a != 2;) {} +} +'''); + } + test_list() async { await assertDiagnosticsFromMarkup(r''' f() {
diff --git a/pkg/linter/test/rules/unnecessary_overrides_test.dart b/pkg/linter/test/rules/unnecessary_overrides_test.dart index 9904db8..23ced39 100644 --- a/pkg/linter/test/rules/unnecessary_overrides_test.dart +++ b/pkg/linter/test/rules/unnecessary_overrides_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -71,6 +72,21 @@ '''); } + test_getter_blockBody_superCall() async { + await assertDiagnosticsFromMarkup(r''' +class A { + int get x => 0; +} + +class B extends A { + @override + int get [!x!] { + return super.x; + } +} +'''); + } + test_getter_expressionFunctionBody_otherTarget() async { await assertNoDiagnostics(r''' class A { @@ -108,6 +124,36 @@ '''); } + test_getter_static() async { + await assertDiagnostics( + r''' +class A { + int get x => 0; +} + +class B extends A { + static int get x => super.x; +} +''', + [ + error(diag.conflictingStaticAndInstance, 68, 1), + error(diag.superInInvalidContext, 73, 5), + ], + ); + } + + test_getter_static_bothStatic() async { + await assertNoDiagnostics(r''' +class A { + static int get x => 0; +} + +class B extends A { + static int get x => A.x; +} +'''); + } + test_method_blockBody() async { await assertDiagnosticsFromMarkup(r''' class A { @@ -405,6 +451,38 @@ '''); } + test_method_static() async { + await assertDiagnostics( + r''' +class A { + void m() {} +} + +class B extends A { + static void m() { + super.m(); + } +} +''', + [ + error(diag.conflictingStaticAndInstance, 61, 1), + error(diag.superInInvalidContext, 71, 5), + ], + ); + } + + test_method_static_unrelatedClass() async { + await assertNoDiagnostics(r''' +class A { + void m() {} +} + +class B { + static void m() {} +} +'''); + } + test_noSuchMethod() async { await assertNoDiagnostics(r''' class A {} @@ -453,6 +531,42 @@ '''); } + test_setter_compoundAssignment() async { + // Known false positive: the assignment operator is not checked, so + // `super.x += value` is treated like forwarding `super.x = value`. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnostics( + r''' +class A { + int x = 0; +} + +class B extends A { + @override + set x(int value) { + super.x += value; + } +} +''', + [lint(64, 1)], + ); + } + + test_setter_compoundAssignment_parameterRenamed() async { + await assertNoDiagnostics(r''' +class A { + int x = 0; +} + +class B extends A { + @override + set x(int v) { + super.x += v; + } +} +'''); + } + test_setter_expressionFunctionBody_otherTarget() async { await assertNoDiagnostics(r''' class A { @@ -466,6 +580,42 @@ '''); } + test_setter_ifNullAssignment() async { + // Known false positive: the assignment operator is not checked, so + // `super.x ??= value` is treated like forwarding `super.x = value`. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnostics( + r''' +class A { + int? x; +} + +class B extends A { + @override + set x(int? value) { + super.x ??= value; + } +} +''', + [lint(61, 1)], + ); + } + + test_setter_ifNullAssignment_parameterRenamed() async { + await assertNoDiagnostics(r''' +class A { + int? x; +} + +class B extends A { + @override + set x(int? v) { + super.x ??= v; + } +} +'''); + } + test_setter_parameterRenamed() async { await assertNoDiagnostics(r''' class A { @@ -490,6 +640,20 @@ '''); } + test_setter_static() async { + await assertNoDiagnostics(r''' +class A { + static set x(int v) {} +} + +class B extends A { + static set x(int v) { + A.x = v; + } +} +'''); + } + test_unaryOperator_expressionFunctionBody() async { await assertDiagnosticsFromMarkup(r''' class A {
diff --git a/pkg/linter/test/rules/unnecessary_unawaited_test.dart b/pkg/linter/test/rules/unnecessary_unawaited_test.dart index aa8c349..9355a2b 100644 --- a/pkg/linter/test/rules/unnecessary_unawaited_test.dart +++ b/pkg/linter/test/rules/unnecessary_unawaited_test.dart
@@ -46,6 +46,15 @@ '''); } + test_dotShorthand_ok() async { + await assertNoDiagnostics(r''' +import 'dart:async'; +void f() { + unawaited(.wait([])); +} +'''); + } + test_function_annotated() async { await assertDiagnosticsFromMarkup(r''' import 'dart:async'; @@ -68,6 +77,67 @@ '''); } + test_getter_annotated() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; +import 'package:meta/meta.dart'; +void f(C c) { + [!unawaited!](c.g); +} +class C { + @awaitNotRequired + Future<void> get g => Future.value(); +} +'''); + } + + test_getter_nested_annotated() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; +import 'package:meta/meta.dart'; +void f(D d) { + [!unawaited!](d.c.g); +} +class C { + @awaitNotRequired + Future<void> get g => Future.value(); +} +class D { + C get c => C(); +} +'''); + } + + test_importPrefixedFunction_annotated() async { + newFile('$testPackageLibPath/a.dart', r''' +import 'package:meta/meta.dart'; +@awaitNotRequired +Future<void> f2() => Future.value(); +'''); + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; +import 'a.dart' as a; +void f() { + [!unawaited!](a.f2()); +} +'''); + } + + test_importPrefixedGetter_annotated() async { + newFile('$testPackageLibPath/a.dart', r''' +import 'package:meta/meta.dart'; +@awaitNotRequired +Future<void> get g => Future.value(); +'''); + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; +import 'a.dart' as a; +void f() { + [!unawaited!](a.g); +} +'''); + } + test_method_annotated() async { await assertDiagnosticsFromMarkup(r''' import 'dart:async'; @@ -94,6 +164,34 @@ '''); } + test_postfixIncrement_annotated_ok() async { + await assertNoDiagnostics(r''' +import 'dart:async'; +import 'package:meta/meta.dart'; +void f(C c) { + unawaited(c++); +} +abstract class C implements Future<void> { + @awaitNotRequired + C operator +(int i) => this; +} +'''); + } + + test_prefixIncrement_annotated() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:async'; +import 'package:meta/meta.dart'; +void f(C c) { + [!unawaited!](++c); +} +abstract class C implements Future<void> { + @awaitNotRequired + C operator +(int i) => this; +} +'''); + } + test_topLevelVariable_annotated() async { await assertDiagnosticsFromMarkup(r''' import 'dart:async';
diff --git a/pkg/linter/test/rules/unnecessary_underscores_test.dart b/pkg/linter/test/rules/unnecessary_underscores_test.dart index 3e660a7..1577c04 100644 --- a/pkg/linter/test/rules/unnecessary_underscores_test.dart +++ b/pkg/linter/test/rules/unnecessary_underscores_test.dart
@@ -17,6 +17,22 @@ @override String get lintRule => 'unnecessary_underscores'; + test_closure_parameter_unused() async { + await assertDiagnosticsFromMarkup(r''' +var f = (int [!__!]) {}; +'''); + } + + test_closure_parameter_used() async { + // Known false positive: closure bodies are not searched for references. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnosticsFromMarkup(r''' +var f = (int [!__!]) { + print(__); +}; +'''); + } + test_commentReferenceFunction() async { await assertNoDiagnostics(''' /// This is a reference to [__]. @@ -42,6 +58,24 @@ '''); } + test_constructor_parameter_unused() async { + await assertDiagnosticsFromMarkup(r''' +class C { + C(int [!__!]); +} +'''); + } + + test_constructor_parameter_used() async { + await assertNoDiagnostics(r''' +class C { + C(int __) { + print(__); + } +} +'''); + } + test_enum_field_unused() async { await assertNoDiagnostics(r''' enum E { @@ -65,6 +99,15 @@ '''); } + test_forIn_target_used() async { + await assertNoDiagnostics(r''' +void f() { + int __ = 0; + for (__ in [1]) {} +} +'''); + } + test_forPart_unused() async { await assertDiagnosticsFromMarkup(r''' void f() { @@ -103,6 +146,21 @@ '''); } + test_functionType_parameter() async { + await assertDiagnosticsFromMarkup(r''' +typedef F = void Function(int [!__!]); +'''); + } + + test_local_assigned() async { + await assertNoDiagnostics(r''' +void f() { + int __ = 0; + __ = 1; +} +'''); + } + test_local_unused() async { await assertDiagnosticsFromMarkup(r''' void f() { @@ -146,6 +204,16 @@ '''); } + test_method_parameter_used() async { + await assertNoDiagnostics(r''' +class C { + void m(int __) { + print(__); + } +} +'''); + } + test_method_unused() async { await assertNoDiagnostics(r''' class A { @@ -154,6 +222,22 @@ '''); } + test_operator_parameter_unused() async { + await assertDiagnosticsFromMarkup(r''' +class C { + int operator +(int [!__!]) => 0; +} +'''); + } + + test_operator_parameter_used() async { + await assertNoDiagnostics(r''' +class C { + int operator +(int __) => __; +} +'''); + } + test_parameter_declaring_unused() async { await assertNoDiagnostics(r''' // ignore: unused_field_from_primary_constructor @@ -161,12 +245,54 @@ '''); } + test_primaryConstructor_parameter_used() async { + await assertNoDiagnostics(r''' +class C(int __) { + this { + print(__); + } +} +'''); + } + + test_setter_parameter_unused() async { + await assertDiagnosticsFromMarkup(r''' +class C { + set s(int [!__!]) {} +} +'''); + } + + test_setter_parameter_used() async { + await assertNoDiagnostics(r''' +class C { + set s(int __) { + print(__); + } +} +'''); + } + test_topLevelFunction_unused() async { await assertNoDiagnostics(r''' __() {} '''); } + test_topLevelSetter_parameter_unused() async { + await assertDiagnosticsFromMarkup(r''' +set s(int [!__!]) {} +'''); + } + + test_topLevelSetter_parameter_used() async { + await assertNoDiagnostics(r''' +set s(int __) { + print(__); +} +'''); + } + test_topLevelVariable_unused() async { await assertNoDiagnostics(r''' int __ = 0;
diff --git a/pkg/linter/test/rules/unreachable_from_main_test.dart b/pkg/linter/test/rules/unreachable_from_main_test.dart index cb11099..a5ce339 100644 --- a/pkg/linter/test/rules/unreachable_from_main_test.dart +++ b/pkg/linter/test/rules/unreachable_from_main_test.dart
@@ -27,6 +27,19 @@ @override String get lintRule => LintNames.unreachable_from_main; + test_class_instanceField_reachable_initializedInConstructor() async { + await assertNoDiagnostics(r''' +void main() { + C(); +} + +class C { + int? f; + C() : f = 0; +} +'''); + } + test_class_instanceField_reachable_matchedInPattern() async { await assertNoDiagnostics(r''' void main() { @@ -304,6 +317,20 @@ '''); } + test_class_reachable_referencedInTypeAnnotation_externalGetterDeclaration() async { + await assertDiagnosticsFromMarkup(r''' +void main() { + D(); +} + +class C {} + +class D { + external C get [!c!]; +} +'''); + } + test_class_reachable_referencedInTypeAnnotation_externalMethodDeclaration() async { await assertNoDiagnostics(r''' void main() { @@ -624,6 +651,21 @@ ]); } + test_classTypeAlias_unreachable() async { + await assertDiagnostics( + r''' +void main() {} + +class A {} + +mixin M {} + +class B = A with M; +''', + [lint(22, 1), lint(34, 1), lint(46, 1)], + ); + } + test_constructor_named_new() async { // https://github.com/dart-lang/sdk/issues/63425 await assertDiagnosticsFromMarkup(r''' @@ -665,6 +707,19 @@ '''); } + test_constructor_named_reachableViaDotShorthand() async { + await assertNoDiagnostics(r''' +class C { + C.named(); +} + +void main() { + C c = .named(); + c; +} +'''); + } + test_constructor_named_reachableViaExplicitSuperCall() async { await assertNoDiagnostics(r''' void main() { @@ -1111,6 +1166,18 @@ '''); } + test_instanceGetter_reachable_toJson() async { + await assertNoDiagnostics(r''' +void main() { + C(); +} + +class C { + int get toJson => 0; +} +'''); + } + test_instanceMethod_reachable_toJson() async { await assertNoDiagnostics(r''' import 'dart:convert'; @@ -1125,6 +1192,21 @@ '''); } + test_instanceSetter_reachable_toJson() async { + // Known false negative: any instance member named `toJson` is treated as + // reachable, but `dart:convert` never invokes a setter. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertNoDiagnostics(r''' +void main() { + C(); +} + +class C { + set toJson(int value) {} +} +'''); + } + test_mixin_reachable_implemented() async { await assertNoDiagnostics(r''' void main() { @@ -1157,6 +1239,22 @@ '''); } + test_operator_compoundAssignment_notCounted() async { + // Known false positive: the compound assignment `c += 1` invokes `+`, but + // is not counted as a reference to it. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnosticsFromMarkup(r''' +void main() { + var c = C(); + c += 1; +} + +class C { + C operator [!+!](int other) => this; +} +'''); + } + test_operator_index() async { await assertNoDiagnostics(r''' void main() { @@ -1253,6 +1351,21 @@ '''); } + test_staticField_reachable_viaStaticQualifierInComment() async { + await assertNoDiagnostics(r''' +void main() { + C(); +} + +/// [D.f] +class C {} + +class D { + static int f = 0; +} +'''); + } + test_staticField_unreachable() async { await assertDiagnosticsFromMarkup(r''' void main() { @@ -1339,6 +1452,19 @@ '''); } + test_staticGetter_reachable_dotShorthand() async { + await assertNoDiagnostics(r''' +class C { + static C get g => C(); +} + +void main() { + C c = .g; + c; +} +'''); + } + test_staticGetter_unreachable() async { await assertDiagnosticsFromMarkup(r''' void main() { @@ -1351,6 +1477,19 @@ '''); } + test_staticMethod_reachable_dotShorthand() async { + await assertNoDiagnostics(r''' +class C { + static C m() => C(); +} + +void main() { + C c = .m(); + c; +} +'''); + } + test_staticMethod_unreachable() async { await assertDiagnosticsFromMarkup(r''' void main() { @@ -1544,6 +1683,26 @@ '''); } + test_topLevelGetter_vmEntryPoint() async { + await assertNoDiagnostics(r''' +void main() {} + +@pragma('vm:entry-point') +int get g => f(); + +int f() => 0; +'''); + } + + test_topLevelGetter_vmEntryPoint_noMain() async { + await assertNoDiagnostics(r''' +@pragma('vm:entry-point') +int get g => f(); + +int f() => 0; +'''); + } + test_topLevelSetter_reachable() async { await assertNoDiagnostics(r''' void main() { @@ -1562,6 +1721,30 @@ '''); } + test_topLevelSetter_vmEntryPoint() async { + await assertNoDiagnostics(r''' +void main() {} + +@pragma('vm:entry-point') +set s(int value) { + f(); +} + +void f() {} +'''); + } + + test_topLevelSetter_vmEntryPoint_noMain() async { + await assertNoDiagnostics(r''' +@pragma('vm:entry-point') +set s(int value) { + f(); +} + +void f() {} +'''); + } + test_topLevelVariable_reachable() async { await assertNoDiagnostics(r''' void main() { @@ -1576,6 +1759,16 @@ '''); } + test_topLevelVariable_reachable_forInTarget() async { + await assertNoDiagnostics(r''' +int x = 0; + +void main() { + for (x in [1]) {} +} +'''); + } + test_topLevelVariable_unreachable() async { await assertDiagnosticsFromMarkup(r''' void main() {}
diff --git a/pkg/linter/test/rules/unsafe_variance_test.dart b/pkg/linter/test/rules/unsafe_variance_test.dart index 8cadbf0..f9ff9c1 100644 --- a/pkg/linter/test/rules/unsafe_variance_test.dart +++ b/pkg/linter/test/rules/unsafe_variance_test.dart
@@ -25,6 +25,20 @@ '''); } + test_class_localVariable() async { + // Known false positive: a local variable is not an instance member, but + // every variable declaration list is checked. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnosticsFromMarkup(r''' +class A<T> { + void m(void Function(T) p) { + void Function([!T!]) v = p; + v; + } +} +'''); + } + test_class_method_bound() async { await assertDiagnosticsFromMarkup(r''' class A<X> { @@ -59,6 +73,14 @@ '''); } + test_class_operator_return() async { + await assertDiagnosticsFromMarkup(r''' +class A<T> { + void Function([!T!]) operator +(int other) => throw 0; +} +'''); + } + test_class_variable() async { await assertDiagnosticsFromMarkup(r''' class A<X> {
diff --git a/pkg/linter/test/rules/use_build_context_synchronously_test.dart b/pkg/linter/test/rules/use_build_context_synchronously_test.dart index 813e4b0..27863ff 100644 --- a/pkg/linter/test/rules/use_build_context_synchronously_test.dart +++ b/pkg/linter/test/rules/use_build_context_synchronously_test.dart
@@ -2162,6 +2162,72 @@ @override String get testPackageRootPath => '$workspaceRootPath/lib'; + test_argument_parenthesized() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + await c(); + g([!(context)!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_argument_parenthesized_guarded() async { + await assertNoDiagnostics(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + await c(); + if (!context.mounted) return; + g((context)); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_argument_thisContext() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +abstract class C extends State<StatefulWidget> { + void f() async { + await c(); + g([!this.context!]); + } +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_argument_thisContext_guarded() async { + await assertNoDiagnostics(r''' +import 'package:flutter/widgets.dart'; + +abstract class C extends State<StatefulWidget> { + void f() async { + await c(); + if (!mounted) return; + g(this.context); + } +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + test_assignmentExpressionContainsMountedCheck_thenReferenceToContext() async { // Assignment statement-expression with mounted check, then use of // BuildContext in if-then statement, is REPORTED. @@ -2495,6 +2561,159 @@ '''); } + test_awaitInBinaryOperatorInvocation_left() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + (await c()) + 1; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInCallInvocation_argument() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, void Function(int) h) async { + h(await c()); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInCascadeIndexAssignmentTarget() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, List<int> list) async { + list..[await c()] = 1; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInCascadeIndexExpression() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, List<int> list) async { + list..[await c()]; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInCascadeMethodInvocation() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, A a) async { + a..m(await c()); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +class A { + int x = 0; + int operator [](int i) => 0; + void operator []=(int i, int v) {} + void m(int i) {} +} +'''); + } + + test_awaitInCascadePropertyAssignment() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, A a) async { + a..x = await c(); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +class A { + int x = 0; + int operator [](int i) => 0; + void operator []=(int i, int v) {} + void m(int i) {} +} +'''); + } + + test_awaitInCompoundAssignment() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, int i) async { + i += await c(); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInConstructorInvocation() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + Duration(days: await c()); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInExtensionOverride() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + E(await c()).m(); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +extension E on int { + void m() {} +} +'''); + } + test_awaitInIfCondition_expressionContainsReferenceToContext() async { // Await expression contains use of BuildContext, is OK. await assertNoDiagnostics(r''' @@ -2509,6 +2728,53 @@ '''); } + test_awaitInIfNull_left() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + (await n()) ?? 0; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +Future<int?> n() async => 0; +'''); + } + + test_awaitInIfNull_right() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, int? i) async { + i ?? await c(); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInIfNullAssignment() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, int? i) async { + i ??= await c(); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + test_awaitInIfThenAndExitInElse_beforeReferenceToContext() async { // Await in an if-body and await-and-exit in the associated else, then use // of BuildContext, is REPORTED. @@ -2528,6 +2794,204 @@ '''); } + test_awaitInImportPrefixedFunctionInvocation() async { + await assertDiagnosticsFromMarkup(r''' +import 'dart:math' as math; + +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + math.max(await c(), 1); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInIncrement_postfix() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, List<int> list) async { + list[await c()]++; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInNullAssertion() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + (await n())!; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +Future<int?> n() async => 0; +'''); + } + + test_awaitInReceiverIndexAssignmentTarget_index() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, List<int> list) async { + list[await c()] = 1; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInReceiverIndexAssignmentTarget_receiver() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + (await a())[0] = 1; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +Future<A> a() async => A(); + +class A { + int x = 0; + int operator [](int i) => 0; + void operator []=(int i, int v) {} + void m(int i) {} +} +'''); + } + + test_awaitInReceiverIndexExpression_index() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, List<int> list) async { + list[await c()]; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInReceiverIndexExpression_receiver() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + (await a())[0]; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +Future<A> a() async => A(); + +class A { + int x = 0; + int operator [](int i) => 0; + void operator []=(int i, int v) {} + void m(int i) {} +} +'''); + } + + test_awaitInReceiverMethodInvocation_receiver() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + (await c()).toString(); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInReceiverPropertyAssignmentTarget() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + (await a()).x = 1; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +Future<A> a() async => A(); + +class A { + int x = 0; + int operator [](int i) => 0; + void operator []=(int i, int v) {} + void m(int i) {} +} +'''); + } + + test_awaitInReceiverPropertyExtraction() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + (await c()).isEven; + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_awaitInUnqualifiedFunctionInvocation() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + h(await c()); + g([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +void h(int i) {} +'''); + } + /// https://github.com/dart-lang/linter/issues/3818 test_context_propertyAccess() async { await assertDiagnosticsFromMarkup(r''' @@ -2547,6 +3011,100 @@ '''); } + test_contextInAnnotation() async { + await assertDiagnostics( + r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + await c(); + @B(context) + var x = 0; + x; +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +class B { + const B(Object o); +} +''', + [error(diag.constWithNonConstantArgument, 95, 7)], + ); + } + + test_contextInCallInvocation() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, void Function(BuildContext) h) async { + await c(); + h([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_contextInCascadeMethodInvocation() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, B b) async { + await c(); + b..m([!context!]); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +class B { + void m(BuildContext context) {} +} +'''); + } + + test_contextInFutureThen_cascade() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context, Future<int> future) async { + future..then((_) { + g([!context!]); + }); +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} +'''); + } + + test_contextInImportPrefixedFunctionInvocation() async { + newFile('$testPackageLibPath/a.dart', r''' +import 'package:flutter/widgets.dart'; + +void g(BuildContext context) {} +'''); + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +import 'a.dart' as a; + +void f(BuildContext context) async { + await c(); + a.g([!context!]); +} + +Future<int> c() async => 0; +'''); + } + /// https://github.com/dart-lang/linter/issues/3676 test_contextPassedAsNamedParam() async { await assertDiagnosticsFromMarkup(r''' @@ -2796,6 +3354,26 @@ '''); } + test_propertyAccess_compoundAssignment() async { + await assertDiagnosticsFromMarkup(r''' +import 'package:flutter/widgets.dart'; + +void f(BuildContext context) async { + await c(); + [!context!].foo += 1; +} + +Future<int> c() async => 0; + +void g(BuildContext context) {} + +extension on BuildContext { + int get foo => 0; + set foo(int x) {} +} +'''); + } + /// https://github.com/dart-lang/linter/issues/3700 test_propertyAccess_getter() async { await assertDiagnosticsFromMarkup(r'''
diff --git a/pkg/linter/test/rules/use_declaring_parameters_test.dart b/pkg/linter/test/rules/use_declaring_parameters_test.dart index baee199..9fe7a5d 100644 --- a/pkg/linter/test/rules/use_declaring_parameters_test.dart +++ b/pkg/linter/test/rules/use_declaring_parameters_test.dart
@@ -17,6 +17,28 @@ @override String get lintRule => LintNames.use_declaring_parameters; + test_assignedInBody_compound() async { + await assertDiagnosticsFromMarkup(r''' +class C(int [!a!]) { + int a = 0; + this { + this.a += a; + } +} +'''); + } + + test_assignedInBody_ifNull() async { + await assertDiagnosticsFromMarkup(r''' +class C(int? [!a!]) { + int? a; + this { + this.a ??= a; + } +} +'''); + } + test_assignedInBody_requiredPositional() async { await assertDiagnosticsFromMarkup(r''' class C(int [!i!]) {
diff --git a/pkg/linter/test/rules/use_function_type_syntax_for_parameters_test.dart b/pkg/linter/test/rules/use_function_type_syntax_for_parameters_test.dart index 0b83cf1..0a52d8a 100644 --- a/pkg/linter/test/rules/use_function_type_syntax_for_parameters_test.dart +++ b/pkg/linter/test/rules/use_function_type_syntax_for_parameters_test.dart
@@ -42,6 +42,18 @@ '''); } + test_classicSyntax_superFormal() async { + await assertDiagnosticsFromMarkup(r''' +// @dart = 3.14 +class A { + A(void Function() f); +} +class B extends A { + B([!void super.f()!]); +} +'''); + } + test_functionTypeSyntax() async { await assertNoDiagnostics(r''' void f2(bool Function(int e) f) {}
diff --git a/pkg/linter/test/rules/use_late_for_private_fields_and_variables_test.dart b/pkg/linter/test/rules/use_late_for_private_fields_and_variables_test.dart index 951f116..31d35eb 100644 --- a/pkg/linter/test/rules/use_late_for_private_fields_and_variables_test.dart +++ b/pkg/linter/test/rules/use_late_for_private_fields_and_variables_test.dart
@@ -222,6 +222,15 @@ '''); } + test_staticField_private_onClass_readByDotShorthand() async { + await assertNoDiagnostics(r''' +class C { + static C? _c; +} +C? f() => ._c; +'''); + } + test_staticField_private_onExtension() async { await assertDiagnosticsFromMarkup(''' extension E on int { @@ -263,6 +272,15 @@ '''); } + test_topLevel_assignedInForEach() async { + await assertNoDiagnostics(''' +int? _i; +void f(List<int?> l) { + for (_i in l) {} +} +'''); + } + test_topLevel_declaredInPart() async { newFile('$testPackageRootPath/lib/lib.dart', ''' part 'test.dart'; @@ -347,6 +365,40 @@ '''); } + test_topLevel_postfixIncrement_nullableOperator() async { + // Known false positive: the variable is written by the user-defined + // operator, which can return `null`, but this write is not counted as + // nullable. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnosticsFromMarkup(''' +extension on int? { + int? operator +(int other) => null; + int? operator -(int other) => null; +} +int? [!_i!]; +void f() { + _i++; +} +'''); + } + + test_topLevel_prefixDecrement_nullableOperator() async { + // Known false positive: the variable is written by the user-defined + // operator, which can return `null`, but this write is not counted as + // nullable. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnosticsFromMarkup(''' +extension on int? { + int? operator +(int other) => null; + int? operator -(int other) => null; +} +int? [!_i!]; +void f() { + --_i; +} +'''); + } + test_topLevel_public() async { await assertNoDiagnostics(''' int? i;
diff --git a/pkg/linter/test/rules/use_setters_to_change_properties_test.dart b/pkg/linter/test/rules/use_setters_to_change_properties_test.dart index 96baecb..b0e3ff3 100644 --- a/pkg/linter/test/rules/use_setters_to_change_properties_test.dart +++ b/pkg/linter/test/rules/use_setters_to_change_properties_test.dart
@@ -103,6 +103,19 @@ '''); } + test_operator() async { + // Known false positive: an operator cannot be replaced with a setter. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnosticsFromMarkup(r''' +class A { + int x = 0; + void operator [!-!](int value) { + x = value; + } +} +'''); + } + test_setterLike_blockBody() async { await assertDiagnosticsFromMarkup(r''' abstract class A {
diff --git a/pkg/linter/test/rules/use_to_and_as_if_applicable_test.dart b/pkg/linter/test/rules/use_to_and_as_if_applicable_test.dart index 453b5d1..75ec504 100644 --- a/pkg/linter/test/rules/use_to_and_as_if_applicable_test.dart +++ b/pkg/linter/test/rules/use_to_and_as_if_applicable_test.dart
@@ -2,6 +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. +import 'package:analyzer/src/diagnostic/diagnostic.dart' as diag; import 'package:test_reflective_loader/test_reflective_loader.dart'; import '../rule_test_support.dart'; @@ -181,6 +182,38 @@ '''); } + test_operator_argumentIsThis() async { + // Known false positive: an operator cannot be renamed to start with `to` + // or `as`. + // See https://github.com/dart-lang/sdk/issues/65178. + await assertDiagnosticsFromMarkup(r''' +class B { + A operator [!-!]() => A.from(this); +} + +class A { + A.from(B _); +} +'''); + } + + test_setter_noParameters() async { + // There is no lint because recovery adds a synthetic formal parameter to + // a setter without formal parameters, so the method has one. + await assertDiagnostics( + r''' +class B { + set x() => A.from(this); +} + +class A { + A.from(B _); +} +''', + [error(diag.wrongNumberOfParametersForSetter, 16, 1)], + ); + } + test_toOther_argumentIsThis() async { await assertNoDiagnostics(r''' class B {
diff --git a/runtime/vm/class_finalizer.cc b/runtime/vm/class_finalizer.cc index 129810f..71f37b0 100644 --- a/runtime/vm/class_finalizer.cc +++ b/runtime/vm/class_finalizer.cc
@@ -9,6 +9,7 @@ #include "vm/bytecode_reader.h" #include "vm/canonical_tables.h" +#include "vm/class_id.h" #include "vm/closure_functions_cache.h" #include "vm/compiler/jit/compiler.h" #include "vm/flags.h" @@ -18,6 +19,7 @@ #include "vm/kernel_loader.h" #include "vm/log.h" #include "vm/longjump.h" +#include "vm/object.h" #include "vm/object_store.h" #include "vm/program_visitor.h" #include "vm/runtime_entry.h" @@ -598,6 +600,7 @@ MarkClassCanBeFuture(zone, cls); } ClassHiearchyUpdater(zone).Register(cls); + EnsureClassSuperTablesUpdated(thread, cls); #endif // !defined(DART_PRECOMPILED_RUNTIME) #else @@ -772,9 +775,121 @@ } #endif // defined(DART_PRECOMPILED_RUNTIME) #endif // defined(DART_PRECOMPILED_RUNTIME) && !defined(DART_DYNAMIC_MODULES) + +#if !defined(DART_PRECOMPILED_RUNTIME) + EnsureClassSuperTablesUpdated(thread, cls); +#endif } #if !defined(DART_PRECOMPILED_RUNTIME) +// Populate class hierarchy tables used by modular AOT type-testing stubs. +void ClassFinalizer::EnsureClassSuperTablesUpdated(Thread* thread, + const Class& cls) { + IsolateGroup* isolate_group = thread->isolate_group(); + ASSERT(isolate_group->program_lock()->IsCurrentThreadWriter()); + if (isolate_group->class_table() != isolate_group->heap_walk_class_table()) { + // Class table is cloned during hot reload; super tables will be rebuilt + // in ProgramReloadContext::RestoreClassHierarchyInvariants once reload + // finishes. + return; + } + Zone* zone = thread->zone(); + if (cls.IsTopLevel()) { + // These tables are only needed for real classes, as top-level classes don't + // participate in types or type tests (and their class ids are outside the + // regular cid range). + return; + } + + ClassTable* class_table = isolate_group->class_table(); + if (class_table->GetBases(cls.id()) != nullptr) { + return; // Already populated. + } + + const Class& super = Class::Handle(zone, cls.SuperClass()); + classid_t bases_length = 1; + if (!super.IsNull()) { + EnsureClassSuperTablesUpdated(thread, super); + const classid_t* super_bases = class_table->GetBases(super.id()); + ASSERT(super_bases != nullptr); + bases_length = super_bases[ClassTable::kBasesLengthIndex] + 1; + } + + // Allocate and populate bases_ta before allocating C-heap memory for bases, + // so a LongJump during Dart heap allocation cannot leak bases. + const Array& bases_ta = + Array::Handle(zone, Array::New(bases_length, Heap::kOld)); + TypeArguments& bases_ta_i = TypeArguments::Handle(zone); + AbstractType& t = AbstractType::Handle(zone); + const TypeArguments& cls_ta = + TypeArguments::Handle(zone, cls.GetDeclarationInstanceTypeArguments()); + // For each super class `cur_super` at index `i`: + // bases_ta[i] = + // cls_ta[(cur_super.NumTypeArguments() - cur_super.NumTypeParameters()).. + // cur_super.NumTypeArguments()] + Class& cur_super = Class::Handle(zone, super.ptr()); + for (intptr_t i = bases_length - 2; i >= 0; + i--, cur_super = cur_super.SuperClass()) { + ASSERT(!cur_super.IsNull()); + const intptr_t num_type_params = cur_super.NumTypeParameters(thread); + if (num_type_params == 0 || cls_ta.IsNull()) { + bases_ta.SetAt(i, Object::null_object()); + } else { + const intptr_t offset = cur_super.NumTypeArguments() - num_type_params; + ASSERT(cls_ta.Length() >= cur_super.NumTypeArguments()); + if (offset == 0 && cls_ta.Length() == num_type_params) { + ASSERT(cls_ta.IsCanonical()); + bases_ta.SetAt(i, cls_ta); + } else { + bases_ta_i = TypeArguments::New(num_type_params, Heap::kOld); + for (intptr_t j = 0; j < num_type_params; j++) { + t = cls_ta.TypeAt(offset + j); + bases_ta_i.SetTypeAt(j, t); + } + bases_ta_i = bases_ta_i.Canonicalize(thread); + bases_ta.SetAt(i, bases_ta_i); + } + } + } + ASSERT(cur_super.IsNull()); + bases_ta.SetAt(bases_length - 1, Object::sentinel()); + + // Create our bases by appending our id to super bases. + classid_t* bases = static_cast<classid_t*>( + malloc((ClassTable::kBasesFirstElementIndex + bases_length) * + sizeof(classid_t))); + bases[ClassTable::kBasesLengthIndex] = bases_length; + if (!super.IsNull()) { + const classid_t* super_bases = class_table->GetBases(super.id()); + ASSERT(super_bases != nullptr); + const classid_t super_bases_length = + super_bases[ClassTable::kBasesLengthIndex]; + ASSERT(super_bases_length + 1 == bases_length); + memmove(&bases[ClassTable::kBasesFirstElementIndex], + &super_bases[ClassTable::kBasesFirstElementIndex], + super_bases_length * sizeof(classid_t)); + } + bases[ClassTable::kBasesFirstElementIndex + bases_length - 1] = cls.id(); + + class_table->SetBasesTA(cls.id(), bases_ta); + class_table->SetBases(cls.id(), bases); + // TODO(aam): Populate interfaces, interfaces type arguments. +} + +void ClassFinalizer::EnsureAllClassSuperTablesUpdated(Thread* thread) { + ASSERT(thread->isolate_group()->program_lock()->IsCurrentThreadWriter()); + ClassTable* class_table = thread->isolate_group()->class_table(); + Class& cls = Class::Handle(thread->zone()); + for (intptr_t i = kInstanceCid; i < class_table->NumCids(); i++) { + if (class_table->HasValidClassAt(i)) { + cls = class_table->At(i); + if (cls.is_type_finalized()) { + HANDLESCOPE(thread); + EnsureClassSuperTablesUpdated(thread, cls); + } + } + } +} ErrorPtr ClassFinalizer::AllocateFinalizeClass(const Class& cls) { ASSERT(IsolateGroup::Current()->program_lock()->IsCurrentThreadWriter()); @@ -824,6 +939,7 @@ } cls.set_is_allocate_finalized(); + return Error::null(); }
diff --git a/runtime/vm/class_finalizer.h b/runtime/vm/class_finalizer.h index 333a875..0882121 100644 --- a/runtime/vm/class_finalizer.h +++ b/runtime/vm/class_finalizer.h
@@ -63,6 +63,10 @@ #if !defined(DART_PRECOMPILED_RUNTIME) // Makes class instantiatable and usable by generated code. static ErrorPtr AllocateFinalizeClass(const Class& cls); + // Populate helper class tables that are used by modaot type testing stubs. + static void EnsureClassSuperTablesUpdated(Thread* thread, const Class& cls); + static void EnsureAllClassSuperTablesUpdated(Thread* thread); + #endif // !defined(DART_PRECOMPILED_RUNTIME) #if !defined(DART_PRECOMPILED_RUNTIME) || defined(DART_DYNAMIC_MODULES)
diff --git a/runtime/vm/class_finalizer_test.cc b/runtime/vm/class_finalizer_test.cc index 3659ccb..8dd08ba 100644 --- a/runtime/vm/class_finalizer_test.cc +++ b/runtime/vm/class_finalizer_test.cc
@@ -2,8 +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. -#include "vm/class_finalizer.h" +#include <string> +#include <vector> + #include "platform/assert.h" +#include "vm/class_finalizer.h" #include "vm/symbols.h" #include "vm/unit_test.h" @@ -53,4 +56,305 @@ EXPECT(ClassFinalizer::ProcessPendingClasses()); } +static void AssertBasesContent(const classid_t* actual, + const std::vector<intptr_t>& expected) { + EXPECT(actual != nullptr); + if (actual == nullptr) { + return; + } + const classid_t expected_size = static_cast<classid_t>(expected.size()); + EXPECT_EQ(expected_size, actual[ClassTable::kBasesLengthIndex]); + if (actual[ClassTable::kBasesLengthIndex] != expected_size) { + return; + } + for (intptr_t i = 0; i < actual[ClassTable::kBasesLengthIndex]; i++) { + EXPECT_EQ( + expected[i], + static_cast<intptr_t>(actual[ClassTable::kBasesFirstElementIndex + i])); + } +} + +static std::string BasesTAToString(Zone* zone, const Array& ta) { + EXPECT(!ta.IsNull()); + EXPECT(ta.IsOld()); + std::string result = "["; + Object& object = Object::Handle(zone); + TypeArguments& tas = TypeArguments::Handle(zone); + AbstractType& t = AbstractType::Handle(zone); + for (intptr_t i = 0; i < ta.Length(); i++) { + if (i > 0) { + result += ", "; + } + object = ta.At(i); + if (object.IsNull()) { + result += "null"; + } else if (object.IsSentinel()) { + result += "sentinel"; + } else { + EXPECT(object.IsTypeArguments()); + tas ^= object.ptr(); + EXPECT(tas.IsOld()); + EXPECT(tas.IsCanonical()); + result += "<"; + for (intptr_t j = 0; j < tas.Length(); j++) { + if (j > 0) { + result += ", "; + } + t = tas.TypeAt(j); + result += t.ToCString(); + } + result += ">"; + } + } + result += "]"; + return result; +} + +TEST_CASE(SuperclassBaseTables_Simple) { + const char* kScriptChars = + "class A<T> {}\n" + "class B<S> extends A<List<S>> {}\n" + "class C extends B<int> {}\n" + "class D extends A<int> {}\n" + "\n" + "class E {}\n" + "class F<U> extends E {}\n" + "class G extends F {}\n" + "class H extends F<List<H>> {}\n" + "class P<T> extends F<dynamic> {}\n" + "\n" + "class I extends E {}\n" + "class J extends I {}\n" + "\n" + "class K<S, T> {}\n" + "class L<S, T, U> extends K<T, List<U>> {}\n" + "class M<S, T> extends L<int, List<S>, Map<S, T>> {}\n" + "\n" + "class N<S, T> extends K<S, T> {}\n" + "\n" + "abstract class Q<T> extends A<List<T>> {}\n"; + // First setup the script and compile the script. + TestCase::LoadTestScript(kScriptChars, /*resolver=*/nullptr); + TransitionNativeToVM transition(thread); + + Zone* zone = thread->zone(); + auto isolate_group = thread->isolate_group(); + auto class_table = isolate_group->class_table(); + + const String& name = String::Handle(zone, String::New(TestCase::url())); + const Library& lib = + Library::Handle(zone, Library::LookupLibrary(thread, name)); + EXPECT(!lib.IsNull()); + + auto lookup = [&](const char* cls_name) -> Class& { + return Class::Handle(zone, lib.LookupClass(String::Handle( + zone, Symbols::New(thread, cls_name)))); + }; + Class& A = lookup("A"); + Class& B = lookup("B"); + Class& C = lookup("C"); + Class& D = lookup("D"); + Class& E = lookup("E"); + Class& F = lookup("F"); + Class& G = lookup("G"); + Class& H = lookup("H"); + Class& I = lookup("I"); + Class& J = lookup("J"); + Class& K = lookup("K"); + Class& L = lookup("L"); + Class& M = lookup("M"); + Class& N = lookup("N"); + Class& P = lookup("P"); + Class& Q = lookup("Q"); + // Verify Q is already populated on type finalization without FinalizeClass. + EXPECT(Q.is_type_finalized()); + EXPECT(!Q.is_finalized()); + { + SafepointWriteRwLocker ml(thread, isolate_group->program_lock()); + ClassFinalizer::FinalizeClass(C); + ClassFinalizer::FinalizeClass(D); + ClassFinalizer::FinalizeClass(G); + ClassFinalizer::FinalizeClass(H); + ClassFinalizer::FinalizeClass(P); + ClassFinalizer::FinalizeClass(J); + ClassFinalizer::FinalizeClass(M); + ClassFinalizer::FinalizeClass(N); + } + + AssertBasesContent(class_table->GetBases(A.id()), + {ClassId::kInstanceCid, A.id()}); + AssertBasesContent(class_table->GetBases(B.id()), + {ClassId::kInstanceCid, A.id(), B.id()}); + AssertBasesContent(class_table->GetBases(C.id()), + {ClassId::kInstanceCid, A.id(), B.id(), C.id()}); + AssertBasesContent(class_table->GetBases(D.id()), + {ClassId::kInstanceCid, A.id(), D.id()}); + AssertBasesContent(class_table->GetBases(E.id()), + {ClassId::kInstanceCid, E.id()}); + AssertBasesContent(class_table->GetBases(F.id()), + {ClassId::kInstanceCid, E.id(), F.id()}); + AssertBasesContent(class_table->GetBases(G.id()), + {ClassId::kInstanceCid, E.id(), F.id(), G.id()}); + AssertBasesContent(class_table->GetBases(H.id()), + {ClassId::kInstanceCid, E.id(), F.id(), H.id()}); + AssertBasesContent(class_table->GetBases(P.id()), + {ClassId::kInstanceCid, E.id(), F.id(), P.id()}); + AssertBasesContent(class_table->GetBases(I.id()), + {ClassId::kInstanceCid, E.id(), I.id()}); + AssertBasesContent(class_table->GetBases(J.id()), + {ClassId::kInstanceCid, E.id(), I.id(), J.id()}); + AssertBasesContent(class_table->GetBases(K.id()), + {ClassId::kInstanceCid, K.id()}); + AssertBasesContent(class_table->GetBases(L.id()), + {ClassId::kInstanceCid, K.id(), L.id()}); + AssertBasesContent(class_table->GetBases(M.id()), + {ClassId::kInstanceCid, K.id(), L.id(), M.id()}); + AssertBasesContent(class_table->GetBases(N.id()), + {ClassId::kInstanceCid, K.id(), N.id()}); + AssertBasesContent(class_table->GetBases(Q.id()), + {ClassId::kInstanceCid, A.id(), Q.id()}); + + auto check_ta = [&](const Class& cls, const char* expected) { + const Array& bases_ta = + Array::Handle(zone, class_table->GetBasesTA(cls.id())); + EXPECT_STREQ(expected, BasesTAToString(zone, bases_ta).c_str()); + }; + check_ta(A, "[null, sentinel]"); + check_ta(B, "[null, <Type: List<C1X0>>, sentinel]"); + check_ta(C, "[null, <Type: List<int>>, <Type: int>, sentinel]"); + check_ta(D, "[null, <Type: int>, sentinel]"); + check_ta(E, "[null, sentinel]"); + check_ta(F, "[null, null, sentinel]"); + check_ta(G, "[null, null, null, sentinel]"); + check_ta(H, "[null, null, <Type: List<H>>, sentinel]"); + check_ta(P, "[null, null, null, sentinel]"); + check_ta(I, "[null, null, sentinel]"); + check_ta(J, "[null, null, null, sentinel]"); + check_ta(K, "[null, sentinel]"); + check_ta(L, "[null, <TypeParameter: C2X1, Type: List<C2X2>>, sentinel]"); + check_ta(M, + "[null, <Type: List<C5X0>, Type: List<Map<C5X0, C5X1>>>, " + "<Type: int, Type: List<C5X0>, Type: Map<C5X0, C5X1>>, sentinel]"); + check_ta(N, "[null, <TypeParameter: X0, TypeParameter: X1>, sentinel]"); + check_ta(Q, "[null, <Type: List<C1X0>>, sentinel]"); + + // Verify canonicalization shares identical TypeArguments vectors across + // classes (both C->B<int> and D->A<int> hold canonical <int>). + const Array& bases_ta_C = + Array::Handle(zone, class_table->GetBasesTA(C.id())); + const Array& bases_ta_D = + Array::Handle(zone, class_table->GetBasesTA(D.id())); + EXPECT(bases_ta_C.At(2) == bases_ta_D.At(1)); + + // Verify ClassTable::Remap updates cids inside bases arrays when sorting. + ClassFinalizer::SortClasses(); + AssertBasesContent(class_table->GetBases(A.id()), + {ClassId::kInstanceCid, A.id()}); + AssertBasesContent(class_table->GetBases(B.id()), + {ClassId::kInstanceCid, A.id(), B.id()}); + AssertBasesContent(class_table->GetBases(C.id()), + {ClassId::kInstanceCid, A.id(), B.id(), C.id()}); + AssertBasesContent(class_table->GetBases(M.id()), + {ClassId::kInstanceCid, K.id(), L.id(), M.id()}); +} + +ISOLATE_UNIT_TEST_CASE(SuperclassBaseTables_CoreClasses) { + Zone* zone = thread->zone(); + IsolateGroup* isolate_group = thread->isolate_group(); + ClassTable* class_table = isolate_group->class_table(); + { + SafepointWriteRwLocker ml(thread, isolate_group->program_lock()); + ClassFinalizer::EnsureAllClassSuperTablesUpdated(thread); + } + + // Verify every type-finalized class loaded from the core snapshot has + // populated bases and bases_ta tables with matching invariants. + Class& cls = Class::Handle(zone); + Class& super = Class::Handle(zone); + Array& bases_ta = Array::Handle(zone); + for (intptr_t cid = kInstanceCid; cid < class_table->NumCids(); cid++) { + if (!class_table->HasValidClassAt(cid)) { + continue; + } + cls = class_table->At(cid); + if (!cls.is_type_finalized()) { + continue; + } + const classid_t* bases = class_table->GetBases(cid); + EXPECT(bases != nullptr); + if (bases == nullptr) { + continue; + } + const intptr_t len = bases[ClassTable::kBasesLengthIndex]; + EXPECT_GE(len, 1); + EXPECT_EQ(cid, static_cast<intptr_t>( + bases[ClassTable::kBasesFirstElementIndex + len - 1])); + + super = cls.ptr(); + for (intptr_t i = ClassTable::kBasesFirstElementIndex + len - 1; + i >= ClassTable::kBasesFirstElementIndex; i--) { + EXPECT(!super.IsNull()); + EXPECT_EQ(super.id(), static_cast<intptr_t>(bases[i])); + super = super.SuperClass(); + } + EXPECT(super.IsNull()); + + bases_ta = class_table->GetBasesTA(cid); + EXPECT(!bases_ta.IsNull()); + EXPECT(bases_ta.IsOld()); + EXPECT_EQ(len, bases_ta.Length()); + EXPECT(bases_ta.At(len - 1) == Object::sentinel().ptr()); + } + + // Internal-only VM classes must not be populated, and GetBasesTA must return + // Array::null() (never raw nullptr) for unpopulated entries. + EXPECT(class_table->GetBases(kClassCid) == nullptr); + bases_ta = class_table->GetBasesTA(kClassCid); + EXPECT(bases_ta.IsNull()); + + // Spot-check key predefined and abstract core classes explicitly. + const Library& core_lib = Library::Handle(zone, Library::CoreLibrary()); + auto lookup_core = [&](const char* name) -> Class& { + return Class::Handle(zone, core_lib.LookupClassAllowPrivate(String::Handle( + zone, Symbols::New(thread, name)))); + }; + const Class& string_base = lookup_core("_StringBase"); + EXPECT(!string_base.IsNull()); + const Class& num_cls = lookup_core("num"); + EXPECT(!num_cls.IsNull()); + const Class& int_cls = lookup_core("int"); + EXPECT(!int_cls.IsNull()); + const Class& string_cls = lookup_core("String"); + EXPECT(!string_cls.IsNull()); + const Class& comparable_cls = lookup_core("Comparable"); + EXPECT(!comparable_cls.IsNull()); + + AssertBasesContent(class_table->GetBases(kInstanceCid), {kInstanceCid}); + AssertBasesContent(class_table->GetBases(kBoolCid), {kInstanceCid, kBoolCid}); + AssertBasesContent(class_table->GetBases(kNullCid), {kInstanceCid, kNullCid}); + AssertBasesContent(class_table->GetBases(kDoubleCid), + {kInstanceCid, kDoubleCid}); + AssertBasesContent(class_table->GetBases(kSmiCid), + {kInstanceCid, kIntegerCid, kSmiCid}); + AssertBasesContent(class_table->GetBases(kMintCid), + {kInstanceCid, kIntegerCid, kMintCid}); + AssertBasesContent(class_table->GetBases(kOneByteStringCid), + {kInstanceCid, string_base.id(), kOneByteStringCid}); + AssertBasesContent(class_table->GetBases(kTwoByteStringCid), + {kInstanceCid, string_base.id(), kTwoByteStringCid}); + AssertBasesContent(class_table->GetBases(kClosureCid), + {kInstanceCid, kClosureCid}); + AssertBasesContent(class_table->GetBases(num_cls.id()), + {kInstanceCid, num_cls.id()}); + AssertBasesContent(class_table->GetBases(int_cls.id()), + {kInstanceCid, num_cls.id(), int_cls.id()}); + AssertBasesContent(class_table->GetBases(string_cls.id()), + {kInstanceCid, string_cls.id()}); + AssertBasesContent(class_table->GetBases(comparable_cls.id()), + {kInstanceCid, comparable_cls.id()}); + EXPECT(class_table->GetBases(kArrayCid) != nullptr); + EXPECT(class_table->GetBases(kImmutableArrayCid) != nullptr); + EXPECT(class_table->GetBases(kGrowableObjectArrayCid) != nullptr); +} + } // namespace dart
diff --git a/runtime/vm/class_table.cc b/runtime/vm/class_table.cc index 1be24e4..1bb7f26 100644 --- a/runtime/vm/class_table.cc +++ b/runtime/vm/class_table.cc
@@ -28,18 +28,31 @@ } ClassTable::~ClassTable() { -#if !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) +#if !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) || \ + !defined(DART_PRECOMPILED_RUNTIME) + +#if !defined(DART_PRECOMPILED_RUNTIME) + classid_t** bases_table = bases(); +#endif // !defined(DART_PRECOMPILED_RUNTIME) for (intptr_t i = 1; i < classes_.num_cids(); i++) { +#if !defined(DART_PRECOMPILED_RUNTIME) + free(bases_table[i]); +#endif // !defined(DART_PRECOMPILED_RUNTIME) +#if !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) const char* name = UserVisibleNameFor(i); if (name != nullptr) { free(const_cast<char*>(name)); } - } #endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) + } + +#endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) || + // !defined(DART_PRECOMPILED_RUNTIME) } void ClassTable::Register(const Class& cls) { - ASSERT(Thread::Current()->IsDartMutatorThread()); + auto thread = Thread::Current(); + ASSERT(thread->IsDartMutatorThread()); ASSERT(cls.id() == kIllegalCid || cls.id() < kNumPredefinedCids); bool did_grow = false; const classid_t cid = @@ -55,10 +68,16 @@ #if !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) classes_.At<kClassNameIndex>(cid) = nullptr; #endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) - if (did_grow) { - IsolateGroup::Current()->set_cached_class_table_table( + auto isolate_group = thread->isolate_group(); + isolate_group->set_cached_class_table_table( classes_.GetColumn<kClassIndex>()); +#if !defined(DART_PRECOMPILED_RUNTIME) + isolate_group->set_cached_class_table_bases( + classes_.GetColumn<kBasesIndex>()); + isolate_group->set_cached_class_table_bases_ta( + classes_.GetColumn<kBasesTAIndex>()); +#endif UpdateCachedAllocationTracingStateTablePointer(); } else { // GCC warns that TSAN doesn't understand thread fences. @@ -88,7 +107,12 @@ classes_.AllocateIndex(index, &did_grow); if (did_grow) { - IsolateGroup::Current()->set_cached_class_table_table(table()); + auto isolate_group = IsolateGroup::Current(); + isolate_group->set_cached_class_table_table(table()); +#if !defined(DART_PRECOMPILED_RUNTIME) + isolate_group->set_cached_class_table_bases(bases()); + isolate_group->set_cached_class_table_bases_ta(bases_ta()); +#endif UpdateCachedAllocationTracingStateTablePointer(); } } @@ -102,22 +126,37 @@ void ClassTable::Remap(intptr_t* old_to_new_cid) { ASSERT(Thread::Current()->OwnsSafepoint()); classes_.Remap(old_to_new_cid); +#if !defined(DART_PRECOMPILED_RUNTIME) + for (intptr_t i = 1; i < classes_.num_cids(); i++) { + classid_t* bases = classes_.At<kBasesIndex>(i); + if (bases != nullptr) { + const intptr_t length = bases[kBasesLengthIndex]; + for (intptr_t j = kBasesFirstElementIndex; + j < kBasesFirstElementIndex + length; j++) { + bases[j] = static_cast<classid_t>(old_to_new_cid[bases[j]]); + } + } + } +#endif // !defined(DART_PRECOMPILED_RUNTIME) } void ClassTable::VisitObjectPointers(ObjectPointerVisitor* visitor) { ASSERT(visitor != nullptr); visitor->set_gc_root_type("class table"); - const auto visit = [&](ClassPtr* table, intptr_t num_cids) { + const auto visit = [&](ObjectPtr* table, intptr_t num_cids) { if (num_cids == 0) { return; } - ObjectPtr* from = reinterpret_cast<ObjectPtr*>(&table[0]); - ObjectPtr* to = reinterpret_cast<ObjectPtr*>(&table[num_cids - 1]); + ObjectPtr* from = &table[0]; + ObjectPtr* to = &table[num_cids - 1]; visitor->VisitPointers(from, to); }; visit(classes_.GetColumn<kClassIndex>(), classes_.num_cids()); +#if !defined(DART_PRECOMPILED_RUNTIME) + visit(classes_.GetColumn<kBasesTAIndex>(), classes_.num_cids()); +#endif visit(top_level_classes_.GetColumn<kClassIndex>(), top_level_classes_.num_cids()); visitor->clear_gc_root_type(); @@ -149,6 +188,53 @@ classes_.At<kSizeIndex>(cid) = static_cast<int32_t>(size); } +#if !defined(DART_PRECOMPILED_RUNTIME) +classid_t* ClassTable::GetBases(intptr_t cid) const { + ASSERT(IsValidIndex(cid)); + if (IsTopLevelCid(cid)) { + UNREACHABLE(); + } + return classes_.LoadAt<kBasesIndex>(cid); +} + +void ClassTable::SetBases(intptr_t cid, classid_t* bases) { + ASSERT(IsValidIndex(cid)); + if (IsTopLevelCid(cid)) { + UNREACHABLE(); + } + classid_t* old_bases = + classes_.LoadAt<kBasesIndex>(cid, std::memory_order_relaxed); + if (old_bases != bases) { + classes_.StoreAt<kBasesIndex>(cid, bases); + allocator_->Free(old_bases); + } +} + +ArrayPtr ClassTable::GetBasesTA(intptr_t cid) const { + ASSERT(IsValidIndex(cid)); + if (IsTopLevelCid(cid)) { + UNREACHABLE(); + } + ArrayPtr bases_ta = classes_.LoadAt<kBasesTAIndex>(cid); + return bases_ta == nullptr ? Array::null() : bases_ta; +} + +void ClassTable::SetBasesTA(intptr_t cid, const Array& bases_ta) { + ASSERT(IsValidIndex(cid)); + if (IsTopLevelCid(cid)) { + UNREACHABLE(); + } + classes_.StoreAt<kBasesTAIndex>(cid, bases_ta.ptr()); +} + +void ClassTable::ClearSuperTables() { + for (intptr_t i = 1; i < classes_.num_cids(); i++) { + SetBases(i, nullptr); + SetBasesTA(i, Object::null_array()); + } +} +#endif // !defined(DART_PRECOMPILED_RUNTIME) + void ClassTable::Validate() { Class& cls = Class::Handle(); for (intptr_t cid = kNumPredefinedCids; cid < classes_.num_cids(); cid++) {
diff --git a/runtime/vm/class_table.h b/runtime/vm/class_table.h index 2961bf5..e0aca4c 100644 --- a/runtime/vm/class_table.h +++ b/runtime/vm/class_table.h
@@ -22,6 +22,7 @@ namespace dart { +class Array; class Class; class ClassTable; class Isolate; @@ -246,6 +247,26 @@ return GetColumn<kColumnIndex>()[index]; } + template < + intptr_t kColumnIndex, + typename T = std::tuple_element_t<kColumnIndex, std::tuple<Columns...>>> + T LoadAt(intptr_t index, + std::memory_order order = std::memory_order_acquire) const { + ASSERT(IsValidIndex(index)); + return std::atomic_ref(std::get<kColumnIndex>(columns_).load()[index]) + .load(order); + } + + template < + intptr_t kColumnIndex, + typename T = std::tuple_element_t<kColumnIndex, std::tuple<Columns...>>> + void StoreAt(intptr_t index, + T value, + std::memory_order order = std::memory_order_release) { + ASSERT(IsValidIndex(index)); + std::atomic_ref(GetColumn<kColumnIndex>()[index]).store(value, order); + } + intptr_t num_cids() const { return num_cids_; } intptr_t capacity() const { return capacity_; } @@ -395,6 +416,26 @@ classes_.At<kUnboxedFieldBitmapIndex>(cid) = map; } +#if !defined(DART_PRECOMPILED_RUNTIME) + // Layout of each `bases` array (Cohen's display): + // bases[kBasesLengthIndex] holds the length (inheritance depth), followed + // by the superclass cids starting at kBasesFirstElementIndex (from Object + // through the class itself). + static constexpr intptr_t kBasesLengthIndex = 0; + static constexpr intptr_t kBasesFirstElementIndex = 1; + + // Cohen's display: list of superclasses for a given class. + // Returns nullptr if not yet populated. + classid_t* GetBases(intptr_t cid) const; + void SetBases(intptr_t cid, classid_t* bases); + // List of superclass type arguments for a given class. + // Returns Array::null() if not yet populated. + ArrayPtr GetBasesTA(intptr_t cid) const; + void SetBasesTA(intptr_t cid, const Array& bases_ta); + // Clears cached superclass displays and type argument arrays for all classes. + void ClearSuperTables(); +#endif // !defined(DART_PRECOMPILED_RUNTIME) + #if !defined(PRODUCT) bool ShouldTraceAllocationFor(intptr_t cid) { return !IsTopLevelCid(cid) && @@ -521,18 +562,33 @@ top_level_classes_(original.allocator_) { classes_.CopyFrom(original.classes_); -#if !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) +#if !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) || \ + !defined(DART_PRECOMPILED_RUNTIME) // Copying classes_ doesn't perform a deep copy. Ensure we duplicate - // the class names to avoid double free crashes at shutdown. + // the class names and bases to avoid double free crashes at shutdown. for (intptr_t cid = 1; cid < classes_.num_cids(); ++cid) { if (classes_.IsValidIndex(cid)) { +#if !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) const char* cls_name = classes_.At<kClassNameIndex>(cid); if (cls_name != nullptr) { classes_.At<kClassNameIndex>(cid) = Utils::StrDup(cls_name); } +#endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) +#if !defined(DART_PRECOMPILED_RUNTIME) + classid_t* bases = classes_.At<kBasesIndex>(cid); + if (bases != nullptr) { + const intptr_t bases_size = + (kBasesFirstElementIndex + bases[kBasesLengthIndex]) * + sizeof(classid_t); + classes_.At<kBasesIndex>(cid) = + static_cast<classid_t*>(malloc(bases_size)); + memmove(classes_.At<kBasesIndex>(cid), bases, bases_size); + } +#endif // !defined(DART_PRECOMPILED_RUNTIME) } } -#endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) +#endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_SAMPLING_HEAP_PROFILER) || + // !defined(DART_PRECOMPILED_RUNTIME) top_level_classes_.CopyFrom(original.top_level_classes_); UpdateCachedAllocationTracingStateTablePointer(); @@ -541,6 +597,10 @@ void AllocateTopLevelIndex(intptr_t index); ClassPtr* table() { return classes_.GetColumn<kClassIndex>(); } +#if !defined(DART_PRECOMPILED_RUNTIME) + classid_t** bases() { return classes_.GetColumn<kBasesIndex>(); } + ArrayPtr* bases_ta() { return classes_.GetColumn<kBasesTAIndex>(); } +#endif // Used to drop recently added classes. void SetNumCids(intptr_t num_cids, intptr_t num_tlc_cids) { @@ -559,6 +619,11 @@ kClassIndex = 0, kSizeIndex, kUnboxedFieldBitmapIndex, +#if !defined(DART_PRECOMPILED_RUNTIME) + // for modular-aot + kBasesIndex, + kBasesTAIndex, +#endif #if !defined(PRODUCT) kAllocationTracingStateIndex, #endif @@ -572,6 +637,10 @@ ClassPtr, uint32_t, UnboxedFieldBitmap, +#if !defined(DART_PRECOMPILED_RUNTIME) + classid_t*, + ArrayPtr, +#endif uint8_t, const char*> classes_; @@ -580,10 +649,23 @@ ClassPtr, uint32_t, UnboxedFieldBitmap, +#if !defined(DART_PRECOMPILED_RUNTIME) + classid_t*, + ArrayPtr, +#endif const char*> classes_; #else - CidIndexedTable<ClassIdTagType, ClassPtr, uint32_t, UnboxedFieldBitmap> + CidIndexedTable<ClassIdTagType, + ClassPtr, + uint32_t, + UnboxedFieldBitmap +#if !defined(DART_PRECOMPILED_RUNTIME) + , + classid_t*, + ArrayPtr +#endif + > classes_; #endif
diff --git a/runtime/vm/constants_arm64.h b/runtime/vm/constants_arm64.h index 458b936b..f18fd26 100644 --- a/runtime/vm/constants_arm64.h +++ b/runtime/vm/constants_arm64.h
@@ -804,7 +804,7 @@ SystemFixed = CompareBranchFixed | B31 | B30 | B24, HINT = SystemFixed | B17 | B16 | B13 | B4 | B3 | B2 | B1 | B0, CLREX = SystemFixed | B17 | B16 | B13 | B12 | B11 | B10 | B9 | B8 | B6 | B4 | - B3 | B2 | B1 | B0, + B3 | B2 | B1 | B0, BTI = HINT | B10, BTI_C = HINT | B10 | B6, BTI_J = HINT | B10 | B7, @@ -1081,7 +1081,7 @@ VNEGW = SIMDTwoRegFixed | B30 | B29 | B23 | B15 | B13 | B12, VSQRTS = SIMDTwoRegFixed | B30 | B29 | B23 | B16 | B15 | B14 | B13 | B12, VSQRTD = - SIMDTwoRegFixed | B30 | B29 | B23 | B22 | B16 | B15 | B14 | B13 | B12, + SIMDTwoRegFixed | B30 | B29 | B23 | B22 | B16 | B15 | B14 | B13 | B12, VRECPES = SIMDTwoRegFixed | B30 | B23 | B16 | B15 | B14 | B12, VRSQRTES = SIMDTwoRegFixed | B30 | B29 | B23 | B16 | B15 | B14 | B12, };
diff --git a/runtime/vm/isolate.cc b/runtime/vm/isolate.cc index 8e1adca..f4819e2 100644 --- a/runtime/vm/isolate.cc +++ b/runtime/vm/isolate.cc
@@ -308,6 +308,10 @@ : class_table_(nullptr), cached_class_table_table_(nullptr), object_store_(object_store), +#if !defined(DART_PRECOMPILED_RUNTIME) + cached_class_table_bases_(nullptr), + cached_class_table_bases_ta_(nullptr), +#endif class_table_allocator_(), embedder_data_(embedder_data), thread_pool_(), @@ -382,6 +386,10 @@ heap_walk_class_table_ = class_table_ = new ClassTable(&class_table_allocator_); cached_class_table_table_.store(class_table_->table()); +#if !defined(DART_PRECOMPILED_RUNTIME) + cached_class_table_bases_.store(class_table_->bases()); + cached_class_table_bases_ta_.store(class_table_->bases_ta()); +#endif memset(&native_assets_api_, 0, sizeof(NativeAssetsApi)); Roots::SetCurrent(roots()); @@ -3962,6 +3970,10 @@ RELEASE_ASSERT(class_table_ == heap_walk_class_table_); class_table_ = class_table_->Clone(); set_cached_class_table_table(nullptr); +#if !defined(DART_PRECOMPILED_RUNTIME) + set_cached_class_table_bases(nullptr); + set_cached_class_table_bases_ta(nullptr); +#endif } void IsolateGroup::RestoreOriginalClassTable() { @@ -3969,6 +3981,10 @@ class_table_allocator_.Free(class_table_); class_table_ = heap_walk_class_table_; set_cached_class_table_table(class_table_->table()); +#if !defined(DART_PRECOMPILED_RUNTIME) + set_cached_class_table_bases(class_table_->bases()); + set_cached_class_table_bases_ta(class_table_->bases_ta()); +#endif } void IsolateGroup::DropOriginalClassTable() { @@ -3976,6 +3992,10 @@ class_table_allocator_.Free(heap_walk_class_table_); heap_walk_class_table_ = class_table_; set_cached_class_table_table(class_table_->table()); +#if !defined(DART_PRECOMPILED_RUNTIME) + set_cached_class_table_bases(class_table_->bases()); + set_cached_class_table_bases_ta(class_table_->bases_ta()); +#endif } #endif
diff --git a/runtime/vm/isolate.h b/runtime/vm/isolate.h index 4b37e1b..361323d 100644 --- a/runtime/vm/isolate.h +++ b/runtime/vm/isolate.h
@@ -455,6 +455,32 @@ return OFFSET_OF(IsolateGroup, cached_class_table_table_); } +#if !defined(DART_PRECOMPILED_RUNTIME) + classid_t** cached_class_table_bases() { + return cached_class_table_bases_.load(); + } + void set_cached_class_table_bases(classid_t** cached_class_table_bases) { + cached_class_table_bases_.store(cached_class_table_bases); + } + static intptr_t cached_class_table_bases_offset() { + COMPILE_ASSERT(sizeof(IsolateGroup::cached_class_table_bases_) == + kWordSize); + return OFFSET_OF(IsolateGroup, cached_class_table_bases_); + } + + ArrayPtr* cached_class_table_bases_ta() { + return cached_class_table_bases_ta_.load(); + } + void set_cached_class_table_bases_ta(ArrayPtr* cached_class_table_bases_ta) { + cached_class_table_bases_ta_.store(cached_class_table_bases_ta); + } + static intptr_t cached_class_table_bases_ta_offset() { + COMPILE_ASSERT(sizeof(IsolateGroup::cached_class_table_bases_ta_) == + kWordSize); + return OFFSET_OF(IsolateGroup, cached_class_table_bases_ta_); + } +#endif // !defined(DART_PRECOMPILED_RUNTIME) + void set_object_store(ObjectStore* object_store); static intptr_t object_store_offset() { COMPILE_ASSERT(sizeof(IsolateGroup::object_store_) == kWordSize); @@ -908,6 +934,10 @@ ClassTable* class_table_; AcqRelAtomic<ClassPtr*> cached_class_table_table_; std::unique_ptr<ObjectStore> object_store_; +#if !defined(DART_PRECOMPILED_RUNTIME) + AcqRelAtomic<classid_t**> cached_class_table_bases_; + AcqRelAtomic<ArrayPtr*> cached_class_table_bases_ta_; +#endif // !defined(DART_PRECOMPILED_RUNTIME) // End accessed from generated code. ClassTableAllocator class_table_allocator_;
diff --git a/runtime/vm/isolate_reload.cc b/runtime/vm/isolate_reload.cc index de1ab27..a73e0e1 100644 --- a/runtime/vm/isolate_reload.cc +++ b/runtime/vm/isolate_reload.cc
@@ -1435,6 +1435,9 @@ VTIR_Print("Registering class: %s\n", new_cls.ToCString()); new_cls.set_id(old_cls.id()); IG->class_table()->SetAt(old_cls.id(), new_cls.ptr()); + ASSERT(old_cls.IsTopLevel() || + ((IG->class_table()->GetBases(old_cls.id()) == nullptr) && + (IG->class_table()->GetBasesTA(old_cls.id()) == Array::null()))); new_cls.CopyCanonicalConstants(old_cls); new_cls.CopyDeclarationType(old_cls); AddBecomeMapping(old_cls, new_cls); @@ -1581,6 +1584,7 @@ RELEASE_ASSERT(IG->class_table() != IG->heap_walk_class_table()); ClassTable* class_table = IG->class_table(); + class_table->ClearSuperTables(); // For efficiency, we build a set of classes before the reload. This set // is used to pair new classes with old classes. @@ -2904,6 +2908,7 @@ void ProgramReloadContext::RestoreClassHierarchyInvariants() { ClassTable* class_table = IG->class_table(); + class_table->ClearSuperTables(); intptr_t num_cids = class_table->NumCids(); // Clear the direct subclasses for all classes. @@ -2929,6 +2934,7 @@ if (cls.implementor_cid() != kIllegalCid) { cls.ClearImplementor(); } + cls.ClearDeclarationInstanceTypeArguments(); } } @@ -2944,6 +2950,7 @@ class_hieararchy_updater.Register(cls); } } + ClassFinalizer::EnsureAllClassSuperTablesUpdated(Thread::Current()); } #endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
diff --git a/runtime/vm/isolate_reload_test.cc b/runtime/vm/isolate_reload_test.cc index 4b1886b..5c52d81 100644 --- a/runtime/vm/isolate_reload_test.cc +++ b/runtime/vm/isolate_reload_test.cc
@@ -3,15 +3,18 @@ // BSD-style license that can be found in the LICENSE file. #include <array> +#include <vector> #include "include/dart_api.h" #include "include/dart_tools_api.h" #include "platform/assert.h" +#include "vm/class_finalizer.h" #include "vm/debugger_api_impl_test.h" #include "vm/globals.h" #include "vm/isolate.h" #include "vm/kernel_loader.h" #include "vm/lockers.h" +#include "vm/symbols.h" #include "vm/thread_barrier.h" #include "vm/thread_pool.h" #include "vm/unit_test.h" @@ -6943,6 +6946,461 @@ EXPECT_STREQ("Okay", SimpleInvokeStr(lib, "main")); } +TEST_CASE(IsolateReload_SuperclassBaseTables) { + Dart_SourceFile sourcefiles[] = { + { + "file:///test-app.dart", + "import 'test-sub.dart';\n" + "main() => useD();\n", + }, + { + "file:///test-lib.dart", + "class Base {}\n" + "class A extends Base {}\n", + }, + { + "file:///test-sub.dart", + "import 'test-lib.dart';\n" + "class D extends A {}\n" + "class E extends D {}\n" + "useD() => D().toString();\n", + }, + }; + + Dart_Handle lib = TestCase::LoadTestScriptWithDFE( + sizeof(sourcefiles) / sizeof(Dart_SourceFile), sourcefiles, + /*resolver=*/nullptr, /*finalize=*/true, /*incrementally=*/true); + EXPECT_VALID(lib); + EXPECT_VALID(Dart_Invoke(lib, NewString("main"), 0, nullptr)); + + auto check_bases = [&](const char* uri, const char* cls_name, + const std::vector<classid_t>& expected) { + TransitionNativeToVM transition(thread); + Zone* zone = thread->zone(); + const Library& l = Library::Handle( + zone, + Library::LookupLibrary(thread, String::Handle(zone, String::New(uri)))); + EXPECT(!l.IsNull()); + const Class& cls = Class::Handle( + zone, + l.LookupClass(String::Handle(zone, Symbols::New(thread, cls_name)))); + EXPECT(!cls.IsNull()); + classid_t* bases = + thread->isolate_group()->class_table()->GetBases(cls.id()); + EXPECT(bases != nullptr); + if (bases == nullptr) { + return; + } + const classid_t expected_size = static_cast<classid_t>(expected.size()); + EXPECT_EQ(expected_size, bases[ClassTable::kBasesLengthIndex]); + if (bases[ClassTable::kBasesLengthIndex] != expected_size) { + return; + } + for (size_t i = 0; i < expected.size(); i++) { + EXPECT_EQ(expected[i], bases[ClassTable::kBasesFirstElementIndex + i]); + } + const Array& bases_ta = Array::Handle( + zone, thread->isolate_group()->class_table()->GetBasesTA(cls.id())); + EXPECT(!bases_ta.IsNull()); + EXPECT_EQ(static_cast<intptr_t>(expected.size()), bases_ta.Length()); + EXPECT(bases_ta.At(bases_ta.Length() - 1) == Object::sentinel().ptr()); + }; + auto get_cid = [&](const char* uri, const char* cls_name) -> classid_t { + TransitionNativeToVM transition(thread); + Zone* zone = thread->zone(); + const Library& l = Library::Handle( + zone, + Library::LookupLibrary(thread, String::Handle(zone, String::New(uri)))); + EXPECT(!l.IsNull()); + const Class& cls = Class::Handle( + zone, + l.LookupClass(String::Handle(zone, Symbols::New(thread, cls_name)))); + EXPECT(!cls.IsNull()); + return static_cast<classid_t>(cls.id()); + }; + + const classid_t base_cid = get_cid("file:///test-lib.dart", "Base"); + const classid_t a_cid = get_cid("file:///test-lib.dart", "A"); + const classid_t d_cid = get_cid("file:///test-sub.dart", "D"); + const classid_t e_cid = get_cid("file:///test-sub.dart", "E"); + + check_bases("file:///test-lib.dart", "A", {kInstanceCid, base_cid, a_cid}); + check_bases("file:///test-sub.dart", "D", + {kInstanceCid, base_cid, a_cid, d_cid}); + + // Reload ONLY test-lib.dart, dropping `extends Base` from A. + // test-sub.dart (containing D and E) is unchanged. + Dart_SourceFile updated_shrink[] = { + { + "file:///test-lib.dart", + "class Base {}\n" + "class A {}\n", + }, + }; + { + const uint8_t* kernel_buffer = nullptr; + intptr_t kernel_buffer_size = 0; + char* error = TestCase::CompileTestScriptWithDFE( + "file:///test-app.dart", + sizeof(updated_shrink) / sizeof(Dart_SourceFile), updated_shrink, + &kernel_buffer, &kernel_buffer_size, /*incrementally=*/true); + EXPECT(error == nullptr); + EXPECT_NOTNULL(kernel_buffer); + lib = TestCase::ReloadTestKernel(kernel_buffer, kernel_buffer_size); + EXPECT_VALID(lib); + } + + // Unchanged subclasses D (finalized) and E (type-finalized) must have + // updated bases (depth 3/4, not 4/5), and internal-only VM classes must + // remain unpopulated. + check_bases("file:///test-lib.dart", "A", {kInstanceCid, a_cid}); + check_bases("file:///test-sub.dart", "D", {kInstanceCid, a_cid, d_cid}); + check_bases("file:///test-sub.dart", "E", + {kInstanceCid, a_cid, d_cid, e_cid}); + { + TransitionNativeToVM transition(thread); + EXPECT(thread->isolate_group()->class_table()->GetBases(kClassCid) == + nullptr); + } + + // Finalizing subclass E after reload must preserve its updated bases table. + { + TransitionNativeToVM transition(thread); + Zone* zone = thread->zone(); + const Library& sub_lib = Library::Handle( + zone, Library::LookupLibrary( + thread, + String::Handle(zone, String::New("file:///test-sub.dart")))); + const Class& cls_e = Class::Handle( + zone, + sub_lib.LookupClass(String::Handle(zone, Symbols::New(thread, "E")))); + EXPECT(!cls_e.is_finalized()); + SafepointWriteRwLocker ml(thread, thread->isolate_group()->program_lock()); + ClassFinalizer::FinalizeClass(cls_e); + } + check_bases("file:///test-sub.dart", "E", + {kInstanceCid, a_cid, d_cid, e_cid}); + + // Reload test-lib.dart again adding `extends Base` back. + Dart_SourceFile updated_grow[] = { + { + "file:///test-lib.dart", + "class Base {}\n" + "class A extends Base {}\n", + }, + }; + { + const uint8_t* kernel_buffer = nullptr; + intptr_t kernel_buffer_size = 0; + char* error = TestCase::CompileTestScriptWithDFE( + "file:///test-app.dart", sizeof(updated_grow) / sizeof(Dart_SourceFile), + updated_grow, &kernel_buffer, &kernel_buffer_size, + /*incrementally=*/true); + EXPECT(error == nullptr); + EXPECT_NOTNULL(kernel_buffer); + lib = TestCase::ReloadTestKernel(kernel_buffer, kernel_buffer_size); + EXPECT_VALID(lib); + } + + check_bases("file:///test-lib.dart", "A", {kInstanceCid, base_cid, a_cid}); + check_bases("file:///test-sub.dart", "D", + {kInstanceCid, base_cid, a_cid, d_cid}); + check_bases("file:///test-sub.dart", "E", + {kInstanceCid, base_cid, a_cid, d_cid, e_cid}); +} + +TEST_CASE(IsolateReload_SuperclassBaseTables_GenericSuperTypeArgChange) { + Dart_SourceFile sourcefiles[] = { + { + "file:///test-app.dart", + "import 'test-lib.dart';\n" + "import 'test-sub.dart';\n" + "main() => '${useB()} $kept';\n", + }, + { + "file:///test-lib.dart", + "class Base<T> {}\n" + "class A extends Base<int> {}\n" + "class Removed extends A {}\n" + "var kept = Removed();\n", + }, + { + "file:///test-sub.dart", + "import 'test-lib.dart';\n" + "class B extends A {}\n" + "useB() => B().toString();\n", + }, + }; + + Dart_Handle lib = TestCase::LoadTestScriptWithDFE( + sizeof(sourcefiles) / sizeof(Dart_SourceFile), sourcefiles, + /*resolver=*/nullptr, /*finalize=*/true, /*incrementally=*/true); + EXPECT_VALID(lib); + EXPECT_VALID(Dart_Invoke(lib, NewString("main"), 0, nullptr)); + + auto get_cid = [&](const char* uri, const char* cls_name) -> classid_t { + TransitionNativeToVM transition(thread); + Zone* zone = thread->zone(); + const Library& l = Library::Handle( + zone, + Library::LookupLibrary(thread, String::Handle(zone, String::New(uri)))); + EXPECT(!l.IsNull()); + const Class& cls = Class::Handle( + zone, + l.LookupClass(String::Handle(zone, Symbols::New(thread, cls_name)))); + EXPECT(!cls.IsNull()); + return static_cast<classid_t>(cls.id()); + }; + + auto check_base_ta_type = [&](classid_t cid, intptr_t index, + const char* expected_type_str) { + TransitionNativeToVM transition(thread); + Zone* zone = thread->zone(); + const Array& bases_ta = Array::Handle( + zone, thread->isolate_group()->class_table()->GetBasesTA(cid)); + EXPECT(!bases_ta.IsNull()); + EXPECT_LT(index, bases_ta.Length()); + const Object& entry = Object::Handle(zone, bases_ta.At(index)); + EXPECT(entry.IsTypeArguments()); + const TypeArguments& ta = TypeArguments::Cast(entry); + EXPECT_EQ(1, ta.Length()); + const AbstractType& t = AbstractType::Handle(zone, ta.TypeAt(0)); + EXPECT_STREQ(expected_type_str, t.ToCString()); + }; + + const classid_t b_cid = get_cid("file:///test-sub.dart", "B"); + const classid_t removed_cid = get_cid("file:///test-lib.dart", "Removed"); + + // Index 0 is Object, index 1 is Base<T>, index 2 is A, index 3 is B/Removed. + check_base_ta_type(b_cid, 1, "Type: int"); + check_base_ta_type(removed_cid, 1, "Type: int"); + + // Reload ONLY test-lib.dart (without reloading test-sub.dart), changing A + // from Base<int> to Base<String> and removing Removed (which still has a live + // instance in `kept`). + Dart_SourceFile updated[] = { + { + "file:///test-lib.dart", + "class Base<T> {}\n" + "class A extends Base<String> {}\n" + "var kept;\n", + }, + }; + { + const uint8_t* kernel_buffer = nullptr; + intptr_t kernel_buffer_size = 0; + char* error = TestCase::CompileTestScriptWithDFE( + "file:///test-lib.dart", sizeof(updated) / sizeof(Dart_SourceFile), + updated, &kernel_buffer, &kernel_buffer_size, /*incrementally=*/false); + EXPECT(error == nullptr); + EXPECT_NOTNULL(kernel_buffer); + lib = TestCase::ReloadTestKernel(kernel_buffer, kernel_buffer_size); + EXPECT_VALID(lib); + } + + // Both unchanged finalized subclass B (in non-reloaded test-sub.dart) and + // removed finalized subclass Removed must reflect Base<String>, not stale + // cached Base<int>. + check_base_ta_type(b_cid, 1, "Type: String"); + check_base_ta_type(removed_cid, 1, "Type: String"); +} + +TEST_CASE(IsolateReload_SuperclassBaseTables_UnfinalizedRemovedSubclass) { + const char* kScript = + "class Base<T, U> {}\n" + "class A {}\n" + "class B<S> extends A {}\n"; + + Dart_Handle lib = TestCase::LoadTestScript(kScript, nullptr); + EXPECT_VALID(lib); + + // Neither A nor B is finalized, only type-finalized. Changing A's + // NumTypeArguments while removing B must be rejected cleanly rather than + // crashing when rebuilding B's super tables. + const char* kReloadScript = + "class Base<T, U> {}\n" + "class A extends Base<int, String> {}\n"; + lib = TestCase::ReloadTestScript(kReloadScript); + EXPECT_ERROR(lib, "type parameters have changed"); + + // Verify rolled-back super tables remain intact. + TransitionNativeToVM transition(thread); + Zone* zone = thread->zone(); + const Library& root_lib = Library::Handle( + zone, thread->isolate_group()->object_store()->root_library()); + const Class& cls_a = Class::Handle( + zone, + root_lib.LookupClass(String::Handle(zone, Symbols::New(thread, "A")))); + const Class& cls_b = Class::Handle( + zone, + root_lib.LookupClass(String::Handle(zone, Symbols::New(thread, "B")))); + ClassTable* class_table = thread->isolate_group()->class_table(); + const classid_t* bases_b = class_table->GetBases(cls_b.id()); + EXPECT(bases_b != nullptr); + EXPECT_EQ(3, bases_b[ClassTable::kBasesLengthIndex]); + EXPECT_EQ(kInstanceCid, bases_b[ClassTable::kBasesFirstElementIndex]); + EXPECT_EQ(cls_a.id(), bases_b[ClassTable::kBasesFirstElementIndex + 1]); + EXPECT_EQ(cls_b.id(), bases_b[ClassTable::kBasesFirstElementIndex + 2]); +} + +TEST_CASE(IsolateReload_SuperclassBaseTables_UnfinalizedSubclassInOtherLib) { + Dart_SourceFile sourcefiles[] = { + { + "file:///test-app.dart", + "import 'test-sub.dart';\n" + "main() => 42;\n", + }, + { + "file:///test-lib.dart", + "class Base<T, U> {}\n" + "class A {}\n", + }, + { + "file:///test-sub.dart", + "import 'test-lib.dart';\n" + "class B<S> extends A {}\n", + }, + }; + + Dart_Handle lib = TestCase::LoadTestScriptWithDFE( + sizeof(sourcefiles) / sizeof(Dart_SourceFile), sourcefiles, + /*resolver=*/nullptr, /*finalize=*/true, /*incrementally=*/true); + EXPECT_VALID(lib); + + Dart_SourceFile updated[] = { + { + "file:///test-lib.dart", + "class Base<T, U> {}\n" + "class A extends Base<int, String> {}\n", + }, + }; + + // First: reload ONLY test-lib.dart without reloading test-sub.dart. + // Unfinalized subclass B is not replaced, so changing A's NumTypeArguments + // must be rejected cleanly. + { + const uint8_t* kernel_buffer = nullptr; + intptr_t kernel_buffer_size = 0; + char* error = TestCase::CompileTestScriptWithDFE( + "file:///test-lib.dart", sizeof(updated) / sizeof(Dart_SourceFile), + updated, &kernel_buffer, &kernel_buffer_size, /*incrementally=*/false); + EXPECT(error == nullptr); + EXPECT_NOTNULL(kernel_buffer); + lib = TestCase::ReloadTestKernel(kernel_buffer, kernel_buffer_size); + EXPECT_ERROR(lib, "type parameters have changed"); + } + + // Second: recompiling the full program (including test-sub.dart) replaces B + // together with A; reload succeeds and B's super tables are updated. + Dart_SourceFile updated_all[] = { + sourcefiles[0], + updated[0], + sourcefiles[2], + }; + { + const uint8_t* kernel_buffer = nullptr; + intptr_t kernel_buffer_size = 0; + char* error = TestCase::CompileTestScriptWithDFE( + "file:///test-app.dart", sizeof(updated_all) / sizeof(Dart_SourceFile), + updated_all, &kernel_buffer, &kernel_buffer_size, + /*incrementally=*/false); + EXPECT(error == nullptr); + EXPECT_NOTNULL(kernel_buffer); + lib = TestCase::ReloadTestKernel(kernel_buffer, kernel_buffer_size); + EXPECT_VALID(lib); + } + + { + TransitionNativeToVM transition(thread); + Zone* zone = thread->zone(); + const Library& lib_l = Library::Handle( + zone, Library::LookupLibrary( + thread, + String::Handle(zone, String::New("file:///test-lib.dart")))); + const Library& sub_l = Library::Handle( + zone, Library::LookupLibrary( + thread, + String::Handle(zone, String::New("file:///test-sub.dart")))); + const Class& base_cls = Class::Handle( + zone, + lib_l.LookupClass(String::Handle(zone, Symbols::New(thread, "Base")))); + const Class& a_cls = Class::Handle( + zone, + lib_l.LookupClass(String::Handle(zone, Symbols::New(thread, "A")))); + const Class& b_cls = Class::Handle( + zone, + sub_l.LookupClass(String::Handle(zone, Symbols::New(thread, "B")))); + ClassTable* class_table = thread->isolate_group()->class_table(); + const classid_t* bases_b = class_table->GetBases(b_cls.id()); + EXPECT(bases_b != nullptr); + EXPECT_EQ(4, bases_b[ClassTable::kBasesLengthIndex]); + EXPECT_EQ(kInstanceCid, bases_b[ClassTable::kBasesFirstElementIndex]); + EXPECT_EQ(base_cls.id(), bases_b[ClassTable::kBasesFirstElementIndex + 1]); + EXPECT_EQ(a_cls.id(), bases_b[ClassTable::kBasesFirstElementIndex + 2]); + EXPECT_EQ(b_cls.id(), bases_b[ClassTable::kBasesFirstElementIndex + 3]); + + const Array& bases_ta = + Array::Handle(zone, class_table->GetBasesTA(b_cls.id())); + EXPECT(!bases_ta.IsNull()); + EXPECT_EQ(4, bases_ta.Length()); + const TypeArguments& base_ta = + TypeArguments::Handle(zone, TypeArguments::RawCast(bases_ta.At(1))); + EXPECT_EQ(2, base_ta.Length()); + EXPECT_STREQ("Type: int", + AbstractType::Handle(zone, base_ta.TypeAt(0)).ToCString()); + EXPECT_STREQ("Type: String", + AbstractType::Handle(zone, base_ta.TypeAt(1)).ToCString()); + EXPECT(bases_ta.At(3) == Object::sentinel().ptr()); + } +} + +TEST_CASE(IsolateReload_SuperclassBaseTables_UnfinalizedTypeParamGrow) { + const char* kScript = + "class Base<T> {}\n" + "class Foo<A> extends Base<int> {}\n" + "class Bar {}\n" + "main() => '$Bar';\n"; + + Dart_Handle lib = TestCase::LoadTestScript(kScript, nullptr); + EXPECT_VALID(lib); + // Populate Bar.declaration_type_ without finalizing Bar. + EXPECT_STREQ("Bar", SimpleInvokeStr(lib, "main")); + + // Unfinalized classes with no subclasses can change type parameters (both + // generic -> generic and non-generic -> generic); make sure stale + // declaration_type_ is not kept on the replacement class. + const char* kReloadScript = + "class Base<T> {}\n" + "class Foo<A, B> extends Base<int> {}\n" + "class Bar<A> extends Base<String> {}\n" + "main() => '$Bar';\n"; + lib = TestCase::ReloadTestScript(kReloadScript); + EXPECT_VALID(lib); + + TransitionNativeToVM transition(thread); + Zone* zone = thread->zone(); + const Library& root_lib = Library::Handle( + zone, thread->isolate_group()->object_store()->root_library()); + auto check_cls = [&](const char* name, const char* expected_base_arg) { + const Class& cls = Class::Handle( + zone, + root_lib.LookupClass(String::Handle(zone, Symbols::New(thread, name)))); + EXPECT(!cls.IsNull()); + const Array& bases_ta = Array::Handle( + zone, thread->isolate_group()->class_table()->GetBasesTA(cls.id())); + EXPECT(!bases_ta.IsNull()); + EXPECT_EQ(3, bases_ta.Length()); + const TypeArguments& base_ta = + TypeArguments::Handle(zone, TypeArguments::RawCast(bases_ta.At(1))); + EXPECT_EQ(1, base_ta.Length()); + EXPECT_STREQ(expected_base_arg, + AbstractType::Handle(zone, base_ta.TypeAt(0)).ToCString()); + EXPECT(bases_ta.At(2) == Object::sentinel().ptr()); + }; + check_cls("Foo", "Type: int"); + check_cls("Bar", "Type: String"); +} + #endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME) } // namespace dart
diff --git a/runtime/vm/module_snapshot.cc b/runtime/vm/module_snapshot.cc index ed774ac..41b22e5 100644 --- a/runtime/vm/module_snapshot.cc +++ b/runtime/vm/module_snapshot.cc
@@ -256,6 +256,12 @@ DeserializationCluster* ReadCluster(); bool ReadRoots(); + void set_classes_range(intptr_t start_index, intptr_t stop_index) { + ASSERT(classes_start_index_ == 0 && classes_stop_index_ == 0); + classes_start_index_ = start_index; + classes_stop_index_ = stop_index; + } + uword instructions() const { return reinterpret_cast<uword>(instructions_buffer_); } @@ -315,6 +321,8 @@ Array& refs_array_; ArrayPtr refs_; intptr_t next_ref_index_ = kFirstReference; + intptr_t classes_start_index_ = 0; + intptr_t classes_stop_index_ = 0; DeserializationCluster** clusters_ = nullptr; }; @@ -634,6 +642,7 @@ auto& function = Function::Handle(d->zone()); auto& field = Field::Handle(d->zone()); auto& name = String::Handle(d->zone()); + d->set_classes_range(start_index_, stop_index_); for (intptr_t id = start_index_, n = stop_index_; id < n; id++) { cls ^= refs.At(id); array = cls.functions(); @@ -2497,6 +2506,14 @@ bool is_platform = ReadRoots(); if (is_platform) { heap_->old_space()->EvaluateAfterLoading(); + ClassFinalizer::EnsureAllClassSuperTablesUpdated(thread()); + } else { + Class& cls = Class::Handle(zone_); + for (intptr_t i = classes_start_index_; i < classes_stop_index_; i++) { + HANDLESCOPE(thread()); + cls ^= refs_array_.At(i); + ClassFinalizer::EnsureClassSuperTablesUpdated(thread(), cls); + } } if (isolate_group->snapshot_is_dontneed_safe()) {
diff --git a/runtime/vm/object.cc b/runtime/vm/object.cc index 3eb7c1e..5a8163a 100644 --- a/runtime/vm/object.cc +++ b/runtime/vm/object.cc
@@ -3269,6 +3269,12 @@ void Class::set_type_parameters(const TypeParameters& value) const { ASSERT((num_type_arguments() == kUnknownNumTypeArguments) || is_declared_in_bytecode() || is_prefinalized()); + if (!value.IsNull() && (declaration_type() != Type::null()) && + (Type::Handle(declaration_type()).arguments() == TypeArguments::null())) { + // An unfinalized non-generic class may have had its non-generic + // declaration_type_ copied during reload before becoming generic. + untag()->set_declaration_type<std::memory_order_release>(Type::null()); + } untag()->set_type_parameters(value.ptr()); } @@ -3300,6 +3306,14 @@ value.ptr()); } +void Class::ClearDeclarationInstanceTypeArguments() const { + ASSERT(IsolateGroup::Current()->program_lock()->IsCurrentThreadWriter()); + if (declaration_instance_type_arguments() != TypeArguments::null()) { + untag()->set_declaration_instance_type_arguments<std::memory_order_release>( + TypeArguments::null()); + } +} + TypeArgumentsPtr Class::GetDeclarationInstanceTypeArguments() const { const intptr_t num_type_arguments = NumTypeArguments(); if (num_type_arguments == 0) {
diff --git a/runtime/vm/object.h b/runtime/vm/object.h index ee6ffa4..1ad7137 100644 --- a/runtime/vm/object.h +++ b/runtime/vm/object.h
@@ -1360,6 +1360,9 @@ // type parameters of this class. TypeArgumentsPtr GetDeclarationInstanceTypeArguments() const; + // Clears cached declaration instance type arguments (if non-null). + void ClearDeclarationInstanceTypeArguments() const; + // Returns flattened instance type arguments vector for // instance of this type, parameterized with given type arguments. // @@ -2804,7 +2807,7 @@ kCachedICDataZeroArgTestedWithoutExactnessTrackingIdx = 0, kCachedICDataMaxArgsTestedWithoutExactnessTracking = 2, kCachedICDataOneArgWithExactnessTrackingIdx = - kCachedICDataZeroArgTestedWithoutExactnessTrackingIdx + + kCachedICDataZeroArgTestedWithoutExactnessTrackingIdx + kCachedICDataMaxArgsTestedWithoutExactnessTracking + 1, kCachedICDataArrayCount = kCachedICDataOneArgWithExactnessTrackingIdx + 1, };
diff --git a/runtime/vm/object_reload.cc b/runtime/vm/object_reload.cc index e1e2d2a..c58b378 100644 --- a/runtime/vm/object_reload.cc +++ b/runtime/vm/object_reload.cc
@@ -244,6 +244,14 @@ if (old_declaration_type.IsNull()) { return; } + // Only non-generic declaration types rely on Class::declaration_type_ for + // canonicalization (see Type::IsDeclarationTypeOf). Generic declaration types + // are canonicalized via ObjectStore::canonical_types(), and copying them + // would leave stale type arguments if an unfinalized class changes its type + // parameters on reload. + if (old_declaration_type.arguments() != TypeArguments::null()) { + return; + } set_declaration_type(old_declaration_type); } @@ -601,6 +609,44 @@ ASSERT(is_enum_class() == replacement.is_enum_class()); ASSERT(num_native_fields() == replacement.num_native_fields()); + if (is_type_finalized() && + ((NumTypeParameters() != replacement.NumTypeParameters()) || + (NumTypeArguments() != replacement.NumTypeArguments()))) { + auto* group_context = context->group_reload_context(); + bool reject = is_finalized(); + if (!reject) { + // Unfinalized classes are allowed to change type parameters when no + // instances exist (see IsolateReload_ChangeInstanceFormat7), unless a + // non-reloaded subclass would be left behind pointing to `replacement`. + // Direct subclasses suffice: any reloaded subclass runs its own + // CheckReload for its subclasses. + const GrowableObjectArray& subclasses = + GrowableObjectArray::Handle(direct_subclasses_unsafe()); + if (!subclasses.IsNull()) { + auto* class_table = group_context->isolate_group()->class_table(); + Class& sub = Class::Handle(); + for (intptr_t i = 0; i < subclasses.Length(); i++) { + sub ^= subclasses.At(i); + // Reject if `sub` already cached type info (is_type_finalized) and + // was not replaced by a reloaded class in the new class table + // (unchanged library or removed), since its cached + // num_type_arguments_ / super_type would no longer match + // `replacement`. + if (sub.is_type_finalized() && + (class_table->At(sub.id()) == sub.ptr())) { + reject = true; + break; + } + } + } + } + if (reject) { + group_context->AddReasonForCancelling( + new (context->zone()) + TypeParametersChanged(context->zone(), *this, replacement)); + return; + } + } if (is_finalized()) { if (!CanReloadFinalized(replacement, context)) return; } @@ -698,16 +744,8 @@ bool Class::CanReloadFinalized(const Class& replacement, ProgramReloadContext* context) const { - // Make sure the declaration types argument count matches for the two classes. - // ex. class A<int,B> {} cannot be replace with class A<B> {}. auto group_context = context->group_reload_context(); auto class_table = group_context->isolate_group()->class_table(); - if (NumTypeArguments() != replacement.NumTypeArguments()) { - group_context->AddReasonForCancelling( - new (context->zone()) - TypeParametersChanged(context->zone(), *this, replacement)); - return false; - } if (RequiresInstanceMorphing(class_table, replacement)) { ASSERT(id() == replacement.id()); const classid_t cid = id();
diff --git a/tools/VERSION b/tools/VERSION index 1c14433..de47746 100644 --- a/tools/VERSION +++ b/tools/VERSION
@@ -27,5 +27,5 @@ MAJOR 3 MINOR 15 PATCH 0 -PRERELEASE 217 +PRERELEASE 218 PRERELEASE_PATCH 0