Skip to content

Commit

Permalink
[wildcards] support for library_prefixes
Browse files Browse the repository at this point in the history
Fixes: dart-lang/linter#5021

Change-Id: I43273a6bef6987298691daaf4b320a4d59e535be
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/375782
Reviewed-by: Brian Wilkerson <brianwilkerson@google.com>
Commit-Queue: Phil Quitslund <pquitslund@google.com>
  • Loading branch information
pq authored and Commit Queue committed Jul 15, 2024
1 parent 37f7206 commit 701eae7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
21 changes: 17 additions & 4 deletions pkg/linter/lib/src/rules/library_prefixes.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';

import '../analyzer.dart';
import '../utils.dart';
Expand Down Expand Up @@ -54,21 +56,32 @@ class LibraryPrefixes extends LintRule {
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
var visitor = _Visitor(this, context.libraryElement);
registry.addImportDirective(this, visitor);
}
}

class _Visitor extends SimpleAstVisitor<void> {
/// Whether the `wildcard_variables` feature is enabled.
final bool _wildCardVariablesEnabled;

final LintRule rule;

_Visitor(this.rule);
_Visitor(this.rule, LibraryElement? library)
: _wildCardVariablesEnabled =
library?.featureSet.isEnabled(Feature.wildcard_variables) ?? false;

@override
void visitImportDirective(ImportDirective node) {
var prefix = node.prefix;
if (prefix != null && !isValidLibraryPrefix(prefix.toString())) {
rule.reportLint(prefix, arguments: [prefix.toString()]);
if (prefix == null) return;

var prefixString = prefix.toString();
// With wildcards, `_` is allowed.
if (_wildCardVariablesEnabled && prefixString == '_') return;

if (!isValidLibraryPrefix(prefixString)) {
rule.reportLint(prefix, arguments: [prefixString]);
}
}
}
17 changes: 17 additions & 0 deletions pkg/linter/test/rules/library_prefixes_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,21 @@ import 'dart:async' as _1;
lint(23, 2),
]);
}

test_wildcard() async {
await assertNoDiagnostics(r'''
import 'dart:async' as _;
''');
}

test_wildcard_preWildCards() async {
await assertDiagnostics(r'''
// @dart = 3.4
// (pre wildcard-variables)
import 'dart:async' as _;
''', [
lint(67, 1),
]);
}
}

0 comments on commit 701eae7

Please sign in to comment.