Skip to content

Commit

Permalink
Enable 'strict-inference' language analysis mode
Browse files Browse the repository at this point in the history
  • Loading branch information
parlough committed Sep 13, 2023
1 parent cb0d6f9 commit 97852ba
Show file tree
Hide file tree
Showing 21 changed files with 60 additions and 38 deletions.
1 change: 1 addition & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ analyzer:

language:
strict-casts: true
strict-inference: true

linter:
rules:
Expand Down
2 changes: 1 addition & 1 deletion lib/src/command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ abstract class PubCommand extends Command<int> {
@override
String get invocation {
PubCommand? command = this;
var names = [];
var names = <String?>[];
do {
names.add(command?.name);
command = command?.parent as PubCommand?;
Expand Down
6 changes: 3 additions & 3 deletions lib/src/command/dependency_services.dart
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ class DependencyServicesReportCommand extends PubCommand {
_UpgradeType.compatible,
),
'singleBreaking': kind != 'transitive' && singleBreakingVersion == null
? []
? <Object>[]
: await computeUpgradeSet(
singleBreakingVersion,
_UpgradeType.singleBreaking,
Expand All @@ -176,7 +176,7 @@ class DependencyServicesReportCommand extends PubCommand {
multiBreakingVersion,
_UpgradeType.multiBreaking,
)
: [],
: <Object>[],
if (smallestUpgrade != null)
'smallestUpdate': await computeUpgradeSet(
smallestUpgrade,
Expand Down Expand Up @@ -503,7 +503,7 @@ class DependencyServicesApplyCommand extends PubCommand {
},
);
// Dummy message.
log.message(json.encode({'dependencies': []}));
log.message(json.encode({'dependencies': <Object>[]}));
}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/src/error_group.dart
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ class _ErrorGroupStream<T> extends Stream<T> {
if (_isDone) return;
_subscription.cancel();
// Call these asynchronously to work around issue 7913.
Future.value().then((_) {
Future<void>.value().then((_) {
_controller.addError(e, stackTrace);
_controller.close();
});
Expand Down
4 changes: 2 additions & 2 deletions lib/src/lock_file.dart
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ class LockFile {
/// serialized as absolute.
String serialize(String? packageDir, SystemCache cache) {
// Convert the dependencies to a simple object.
var packageMap = {};
var packageMap = <String, Object?>{};
for (final id in packages.values) {
packageMap[id.name] = {
'version': id.version.toString(),
Expand All @@ -432,7 +432,7 @@ class LockFile {
}

var data = {
'sdks': mapMap(
'sdks': mapMap<String, SdkConstraint, String, String>(
sdkConstraints,
value: (_, constraint) => constraint.effectiveConstraint.toString(),
),
Expand Down
6 changes: 3 additions & 3 deletions lib/src/oauth2.dart
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ Future<T> withClient<T>(Future<T> Function(http.Client) fn) {
// Be sure to save the credentials even when an error happens.
_saveCredentials(client.credentials);
});
}).catchError((error) {
}).catchError((Object error) {
if (error is _ExpirationException) {
log.error("Pub's authorization to upload packages has expired and "
"can't be automatically refreshed.");
Expand All @@ -139,7 +139,7 @@ Future<T> withClient<T>(Future<T> Function(http.Client) fn) {
return withClient(fn);
} else {
// ignore: only_throw_errors
throw error as Object;
throw error;
}
});
}
Expand Down Expand Up @@ -970,7 +970,7 @@ class Credentials {
///
/// Throws a [FormatException] if the JSON is incorrectly formatted.
factory Credentials.fromJson(String json) {
void validate(bool condition, message) {
void validate(bool condition, String message) {
if (condition) return;
throw FormatException('Failed to load credentials: $message.\n\n$json');
}
Expand Down
2 changes: 1 addition & 1 deletion lib/src/source/hosted.dart
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ class HostedSource extends CachedSource {
/// this throws a descriptive FormatException.
HostedDescription _parseDescription(
String packageName,
description,
Object? description,
LanguageVersion languageVersion,
) {
if (description == null) {
Expand Down
4 changes: 2 additions & 2 deletions lib/src/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ final _unquotableYamlString = RegExp(r'^[a-zA-Z_-][a-zA-Z_0-9-]*$');
String yamlToString(Object? data) {
var buffer = StringBuffer();

void stringify(bool isMapValue, String indent, data) {
void stringify(bool isMapValue, String indent, Object? data) {
// TODO(nweiz): Serialize using the YAML library once it supports
// serialization.

Expand Down Expand Up @@ -757,7 +757,7 @@ Future<T> retry<T>(
final rf = randomizationFactor * (random.nextDouble() * 2 - 1) + 1;
final exp = math.min(attempt, 31); // prevent overflows.
final delay = delayFactor * math.pow(2.0, exp) * rf;
await Future.delayed(delay < maxDelay ? delay : maxDelay);
await Future<void>.delayed(delay < maxDelay ? delay : maxDelay);
}
}

Expand Down
10 changes: 9 additions & 1 deletion test/cache/list_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,15 @@ void main() {
d.dir('hosted', [d.dir('pub.dev', [])]),
]).create();

await runPub(args: ['cache', 'list'], outputJson: {'packages': {}});
await runPub(
args: [
'cache',
'list',
],
outputJson: {
'packages': <String, Object>{},
},
);
});

test('running pub cache list', () async {
Expand Down
6 changes: 4 additions & 2 deletions test/dependency_services/dependency_services_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -631,9 +631,11 @@ Future<void> main() async {
}

dynamic findChangeVersion(dynamic json, String updateType, String name) {
final dep = json['dependencies'].firstWhere((p) => p['name'] == 'foo');
final dep =
json['dependencies'].firstWhere((dynamic p) => p['name'] == 'foo');
if (dep == null) return null;
return dep[updateType].firstWhere((p) => p['name'] == name)['version'];
return dep[updateType]
.firstWhere((dynamic p) => p['name'] == name)['version'];
}

class _PackageVersion {
Expand Down
2 changes: 1 addition & 1 deletion test/embedding/ensure_pubspec_resolved.dart
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ Future<void> _noImplicitPubGet({
Future _touch(String path) async {
// Delay a bit to make sure the modification times are noticeably different.
// 1s seems to be the finest granularity that dart:io reports.
await Future.delayed(Duration(seconds: 1));
await Future<void>.delayed(Duration(seconds: 1));

path = p.join(d.sandbox, 'myapp', path);
touch(path);
Expand Down
20 changes: 13 additions & 7 deletions test/error_group_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,13 @@ void main() {
expect(errorGroup.done, throwsFormatException);
errorGroup.signalError(FormatException());

expect(() => errorGroup.registerFuture(Future.value()), throwsStateError);
expect(
() => errorGroup.registerStream(StreamController(sync: true).stream),
() => errorGroup.registerFuture(Future<void>.value()),
throwsStateError,
);
expect(
() => errorGroup
.registerStream(StreamController<void>(sync: true).stream),
throwsStateError,
);
});
Expand Down Expand Up @@ -63,12 +67,14 @@ void main() {
completer.complete('value');

expect(
completer.future.then((_) => errorGroup.registerFuture(Future.value())),
completer.future
.then((_) => errorGroup.registerFuture(Future<void>.value())),
throwsStateError,
);
expect(
completer.future.then(
(_) => errorGroup.registerStream(StreamController(sync: true).stream),
(_) => errorGroup
.registerStream(StreamController<void>(sync: true).stream),
),
throwsStateError,
);
Expand Down Expand Up @@ -401,7 +407,7 @@ void main() {
test(
"shouldn't throw a top-level exception if a stream receives an error "
'after the other listened stream completes', () {
var signal = Completer();
var signal = Completer<void>();
expect(
stream1.toList().whenComplete(signal.complete),
completion(equals(['value1', 'value2'])),
Expand All @@ -423,7 +429,7 @@ void main() {
test(
"shouldn't throw a top-level exception if an error is signaled after "
'one listened stream completes', () {
var signal = Completer();
var signal = Completer<void>();
expect(
stream1.toList().whenComplete(signal.complete),
completion(equals(['value1', 'value2'])),
Expand Down Expand Up @@ -505,7 +511,7 @@ void main() {
test(
"shouldn't throw a top-level exception if the future receives an "
'error after the listened stream completes', () {
var signal = Completer();
var signal = Completer<void>();
expect(
stream.toList().whenComplete(signal.complete),
completion(equals(['value1', 'value2'])),
Expand Down
2 changes: 1 addition & 1 deletion test/lish/cloud_storage_upload_doesnt_redirect_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ void main() {
handleUploadForm(globalServer);

globalServer.expect('POST', '/upload', (request) async {
await request.read().drain();
await request.read().drain<void>();
return shelf.Response(200);
});

Expand Down
2 changes: 1 addition & 1 deletion test/lish/cloud_storage_upload_provides_an_error_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ void main() {
handleUploadForm(globalServer);

globalServer.expect('POST', '/upload', (request) {
return request.read().drain().then((_) {
return request.read().drain<void>().then((_) {
return shelf.Response.notFound(
'<Error><Message>Your request sucked.</Message></Error>',
headers: {'content-type': 'application/xml'},
Expand Down
2 changes: 1 addition & 1 deletion test/lish/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ void handleUpload(PackageServer server) {
// that the request body is correctly formatted. See issue 6952.
return request
.read()
.drain()
.drain<void>()
.then((_) => server.url)
.then((url) => shelf.Response.found(Uri.parse(url).resolve('/create')));
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ void main() {
var pub = await startPublish(globalServer);

globalServer.expect('POST', '/token', (request) {
return request.read().drain().then((_) {
return request.read().drain<void>().then((_) {
return shelf.Response(
400,
body: jsonEncode({'error': 'invalid_request'}),
Expand All @@ -46,7 +46,7 @@ void main() {
await expectLater(pub.stdout, emits(startsWith('Uploading...')));
await authorizePub(pub, globalServer, 'new access token');

var done = Completer();
var done = Completer<void>();
globalServer.expect('GET', '/api/packages/versions/new', (request) async {
expect(
request.headers,
Expand Down
6 changes: 3 additions & 3 deletions test/test_pub.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ String packageConfigFilePath =
Map<String, dynamic> packageSpec(String packageName) => json
.decode(File(d.path(packageConfigFilePath)).readAsStringSync())['packages']
.firstWhere(
(e) => e['name'] == packageName,
(dynamic e) => e['name'] == packageName,
orElse: () => null,
) as Map<String, dynamic>;

Expand Down Expand Up @@ -796,7 +796,7 @@ String binStubName(String name) => Platform.isWindows ? '$name.bat' : name;
void _validateOutput(
List<String> failures,
String pipe,
expected,
Object? expected,
String actual,
) {
if (expected == null) return;
Expand Down Expand Up @@ -884,7 +884,7 @@ void _validateOutputJson(
// Remove dart2js's timing logs, which would otherwise cause tests to fail
// flakily when compilation takes a long time.
actual['log']?.removeWhere(
(entry) =>
(dynamic entry) =>
entry['level'] == 'Fine' &&
(entry['message'] as String).startsWith('Not yet complete after'),
);
Expand Down
4 changes: 3 additions & 1 deletion test/token/remove_token_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ void main() {

await runPub(args: ['token', 'remove', 'https://server.demo']);

await d.tokensFile({'version': 1, 'hosted': []}).validate();
await d.tokensFile(
{'version': 1, 'hosted': <Map<String, String>>[]},
).validate();
});

test('without any matching schemes, does nothing', () async {
Expand Down
4 changes: 3 additions & 1 deletion test/token/when_receives_401_removes_token_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ void main() {

await pub.shouldExit(65);

await d.tokensFile({'version': 1, 'hosted': []}).validate();
await d.tokensFile(
{'version': 1, 'hosted': <Map<String, Object?>>[]},
).validate();
});
}
6 changes: 3 additions & 3 deletions test/utils_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ no: 1
});

test('handles non-string map keys', () {
var map = {};
var map = <Object?, Object?>{};
map[null] = 'null';
map[123] = 'num';
map[true] = 'bool';
Expand All @@ -92,7 +92,7 @@ true: bool'''),
test('handles empty maps', () {
expect(yamlToString({}), equals('{}'));
expect(
yamlToString({'a': {}, 'b': {}}),
yamlToString({'a': <Object, Object>{}, 'b': <Object, Object>{}}),
equals('''
a: {}
b: {}'''),
Expand Down Expand Up @@ -188,7 +188,7 @@ b: {}'''),
expect(() => hexEncode([256, 0, 1]), throwsA(isA<FormatException>()));
});
test('hexDecode', () {
expect(hexDecode(''), []);
expect(hexDecode(''), <int>[]);
expect(hexDecode('ff0001f0abcdef'), [255, 0, 1, 240, 171, 205, 239]);
expect(hexDecode('FF0001F0ABCDEF'), [255, 0, 1, 240, 171, 205, 239]);
expect(() => hexDecode('F'), throwsA(isA<FormatException>()));
Expand Down
3 changes: 2 additions & 1 deletion tool/extract_all_pub_dev.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ Future<void> main() async {
for (final packageName in json['packages'] as Iterable? ?? []) {
alreadyDonePackages.add(packageName as String);
}
for (final failure in (json['failures'] ?? []) as Iterable) {
for (final failure
in (json['failures'] ?? <Map<String, dynamic>>[]) as Iterable) {
failures.add(failure as Map<String, dynamic>);
}
}
Expand Down

0 comments on commit 97852ba

Please sign in to comment.