|
| 1 | +// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'package:analyzer/dart/ast/ast.dart'; |
| 6 | +import 'package:analyzer/dart/ast/token.dart'; |
| 7 | +import 'package:analyzer/dart/ast/visitor.dart'; |
| 8 | + |
| 9 | +import '../analyzer.dart'; |
| 10 | + |
| 11 | +const _desc = r'Do use sound null safety.'; |
| 12 | + |
| 13 | +const _details = r''' |
| 14 | +**DO** use sound null safety, by not specifying a dart version lower than `2.12`. |
| 15 | +
|
| 16 | +**BAD:** |
| 17 | +```dart |
| 18 | +// @dart=2.8 |
| 19 | +a() { |
| 20 | +} |
| 21 | +``` |
| 22 | +
|
| 23 | +**GOOD:** |
| 24 | +```dart |
| 25 | +b() { |
| 26 | +} |
| 27 | +'''; |
| 28 | + |
| 29 | +class EnableNullSafety extends LintRule implements NodeLintRule { |
| 30 | + EnableNullSafety() |
| 31 | + : super( |
| 32 | + name: 'enable_null_safety', |
| 33 | + description: _desc, |
| 34 | + details: _details, |
| 35 | + group: Group.style); |
| 36 | + |
| 37 | + @override |
| 38 | + void registerNodeProcessors( |
| 39 | + NodeLintRegistry registry, LinterContext context) { |
| 40 | + var visitor = _Visitor(this, context); |
| 41 | + registry.addCompilationUnit(this, visitor); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +class _Visitor extends SimpleAstVisitor<void> { |
| 46 | + // to be kept in sync with LanguageVersionOverrideVerifier (added groups for the version) |
| 47 | + static final regExp = RegExp(r'^\s*//\s*@dart\s*=\s*(\d+)\.(\d+)'); |
| 48 | + final LintRule rule; |
| 49 | + final LinterContext context; |
| 50 | + |
| 51 | + _Visitor(this.rule, this.context); |
| 52 | + |
| 53 | + @override |
| 54 | + void visitCompilationUnit(CompilationUnit node) { |
| 55 | + var beginToken = node.beginToken; |
| 56 | + if (beginToken.type == TokenType.SCRIPT_TAG) { |
| 57 | + beginToken = beginToken.next!; |
| 58 | + } |
| 59 | + CommentToken? comment = beginToken.precedingComments; |
| 60 | + while (comment != null) { |
| 61 | + var match = regExp.firstMatch(comment.lexeme); |
| 62 | + if (match != null && match.groupCount == 2) { |
| 63 | + var major = int.parse(match.group(1)!); |
| 64 | + var minor = int.parse(match.group(2)!); |
| 65 | + if (major == 1 || (major == 2 && minor < 12)) { |
| 66 | + rule.reportLintForToken(comment); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + var next = comment.next; |
| 71 | + comment = next is CommentToken ? next : null; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments