Skip to content

Use a trie to quickly skip templates in union creation #59759

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 46 additions & 3 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ import {
createModuleNotFoundChain,
createMultiMap,
createNameResolver,
createPrefixSuffixTrie,
createPrinterWithDefaults,
createPrinterWithRemoveComments,
createPrinterWithRemoveCommentsNeverAsciiEscape,
Expand Down Expand Up @@ -17669,13 +17670,55 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

function removeStringLiteralsMatchedByTemplateLiterals(types: Type[]) {
const templates = filter(types, isPatternLiteralType) as (TemplateLiteralType | StringMappingType)[];
if (templates.length) {
let patterns = filter(types, isPatternLiteralType) as (TemplateLiteralType | StringMappingType)[];
const templateLiterals = filter(patterns, t => !!(t.flags & TypeFlags.TemplateLiteral)) as TemplateLiteralType[];

const estimatedCount = templateLiterals.length * countWhere(types, t => !!(t.flags & TypeFlags.StringLiteral));
// TODO(jakebailey): set higher limit after testing
if (estimatedCount > 0) {
// To remove string literals already covered by template literals, we may potentially
// check every string literal against every template literal, leading to a combinatoric
// explosion. This is made even worse if the strings all share common prefixes or suffixes,
// making the "fast path" of a prefix check in inferFromLiteralPartsToTemplateLiteral not actually
// very fast as we'll repeatedly scan the strings much farther than just a few characters.
//
// To reduce the amount of work we need to do, we can build a two-way trie out of the
// template literals, only checking those which can be satisfied by a given string.

const trie = createPrefixSuffixTrie<TemplateLiteralType[]>();

forEach(templateLiterals, t => {
const prefix = t.texts[0];
const suffix = t.texts[t.texts.length - 1];
trie.set(prefix, suffix, templates => append(templates, t));
});

let i = types.length;
outer: while (i > 0) {
i--;
const t = types[i];
if (!(t.flags & TypeFlags.StringLiteral)) continue;
const text = (t as StringLiteralType).value;

for (const templates of trie.iterateAllMatches(text)) {
if (some(templates, template => isTypeMatchedByTemplateLiteralOrStringMapping(t, template))) {
orderedRemoveItemAt(types, i);
continue outer;
}
}
}

// Fall through into the general case with just the string mappings.
patterns = filter(patterns, t => !!(t.flags & TypeFlags.StringMapping)) as StringMappingType[];
}

if (patterns.length) {
let i = types.length;
while (i > 0) {
i--;
const t = types[i];
if (t.flags & TypeFlags.StringLiteral && some(templates, template => isTypeMatchedByTemplateLiteralOrStringMapping(t, template))) {
if (!(t.flags & TypeFlags.StringLiteral)) continue;
if (some(patterns, template => isTypeMatchedByTemplateLiteralOrStringMapping(t, template))) {
orderedRemoveItemAt(types, i);
}
}
Expand Down
93 changes: 93 additions & 0 deletions src/compiler/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2590,3 +2590,96 @@ export function isNodeLikeSystem(): boolean {
&& !(process as any).browser
&& typeof require !== "undefined";
}

/** @internal */
export interface PrefixSuffixTrie<T extends {}> {
iterateAllMatches(input: string): Iterable<T>;
set(prefix: string, suffix: string, fn: (value: T | undefined) => T | undefined): void;
hasAnyMatch(input: string): boolean;
}

/** @internal */
export function createPrefixSuffixTrie<T extends {}>(): PrefixSuffixTrie<T> {
interface Trie<T extends {}> {
children: Record<string, Trie<T>> | undefined;
value: T | undefined;
}

function createTrie<T extends {}>(): Trie<T> {
return {
children: undefined,
value: undefined,
};
}

const root = createTrie<Trie<T>>();

function* iterateAllMatches(input: string) {
let node = root;

if (node.value) {
yield* iterateSuffix(node.value, 0);
}

for (let i = 0; i < input.length; i++) {
const child = node.children?.[input[i]];
if (!child) break;
if (child.value) {
yield* iterateSuffix(child.value, i + 1);
}
node = child;
}

return;

function* iterateSuffix(node: Trie<T>, start: number) {
if (node.value) {
yield node.value;
}

for (let i = input.length - 1; i >= start; i--) {
const child = node.children?.[input[i]];
if (!child) break;
if (child.value) {
yield child.value;
}
node = child;
}
}
}

function set(prefix: string, suffix: string, fn: (value: T | undefined) => T | undefined) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An interesting thing about building tries dynamically is that they can grow quite large in memory consumed rather quickly when you do something like this and always create new trie nodes for every new match state. When you're matching a whole dictionary, for example, this can quickly become untenably large. All is not lost, however - there are a large number of sub-tries that are identical (for example, the -es suffix trie), and you can save quite a bit of space at the cost of some time by compressing the trie by unifying all those subtrees. So rather than having a trie like

stateDiagram-v2
    1:_ 
    2:_
    3:_
    4:_
    5:_
    6:_
    7:_
    8:_
    9:_
    10:_
    11:_
    12:_
    [*] --> 1 : s
    1 --> 2 : p
    2 --> 3 : a
    3 --> 4 : c
    4 --> 5 : e
    5 --> 6 : s
    6 --> [*] : End of string
    [*] --> 7 : p
    7 --> 8 : l
    8 --> 9 : a
    9 --> 10 : c
    10 --> 11 : e
    11 --> 12 : s
    12 --> [*] : End of string
Loading

you compress it like so

stateDiagram-v2
    s:_
    p:_
    a:_
    c:_
    e:_
    s`:_
    p`:_
    l:_
    [*] --> s : s
    s --> p : p
    p --> a : a
    a --> c : c
    c --> e : e
    e --> s` : s
    s` --> [*] : End of string
    [*] --> p` : p
    p` --> l : l
    l --> a : a
Loading

or, better yet,

stateDiagram-v2
    s:_
    p:_
    p`:_
    l:_
    [*] --> s : s
    s --> p : p
    p --> [*] : aces
    [*] --> p` : p
    p` --> l : l
    l --> [*] : aces
Loading

Which, a quick search seems to indicate is referred to either as a "compressed trie" or just a "suffix tree". Extra memory efficiency, since JS is GC'd, can change the breakpoint where it's worth it to swap between the naive scan and the trie-based structure.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I thought about compressing the trie into a proper radix tree, but wasn't sure if that would be worth it in the end (and the implementation does get more complicated). But I can give it a try.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main problem is just that the edges being strings means that I don't know how to walk down them without iterating over each of them...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess radix tress ensure that the children are keyed on equal length prefixes, so that would work.

However, your example coming together like this I don't think works out for our use case here; otherwise as we walk down the graph, we'll merge together with template literals that don't actually match (because they came from another branch) and not reduce the number of inferences that much.

A proper radix tree doesn't converge like this so would at least still be optimal, I think, so I may attempt that if I have a change.

let prefixNode = root;

for (let i = 0; i < prefix.length; i++) {
const char = prefix[i];
const children = prefixNode.children ??= {};
const child = children[char] ??= createTrie();
prefixNode = child;
}

let suffixNode = prefixNode.value ??= createTrie();

for (let i = suffix.length - 1; i >= 0; i--) {
const char = suffix[i];
const children = suffixNode.children ??= {};
const child = children[char] ??= createTrie();
suffixNode = child;
}

suffixNode.value = fn(suffixNode.value);
}

function hasAnyMatch(input: string) {
for (const _ of iterateAllMatches(input)) {
return true;
}
return false;
}
Comment on lines +2673 to +2678
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused in this PR but would be used in #59058.


return {
iterateAllMatches,
set,
hasAnyMatch,
};
}