Skip to content

Commit 04945d9

Browse files
authored
Fix StringTrie so it handles partial matches better (#2813)
1 parent a3ca4cf commit 04945d9

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

lib/src/comment_references/parser.dart

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,22 @@ class StringTrie {
3636
/// Does [this] node represent a valid entry in the trie?
3737
bool valid = false;
3838

39-
/// Greedily match on the string trie. Returns the index of the first
40-
/// non-operator character if valid, otherwise -1.
41-
int match(String toMatch, [int index = 0]) {
42-
if (index < 0 || index >= toMatch.length) return valid ? index : 1;
39+
/// Greedily match on the string trie starting at the given index. Returns
40+
/// the index of the first non-operator character if a match is valid,
41+
/// otherwise -1.
42+
int match(String toMatch, [int index = 0, int lastValid = -1]) {
43+
if (index < 0 || index > toMatch.length) {
44+
return lastValid;
45+
}
46+
if (index == toMatch.length) {
47+
return valid ? index : lastValid;
48+
}
4349
var matchChar = toMatch.codeUnitAt(index);
4450
if (children.containsKey(matchChar)) {
45-
return children[matchChar].match(toMatch, index + 1);
51+
lastValid = valid ? index : lastValid;
52+
return children[matchChar].match(toMatch, index + 1, lastValid);
4653
}
47-
return valid ? index : -1;
54+
return valid ? index : lastValid;
4855
}
4956

5057
void addWord(String toAdd) {

test/comment_referable/parser_test.dart

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,30 @@ void main() {
2727
isEmpty);
2828
}
2929

30+
group('StringTrie tests', () {
31+
test('test partials', () {
32+
var trie = StringTrie()..addWord('longerString');
33+
expect(trie.match('l'), equals(-1));
34+
expect(trie.match('longerStringWithExtras'), equals(12));
35+
expect(trie.match('longerString'), equals(12));
36+
expect(trie.match('prefix-longerString'), equals(-1));
37+
});
38+
39+
test('substrings', () {
40+
var trie = StringTrie();
41+
trie.addWord('aString');
42+
trie.addWord('aStr');
43+
trie.addWord('a');
44+
expect(trie.match('a'), equals(1));
45+
expect(trie.match('aS'), equals(1));
46+
expect(trie.match('aStr'), equals(4));
47+
expect(trie.match('aStringTwo'), equals(7));
48+
});
49+
});
50+
3051
group('Basic comment reference parsing', () {
3152
test('Check that basic references parse', () {
53+
expectParseEquivalent('Funvas.u', ['Funvas', 'u']);
3254
expectParseEquivalent('valid', ['valid']);
3355
expectParseEquivalent('new valid', ['valid'], constructorHint: true);
3456
expectParseEquivalent('valid()', ['valid'], callableHint: true);

0 commit comments

Comments
 (0)