我正在使用Dart Analyzer package中的标记器,从this example中的代码开始。
我已经调整了代码,只是吐出令牌(不使用Parser)来尝试追踪我的问题。所以我的代码看起来像这样:
import 'dart:io';
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/scanner.dart';
void main(List<String> args) {
// Dummy code to parse (contains comments!)
var src = """
// test
/* test */
import 'dartd:io';
// This is a test
""";
// Tokenise the code
var errorListener = new _ErrorCollector();
var reader = new CharSequenceReader(src);
var scanner = new Scanner(null, reader, errorListener);
var token = scanner.tokenize();
// Dump all tokens to screen
while (token != null && token.type != TokenType.EOF)
{
print(token);
token = token.next;
}
然而,当我运行它时,评论消失了:
import
'dartd:io'
;
我正在挖掘Scanner code试图了解评论的去向,没有快乐。有一个名为_preserveComments
的布尔值,但无论如何都默认为true!
答案 0 :(得分:4)
评论似乎在他们自己的令牌链中。您可以通过普通令牌的precedingComments
访问者访问它们,然后您需要使用next
遍历每个评论,直到结束:
// Dump all tokens to screen
while (token != null && token.type != TokenType.EOF)
{
printComments(token);
print(token);
token = token.next;
if(token.type == TokenType.EOF) {
printComments(token);
}
}
void printComments(Token token) {
var comments = token.precedingComments;
while(comments != null) {
print(comments);
comments = comments.next;
}
}