scanDartDirectives function
The directives of source, in order.
Implementation
List<DartDirective> scanDartDirectives(String source) {
final tokens = _Tokenizer(source).tokens();
final directives = <DartDirective>[];
var depth = 0;
_Token? previous;
for (var i = 0; i < tokens.length; i++) {
final token = tokens[i];
if (token.kind == _TokenKind.punct) {
if (token.text == '{') depth++;
if (token.text == '}' && depth > 0) depth--;
}
final atStatementStart =
previous == null ||
(previous.kind == _TokenKind.punct &&
(previous.text == ';' || previous.text == '}'));
if (depth == 0 &&
atStatementStart &&
token.kind == _TokenKind.ident &&
(token.text == 'import' ||
token.text == 'export' ||
token.text == 'part')) {
var kind = switch (token.text) {
'import' => DartDirectiveKind.import,
'export' => DartDirectiveKind.export,
_ => DartDirectiveKind.part,
};
final uris = <String>[];
int? line;
var j = i + 1;
if (kind == DartDirectiveKind.part &&
j < tokens.length &&
tokens[j].kind == _TokenKind.ident &&
tokens[j].text == 'of') {
kind = DartDirectiveKind.partOf;
j++;
}
for (; j < tokens.length; j++) {
final t = tokens[j];
if (t.kind == _TokenKind.punct && t.text == ';') break;
if (t.kind == _TokenKind.string) {
uris.add(t.text);
line ??= t.line;
}
}
directives.add(DartDirective(kind, uris, line ?? token.line));
i = j;
previous = j < tokens.length ? tokens[j] : null;
continue;
}
previous = token;
}
return directives;
}