Skip to content
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

Optimize path mapping lookups #59048

Merged
merged 14 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 2 additions & 2 deletions src/compiler/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2532,12 +2532,12 @@ export function matchedText(pattern: Pattern, candidate: string): string {
*
* @internal
*/
export function findBestPatternMatch<T>(values: readonly T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined {
export function findBestPatternMatch<T>(values: readonly T[], getPattern: (value: T) => Pattern, candidate: string, endIndex: number = values.length): T | undefined {
let matchedValue: T | undefined;
// use length of prefix as betterness criteria
let longestMatchPrefixLength = -1;

for (let i = 0; i < values.length; i++) {
for (let i = 0; i < endIndex; i++) {
const v = values[i];
const pattern = getPattern(v);
if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Wouldn't it be better to run these conditions in the reverse order? No point in running the cost of pattern matching if the pattern to be matched is a worse fit than the current best.

Copy link
Member Author

Choose a reason for hiding this comment

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

In practice, what will probably happen is we'll have an empty prefix, that'll match, and then everything after will still need to be checked. It probably makes sense to walk the list backwards looking for a match in case a long match is found, and then bail out as soon as an entry with a shorter prefix length is encountered.

Expand Down
100 changes: 93 additions & 7 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
BarBarEqualsToken,
BinaryExpression,
binarySearch,
binarySearchKey,
BindableObjectDefinePropertyCall,
BindableStaticAccessExpression,
BindableStaticElementAccessExpression,
Expand Down Expand Up @@ -339,6 +340,7 @@ import {
isParameterPropertyDeclaration,
isParenthesizedExpression,
isParenthesizedTypeNode,
isPatternMatch,
isPrefixUnaryExpression,
isPrivateIdentifier,
isPropertyAccessExpression,
Expand Down Expand Up @@ -10061,6 +10063,13 @@ export const emptyFileSystemEntries: FileSystemEntries = {
directories: emptyArray,
};

interface MatchPatternOrExactCacheEntry {
matchableStringSet: Set<string>;
sortedPatterns: Pattern[];
}

const patternOrStringsCache = new WeakMap<readonly (string | Pattern)[], MatchPatternOrExactCacheEntry>();

/**
* patternOrStrings contains both patterns (containing "*") and regular strings.
* Return an exact match if possible, or a pattern match, or undefined.
Expand All @@ -10069,18 +10078,95 @@ export const emptyFileSystemEntries: FileSystemEntries = {
* @internal
*/
export function matchPatternOrExact(patternOrStrings: readonly (string | Pattern)[], candidate: string): string | Pattern | undefined {
const patterns: Pattern[] = [];
for (const patternOrString of patternOrStrings) {
if (patternOrString === candidate) {
return candidate;
let matchableStringSet: Set<string>;
let sortedPatterns: Pattern[];

const cacheEntry = patternOrStringsCache.get(patternOrStrings);
if (cacheEntry !== undefined) {
({ matchableStringSet, sortedPatterns } = cacheEntry);
}
else {
matchableStringSet = new Set();
sortedPatterns = [];

for (const patternOrString of patternOrStrings) {
if (typeof patternOrString === "string") {
matchableStringSet.add(patternOrString);
}
else {
sortedPatterns.push(patternOrString);
}
}

sortedPatterns.sort((a, b) => compareStringsCaseSensitive(a.prefix, b.prefix));

patternOrStringsCache.set(patternOrStrings, {
matchableStringSet,
sortedPatterns,
});
}
DanielRosenwasser marked this conversation as resolved.
Show resolved Hide resolved

if (matchableStringSet.has(candidate)) {
return candidate;
}
if (sortedPatterns.length === 0) {
return undefined;
}

let index = binarySearchKey(sortedPatterns, candidate, getPatternPrefix, compareStringsCaseSensitive);
Copy link
Contributor

Choose a reason for hiding this comment

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

In Rush we have to efficiently match a large array of Git file paths to project prefixes as part of hashing our input states; for that we use this class which you might find useful for this application: https://github.com/microsoft/rushstack/blob/main/libraries/rush-lib/src/logic/LookupByPath.ts

Copy link
Contributor

@dmichon-msft dmichon-msft Jun 27, 2024

Choose a reason for hiding this comment

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

For some numbers, that tool matches 142936 unique file paths to 1279 unique path prefixes in 62 milliseconds on my codespace machine (single threaded). This is without taking any advantage of that the list of paths returned by Git are technically sorted.

if (index < 0) {
index = ~index;
}

if (index >= sortedPatterns.length) {
// If we are past the end of the array, then the candidate length just exceeds the last prefix.
// Bump us back into a reasonable range.
index--;
}

// `sortedPatterns` is sorted by prefixes, where longer prefixes should occur later;
// however, the sort is stable, so the original input order of patterns is preserved within each group.
// So for something like
//
// { prefix: "foo/", suffix: "bar"}, { "prefix: "", suffix: "" }, { prefix: "foo/", suffix: "" }, { "prefix: "", suffix: "bar" },
//
// we will end up with
//
// { "prefix: "", suffix: "" }, { "prefix: "", suffix: "bar" }, { prefix: "foo/", suffix: "bar"}, { prefix: "foo/", suffix: "" }
//
// guaranteeing that within a group, the first match is ideal.
//
// Now the binary search may have landed us in the very middle of a group. If we are searching for "foo/" in
//
// ..., { prefix: "foo/", suffix: "" }, { prefix: "foo/", suffix: "my-suffix" }, ...
//
// then we could have ended up on an exact match. Keep walking backwards on exact matches until we find the first.
// This will allow us to try out all patterns with an identical prefix, while maintaining the relative original order of the
// patterns as specified.
const groupPrefix = sortedPatterns[index].prefix;
while (index > 0 && groupPrefix === sortedPatterns[index - 1].prefix) {
index--;
}

for (let i = index; i < sortedPatterns.length; i++) {
const currentPattern = sortedPatterns[i];
if (currentPattern.prefix !== groupPrefix) {
break;
}

if (!isString(patternOrString)) {
patterns.push(patternOrString);
if (isPatternMatch(currentPattern, candidate)) {
return currentPattern;
}
}

return findBestPatternMatch(patterns, _ => _, candidate);
// We could not find a pattern within the group that matched.
// Technically we could walk backwards from here and find likely matches.
// For now, we'll just do a simple linear search up to the current group index.
return findBestPatternMatch(sortedPatterns, _ => _, candidate, /*endIndex*/ index);
}

function getPatternPrefix(pattern: Pattern) {
return pattern.prefix;
}

/** @internal */
Expand Down