Skip to content

Commit ef300f5

Browse files
srawlinsCommit Queue
authored and
Commit Queue
committed
analyzer: allow LintCode instances to set their own severity
Work towards #53402 Letting plugin authors set the default severity of a lint code is a top request. Users can still customize severities with analysis options. Change-Id: Id0a360f4a96ca9627f00d63d3487bfde554b74e8 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/430260 Reviewed-by: Brian Wilkerson <[email protected]> Commit-Queue: Samuel Rawlins <[email protected]> Reviewed-by: Konstantin Shcheglov <[email protected]>
1 parent b37171c commit ef300f5

File tree

5 files changed

+82
-29
lines changed

5 files changed

+82
-29
lines changed

pkg/analysis_server_plugin/lib/src/plugin_server.dart

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ class PluginServer {
377377
AnalysisRuleVisitor(nodeRegistry, shouldPropagateExceptions: true));
378378

379379
var ignoreInfo = IgnoreInfo.forDart(unitResult.unit, unitResult.content);
380-
var errors = listener.errors.where((e) {
380+
var diagnostics = listener.errors.where((e) {
381381
var pluginName = pluginCodeMapping[e.errorCode.name];
382382
if (pluginName == null) {
383383
// If [e] is somehow not mapped, something is wrong; but don't mark it
@@ -389,27 +389,40 @@ class PluginServer {
389389

390390
// The list of the `AnalysisError`s and their associated
391391
// `protocol.AnalysisError`s.
392-
var errorsAndProtocolErrors = [
393-
for (var e in errors)
392+
var diagnosticsAndProtocolErrors = [
393+
for (var diagnostic in diagnostics)
394394
(
395-
diagnostic: e,
395+
diagnostic: diagnostic,
396396
protocolError: protocol.AnalysisError(
397-
protocol.AnalysisErrorSeverity.INFO,
397+
_severityOf(diagnostic),
398398
protocol.AnalysisErrorType.STATIC_WARNING,
399-
_locationFor(currentUnit.unit, path, e),
400-
e.message,
401-
e.errorCode.name,
402-
correction: e.correctionMessage,
399+
_locationFor(currentUnit.unit, path, diagnostic),
400+
diagnostic.message,
401+
diagnostic.errorCode.name,
402+
correction: diagnostic.correctionMessage,
403403
// TODO(srawlins): Use a valid value here.
404404
hasFix: true,
405405
)
406406
),
407407
];
408408
_recentState[path] = (
409409
analysisContext: analysisContext,
410-
errors: [...errorsAndProtocolErrors],
410+
errors: [...diagnosticsAndProtocolErrors],
411411
);
412-
return errorsAndProtocolErrors.map((e) => e.protocolError).toList();
412+
return diagnosticsAndProtocolErrors.map((e) => e.protocolError).toList();
413+
}
414+
415+
/// Converts the severity of [diagnostic] into a
416+
/// [protocol.AnalysisErrorSeverity].
417+
protocol.AnalysisErrorSeverity _severityOf(Diagnostic diagnostic) {
418+
try {
419+
return protocol.AnalysisErrorSeverity.values
420+
.byName(diagnostic.severity.name.toUpperCase());
421+
} catch (_) {
422+
assert(false, 'Invalid severity: ${diagnostic.severity}');
423+
// Return the default severity of `LintCode`.
424+
return protocol.AnalysisErrorSeverity.INFO;
425+
}
413426
}
414427

415428
/// Invokes [fn] first for priority analysis contexts, then for the rest.

pkg/analysis_server_plugin/test/src/lint_rules.dart

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,27 @@ class NoDoublesRule extends AnalysisRule {
4141
}
4242
}
4343

44+
class NoDoublesWarningRule extends AnalysisRule {
45+
static const LintCode code = LintCode(
46+
'no_doubles_warning',
47+
'No doubles message',
48+
severity: DiagnosticSeverity.WARNING,
49+
);
50+
51+
NoDoublesWarningRule()
52+
: super(name: 'no_doubles_warning', description: 'No doubles message');
53+
54+
@override
55+
DiagnosticCode get diagnosticCode => code;
56+
57+
@override
58+
void registerNodeProcessors(
59+
NodeLintRegistry registry, LinterContext context) {
60+
var visitor = _NoDoublesVisitor(this);
61+
registry.addDoubleLiteral(this, visitor);
62+
}
63+
}
64+
4465
class _NoBoolsVisitor extends SimpleAstVisitor<void> {
4566
final AnalysisRule rule;
4667

pkg/analysis_server_plugin/test/src/plugin_server_test.dart

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,22 @@ bool b = false;
144144
expect(result.fixes.first.fixes, hasLength(4));
145145
}
146146

147-
Future<void> test_lintDiagnosticsAreDisabledByDefault() async {
147+
Future<void> test_lintCodesCanHaveCustomSeverity() async {
148+
writeAnalysisOptionsWithPlugin({'no_doubles_warning': true});
149+
newFile(filePath, 'double x = 3.14;');
150+
await channel
151+
.sendRequest(protocol.AnalysisSetContextRootsParams([contextRoot]));
152+
var paramsQueue = _analysisErrorsParams;
153+
var params = await paramsQueue.next;
154+
expect(params.errors, hasLength(1));
155+
_expectAnalysisError(
156+
params.errors.single,
157+
message: 'No doubles message',
158+
severity: protocol.AnalysisErrorSeverity.WARNING,
159+
);
160+
}
161+
162+
Future<void> test_lintRulesAreDisabledByDefault() async {
148163
writeAnalysisOptionsWithPlugin();
149164
newFile(filePath, 'double x = 3.14;');
150165
await channel
@@ -154,7 +169,7 @@ bool b = false;
154169
expect(params.errors, isEmpty);
155170
}
156171

157-
Future<void> test_lintDiagnosticsCanBeEnabled() async {
172+
Future<void> test_lintRulesCanBeEnabled() async {
158173
writeAnalysisOptionsWithPlugin({'no_doubles': true});
159174
newFile(filePath, 'double x = 3.14;');
160175
await channel
@@ -234,7 +249,7 @@ bool b = false;
234249
_expectAnalysisError(params.errors.single, message: 'No bools message');
235250
}
236251

237-
Future<void> test_warningDiagnosticsAreEnabledByDefault() async {
252+
Future<void> test_warningRulesAreEnabledByDefault() async {
238253
writeAnalysisOptionsWithPlugin();
239254
newFile(filePath, 'bool b = false;');
240255
await channel
@@ -245,7 +260,7 @@ bool b = false;
245260
_expectAnalysisError(params.errors.single, message: 'No bools message');
246261
}
247262

248-
Future<void> test_warningDiagnosticsCanBeDisabled() async {
263+
Future<void> test_warningRulesCanBeDisabled() async {
249264
writeAnalysisOptionsWithPlugin({'no_bools': false});
250265
newFile(filePath, 'bool b = false;');
251266
await channel
@@ -270,13 +285,16 @@ plugins:
270285
newAnalysisOptionsYamlFile(packagePath, buffer.toString());
271286
}
272287

273-
void _expectAnalysisError(protocol.AnalysisError error,
274-
{required String message}) {
288+
void _expectAnalysisError(
289+
protocol.AnalysisError error, {
290+
required String message,
291+
protocol.AnalysisErrorSeverity severity =
292+
protocol.AnalysisErrorSeverity.INFO,
293+
}) {
275294
expect(
276295
error,
277296
isA<protocol.AnalysisError>()
278-
.having((e) => e.severity, 'severity',
279-
protocol.AnalysisErrorSeverity.INFO)
297+
.having((e) => e.severity, 'severity', severity)
280298
.having(
281299
(e) => e.type, 'type', protocol.AnalysisErrorType.STATIC_WARNING)
282300
.having((e) => e.message, 'message', message),
@@ -313,6 +331,7 @@ class _NoLiteralsPlugin extends Plugin {
313331
void register(PluginRegistry registry) {
314332
registry.registerWarningRule(NoBoolsRule());
315333
registry.registerLintRule(NoDoublesRule());
334+
registry.registerLintRule(NoDoublesWarningRule());
316335
registry.registerFixForRule(NoBoolsRule.code, _WrapInQuotes.new);
317336
registry.registerAssist(_InvertBoolean.new);
318337
}

pkg/analyzer/api.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4436,7 +4436,7 @@ package:analyzer/error/error.dart:
44364436
compareTo (method: int Function(DiagnosticType))
44374437
toString (method: String Function())
44384438
LintCode (class extends DiagnosticCode):
4439-
new (constructor: LintCode Function(String, String, {String? correctionMessage, bool hasPublishedDocs, String? uniqueName}))
4439+
new (constructor: LintCode Function(String, String, {String? correctionMessage, bool hasPublishedDocs, DiagnosticSeverity severity, String? uniqueName}))
44404440
errorSeverity (getter: DiagnosticSeverity)
44414441
hashCode (getter: int)
44424442
type (getter: DiagnosticType)

pkg/analyzer/lib/src/dart/error/lint_codes.dart

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,29 @@ library;
88
import 'package:_fe_analyzer_shared/src/base/analyzer_public_api.dart';
99
import 'package:analyzer/error/error.dart';
1010

11-
/// Defines style and best practice recommendations.
11+
/// Diagnostic codes which are not reported by default.
1212
///
13-
/// Unlike [WarningCode]s, which are akin to traditional static warnings from a
14-
/// compiler, lint recommendations focus on matters of avoiding errors,
15-
/// unintended code, maintainability, style and other best practices that might
16-
/// be aggregated to define a project's style guide.
13+
/// Lint codes are only reported when a lint rule (either a first-party lint
14+
/// rule, or one declared in an analyzer plugin) is enabled.
1715
@AnalyzerPublicApi(message: 'exported by lib/error/error.dart')
1816
class LintCode extends DiagnosticCode {
17+
@override
18+
final DiagnosticSeverity errorSeverity;
19+
1920
const LintCode(
2021
String name,
2122
String problemMessage, {
2223
super.correctionMessage,
2324
super.hasPublishedDocs,
2425
String? uniqueName,
25-
}) : super(
26+
DiagnosticSeverity severity = DiagnosticSeverity.INFO,
27+
}) : errorSeverity = severity,
28+
super(
2629
problemMessage: problemMessage,
2730
name: name,
2831
uniqueName: uniqueName ?? 'LintCode.$name',
2932
);
3033

31-
@override
32-
DiagnosticSeverity get errorSeverity => DiagnosticSeverity.INFO;
33-
3434
@override
3535
int get hashCode => uniqueName.hashCode;
3636

0 commit comments

Comments
 (0)