From c12e339864843b5d0f06e0319f3c90b32c1956de Mon Sep 17 00:00:00 2001 From: pq Date: Fri, 20 Oct 2017 09:21:54 -0700 Subject: [PATCH] Fix comment_references to flag keywords (#808). Update `comment_references` to check for keywords that are not treated as references by the parser but should be flagged by the linter. Fixes: #808. --- lib/src/rules/comment_references.dart | 33 +++++++++++++++++++++++++++ test/rules/comment_references.dart | 6 +++++ 2 files changed, 39 insertions(+) diff --git a/lib/src/rules/comment_references.dart b/lib/src/rules/comment_references.dart index 2a67615aa..76b26c822 100644 --- a/lib/src/rules/comment_references.dart +++ b/lib/src/rules/comment_references.dart @@ -3,6 +3,7 @@ // BSD-style license that can be found in the LICENSE file. import 'package:analyzer/dart/ast/ast.dart'; +import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:linter/src/analyzer.dart'; @@ -48,6 +49,32 @@ class Visitor extends SimpleAstVisitor { final LintRule rule; Visitor(this.rule); + @override + visitComment(Comment node) { + // Check for keywords that are not treated as references by the parser + // but should be flagged by the linter. + // Note that no special care is taken to handle embedded code blocks. + for (Token token in node.tokens) { + if (!token.isSynthetic) { + String comment = token.lexeme; + int length = comment.length; + int leftIndex = comment.indexOf('['); + while (leftIndex >= 0 && leftIndex + 1 < length) { + int rightIndex = comment.indexOf(']', leftIndex); + if (rightIndex >= 0) { + String reference = comment.substring(leftIndex + 1, rightIndex); + if (_isParserSpecialCase(reference)) { + int nameOffset = token.offset + leftIndex + 1; + rule.reporter.reportErrorForOffset( + rule.lintCode, nameOffset, reference.length); + } + } + leftIndex = comment.indexOf('[', rightIndex); + } + } + } + } + @override visitCommentReference(CommentReference node) { Identifier identifier = node.identifier; @@ -55,4 +82,10 @@ class Visitor extends SimpleAstVisitor { rule.reportLint(identifier); } } + + bool _isParserSpecialCase(String reference) => + reference == 'this' || + reference == 'null' || + reference == 'true' || + reference == 'false'; } diff --git a/test/rules/comment_references.dart b/test/rules/comment_references.dart index 12f5cd7a8..ef63d1eb1 100644 --- a/test/rules/comment_references.dart +++ b/test/rules/comment_references.dart @@ -4,6 +4,12 @@ // test w/ `pub run test -N comment_references` +/// Keywords special cased by the parser should nonetheless lint: +/// [this] #LINT +/// [null] #LINT +/// [true] #LINT +/// [false] #LINT + /// Writes [y]. #LINT void write(int x) {}