Skip to content

Use more explicit operations in core helpers (and other nits) #58873

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

Merged
merged 16 commits into from
Jun 18, 2024
Merged
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
6 changes: 3 additions & 3 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ import {
appendIfUnique,
ArrayBindingPattern,
arrayFrom,
arrayIsEqualTo,
arrayIsHomogeneous,
ArrayLiteralExpression,
arrayOf,
arraysEqual,
arrayToMultiMap,
ArrayTypeNode,
ArrowFunction,
Expand Down Expand Up @@ -25860,7 +25860,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
function inferTypesFromTemplateLiteralType(source: Type, target: TemplateLiteralType): Type[] | undefined {
return source.flags & TypeFlags.StringLiteral ? inferFromLiteralPartsToTemplateLiteral([(source as StringLiteralType).value], emptyArray, target) :
source.flags & TypeFlags.TemplateLiteral ?
arraysEqual((source as TemplateLiteralType).texts, target.texts) ? map((source as TemplateLiteralType).types, (s, i) => {
arrayIsEqualTo((source as TemplateLiteralType).texts, target.texts) ? map((source as TemplateLiteralType).types, (s, i) => {
return isTypeAssignableTo(getBaseConstraintOrType(s), getBaseConstraintOrType(target.types[i])) ? s : getStringLikeTypeForType(s);
}) :
inferFromLiteralPartsToTemplateLiteral((source as TemplateLiteralType).texts, (source as TemplateLiteralType).types, target) :
Expand Down Expand Up @@ -28625,7 +28625,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType)));
}
const result = recombineUnknownType(getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction));
if (result !== declaredType && result.flags & declaredType.flags & TypeFlags.Union && arraysEqual((result as UnionType).types, (declaredType as UnionType).types)) {
if (result !== declaredType && result.flags & declaredType.flags & TypeFlags.Union && arrayIsEqualTo((result as UnionType).types, (declaredType as UnionType).types)) {
return declaredType;
}
return result;
Expand Down
4 changes: 1 addition & 3 deletions src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2580,9 +2580,7 @@ export function convertToTSConfig(configParseResult: ParsedCommandLine, configFi

/** @internal */
export function optionMapToObject(optionMap: Map<string, CompilerOptionsValue>): object {
return {
...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ ...prev, [cur[0]]: cur[1] }), {}),
};
return Object.fromEntries(optionMap);
}

function filterSameAsDefaultInclude(specs: readonly string[] | undefined) {
Expand Down
174 changes: 79 additions & 95 deletions src/compiler/core.ts

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion src/compiler/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import {
LiteralType,
map,
MatchingKeys,
maxBy,
ModifierFlags,
Node,
NodeArray,
Expand Down Expand Up @@ -1126,7 +1127,7 @@ m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n")

function renderGraph() {
const columnCount = columnWidths.length;
const laneCount = nodes.reduce((x, n) => Math.max(x, n.lane), 0) + 1;
const laneCount = maxBy(nodes, 0, n => n.lane) + 1;
const lanes: string[] = fill(Array(laneCount), "");
const grid: (FlowGraphNode | undefined)[][] = columnWidths.map(() => Array(laneCount));
const connectors: Connection[][] = columnWidths.map(() => fill(Array(laneCount), 0));
Expand Down
4 changes: 2 additions & 2 deletions src/compiler/scanner.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
append,
arraysEqual,
arrayIsEqualTo,
binarySearch,
CharacterCodes,
CommentDirective,
Expand Down Expand Up @@ -475,7 +475,7 @@ export function computePositionOfLineAndCharacter(lineStarts: readonly number[],
line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
}
else {
Debug.fail(`Bad line number. Line: ${line}, lineStarts.length: ${lineStarts.length} , line map is correct? ${debugText !== undefined ? arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"}`);
Debug.fail(`Bad line number. Line: ${line}, lineStarts.length: ${lineStarts.length} , line map is correct? ${debugText !== undefined ? arrayIsEqualTo(lineStarts, computeLineStarts(debugText)) : "unknown"}`);
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/compiler/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import {
isReferenceFileLocation,
isString,
last,
maxBy,
maybeBind,
memoize,
ModuleKind,
Expand Down Expand Up @@ -305,7 +306,7 @@ function createTabularErrorsDisplay(filesInError: (ReportFileInError | undefined

const numberLength = (num: number) => Math.log(num) * Math.LOG10E + 1;
const fileToErrorCount = distinctFiles.map(file => ([file, countWhere(filesInError, fileInError => fileInError!.fileName === file!.fileName)] as const));
const maxErrors = fileToErrorCount.reduce((acc, value) => Math.max(acc, value[1] || 0), 0);
const maxErrors = maxBy(fileToErrorCount, 0, value => value[1]);

const headerRow = Diagnostics.Errors_Files.message;
const leftColumnHeadingLength = headerRow.split(" ")[0].length;
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
const leftColumnHeadingLength = headerRow.split(" ")[0].length;
const leftColumnFirstSpace = headerRow.indexOf(" ");
const leftColumnHeadingLength = leftColumnFirstSpace < 0 ? headerRow.length : leftColumnFirstSpace;

Though I assume this line isn't a hot path.

Expand Down
15 changes: 5 additions & 10 deletions src/harness/fourslashImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2642,17 +2642,12 @@ export class TestState {
if (info === undefined) return "No completion info.";
const { entries } = info;

function pad(s: string, length: number) {
return s + new Array(length - s.length + 1).join(" ");
}
function max<T>(arr: T[], selector: (x: T) => number): number {
return arr.reduce((prev, x) => Math.max(prev, selector(x)), 0);
}
const longestNameLength = max(entries, m => m.name.length);
const longestKindLength = max(entries, m => m.kind.length);
const longestNameLength = ts.maxBy(entries, 0, m => m.name.length);
const longestKindLength = ts.maxBy(entries, 0, m => m.kind.length);
entries.sort((m, n) => m.sortText > n.sortText ? 1 : m.sortText < n.sortText ? -1 : m.name > n.name ? 1 : m.name < n.name ? -1 : 0);
const membersString = entries.map(m => `${pad(m.name, longestNameLength)} ${pad(m.kind, longestKindLength)} ${m.kindModifiers} ${m.isRecommended ? "recommended " : ""}${m.source === undefined ? "" : m.source}`).join("\n");
Harness.IO.log(membersString);

const formattedEntries = entries.map(m => `${m.name.padEnd(longestNameLength)} ${m.kind.padEnd(longestKindLength)} ${m.kindModifiers} ${m.isRecommended ? "recommended " : ""}${m.source ?? ""}`);
Harness.IO.log(formattedEntries.join("\n"));
}

public printContext() {
Expand Down
12 changes: 6 additions & 6 deletions src/server/editorServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ import {
LanguageServiceMode,
length,
map,
mapDefinedEntries,
mapDefinedIterator,
missingFileModifiedTime,
MultiMap,
Expand Down Expand Up @@ -4273,14 +4272,15 @@ export class ProjectService {

/** @internal */
loadAncestorProjectTree(forProjects?: ReadonlyCollection<string>) {
forProjects = forProjects || mapDefinedEntries(
this.configuredProjects,
(key, project) => !project.isInitialLoadPending() ? [key, true] : undefined,
forProjects ??= new Set(
mapDefinedIterator(this.configuredProjects.entries(), ([key, project]) => !project.isInitialLoadPending() ? key : undefined),
);

const seenProjects = new Set<NormalizedPath>();
// Work on array copy as we could add more projects as part of callback
for (const project of arrayFrom(this.configuredProjects.values())) {
// We must copy the current configured projects into a separate array,
// as we could end up creating and adding more projects indirectly.
const currentConfiguredProjects = arrayFrom(this.configuredProjects.values());
for (const project of currentConfiguredProjects) {
// If this project has potential project reference for any of the project we are loading ancestor tree for
// load this project first
if (forEachPotentialProjectReference(project, potentialRefPath => forProjects.has(potentialRefPath))) {
Expand Down
4 changes: 2 additions & 2 deletions src/services/jsDoc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
arraysEqual,
arrayIsEqualTo,
ArrowFunction,
AssignmentDeclarationKind,
BinaryExpression,
Expand Down Expand Up @@ -222,7 +222,7 @@ export function getJsDocCommentsFromDeclarations(declarations: readonly Declarat
}

function isIdenticalListOfDisplayParts(parts1: SymbolDisplayPart[], parts2: SymbolDisplayPart[]) {
return arraysEqual(parts1, parts2, (p1, p2) => p1.kind === p2.kind && p1.text === p2.text);
return arrayIsEqualTo(parts1, parts2, (p1, p2) => p1.kind === p2.kind && p1.text === p2.text);
}

function getCommentHavingNodes(declaration: Declaration): readonly (JSDoc | JSDocTag)[] {
Expand Down