From 01701b2ae445216da63a63dfb4de5c25279aa084 Mon Sep 17 00:00:00 2001 From: JordanBoltonMN Date: Fri, 2 Sep 2022 08:47:15 -0700 Subject: [PATCH] Update code style (#341) * initial commit * more changes * more changes * purged last maybe * removing Fn suffix * updating package --- package-lock.json | 4 +- package.json | 2 +- src/example.ts | 10 +- src/powerquery-parser/common/arrayUtils.ts | 66 +- src/powerquery-parser/common/assert.ts | 42 +- src/powerquery-parser/common/error.ts | 4 +- src/powerquery-parser/common/immutableSet.ts | 10 +- src/powerquery-parser/common/mapUtils.ts | 34 +- src/powerquery-parser/common/orderedMap.ts | 4 +- .../common/result/resultUtils.ts | 8 +- src/powerquery-parser/common/setUtils.ts | 12 +- src/powerquery-parser/common/stringUtils.ts | 24 +- src/powerquery-parser/common/trace.ts | 90 +- src/powerquery-parser/common/traversal.ts | 63 +- src/powerquery-parser/language/ast/ast.ts | 34 +- .../language/ast/astUtils/astUtils.ts | 6 +- .../language/constant/constantUtils.ts | 34 +- src/powerquery-parser/language/textUtils.ts | 38 +- src/powerquery-parser/language/type/type.ts | 60 +- .../language/type/typeUtils/assert.ts | 74 +- .../language/type/typeUtils/categorize.ts | 132 +-- .../language/type/typeUtils/factories.ts | 40 +- .../language/type/typeUtils/isCompatible.ts | 58 +- .../language/type/typeUtils/isEqualType.ts | 18 +- .../language/type/typeUtils/isType.ts | 50 +- .../language/type/typeUtils/nameOf.ts | 26 +- .../language/type/typeUtils/primitive.ts | 2 +- .../language/type/typeUtils/simplify.ts | 160 ++- .../language/type/typeUtils/typeCheck.ts | 81 +- .../language/type/typeUtils/typeUtils.ts | 57 +- src/powerquery-parser/lexer/lexer.ts | 223 ++-- src/powerquery-parser/lexer/lexerSnapshot.ts | 57 +- .../localization/localization.ts | 30 +- .../parser/context/context.ts | 8 +- .../parser/context/contextUtils.ts | 125 +-- .../disambiguation/disambiguationUtils.ts | 126 ++- src/powerquery-parser/parser/error.ts | 20 +- .../parser/nodeIdMap/ancestryUtils.ts | 71 +- .../parser/nodeIdMap/nodeIdMap.ts | 2 +- .../parser/nodeIdMap/nodeIdMapIterator.ts | 164 ++- .../nodeIdMapUtils/childSelectors.ts | 118 +-- .../nodeIdMapUtils/commonSelectors.ts | 24 +- .../nodeIdMap/nodeIdMapUtils/idUtils.ts | 36 +- .../nodeIdMap/nodeIdMapUtils/leafSelectors.ts | 79 +- .../nodeIdMapUtils/nodeIdMapUtils.ts | 22 +- .../nodeIdMapUtils/parentSelectors.ts | 60 +- .../nodeIdMapUtils/specializedSelectors.ts | 72 +- .../parser/nodeIdMap/xorNodeUtils.ts | 20 +- .../parser/parseState/parseState.ts | 8 +- .../parser/parseState/parseStateUtils.ts | 125 ++- src/powerquery-parser/parser/parser/parser.ts | 128 ++- .../parser/parser/parserUtils.ts | 36 +- .../parser/parsers/combinatorialParser.ts | 91 +- src/powerquery-parser/parser/parsers/naive.ts | 963 ++++++++---------- src/powerquery-parser/settings/settings.ts | 23 +- .../settings/settingsUtils.ts | 4 +- src/powerquery-parser/task/taskUtils.ts | 10 +- .../libraryTest/common/cancellationToken.ts | 2 +- src/test/libraryTest/common/stringUtils.ts | 56 +- src/test/libraryTest/lexer/common.ts | 2 +- src/test/libraryTest/parser/columnNumber.ts | 2 +- src/test/libraryTest/parser/error.ts | 11 +- src/test/libraryTest/parser/idUtils.ts | 12 +- src/test/libraryTest/parser/nodeIdMapUtils.ts | 20 +- src/test/libraryTest/parser/simple.ts | 20 +- src/test/libraryTest/tokenizer/common.ts | 2 +- src/test/libraryTest/type/typeUtils/nameOf.ts | 20 +- .../libraryTest/type/typeUtils/typeCheck.ts | 32 +- .../libraryTest/type/typeUtils/typeUtils.ts | 22 +- src/test/testUtils/assertUtils.ts | 2 +- src/test/testUtils/fileUtils.ts | 4 +- style.md | 7 - 72 files changed, 1867 insertions(+), 2235 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1aeb4dc6..328805fb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@microsoft/powerquery-parser", - "version": "0.9.8", + "version": "0.10.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@microsoft/powerquery-parser", - "version": "0.9.8", + "version": "0.10.0", "license": "MIT", "dependencies": { "grapheme-splitter": "^1.0.4", diff --git a/package.json b/package.json index b3e8fb70..44007cdb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@microsoft/powerquery-parser", - "version": "0.9.8", + "version": "0.10.0", "description": "A parser for the Power Query/M formula language.", "author": "Microsoft", "license": "MIT", diff --git a/src/example.ts b/src/example.ts index 6bafd3c3..fcbbb1f7 100644 --- a/src/example.ts +++ b/src/example.ts @@ -43,7 +43,7 @@ function lexText(text: string): void { // An error state is returned if the argument can't be lexed. // Use either the typeguard Lexer.isErrorState to discover if it's an error state, - // or Lexer.maybeErrorLineMap to quickly get all lines with errors. + // or Lexer.errorLineMap to quickly get all lines with errors. // Note: At this point all errors are isolated to a single line. // Checks for multiline errors, such as an unterminated string, have not been processed. let triedLex: Lexer.TriedLex = Lexer.tryLex(DefaultSettings, text); @@ -58,12 +58,10 @@ function lexText(text: string): void { // The lexer state might have an error. // To be sure either use the typeguard Lexer.isErrorState, - // or Lexer.maybeErrorLineMap to get an option containing a map of all lines with errors. - const maybeErrorLineMap: Lexer.ErrorLineMap | undefined = Lexer.maybeErrorLineMap(lexerState); - - if (maybeErrorLineMap !== undefined) { - const errorLineMap: Lexer.ErrorLineMap = maybeErrorLineMap; + // or Lexer.errorLineMap to get an option containing a map of all lines with errors. + const errorLineMap: Lexer.ErrorLineMap | undefined = Lexer.errorLineMap(lexerState); + if (errorLineMap !== undefined) { for (const [lineNumber, errorLine] of errorLineMap.entries()) { console.log(`lineNumber ${lineNumber} has the following error: ${errorLine.error.message}`); } diff --git a/src/powerquery-parser/common/arrayUtils.ts b/src/powerquery-parser/common/arrayUtils.ts index d53b7d42..073be4f3 100644 --- a/src/powerquery-parser/common/arrayUtils.ts +++ b/src/powerquery-parser/common/arrayUtils.ts @@ -5,10 +5,10 @@ import { Assert } from "."; export function all( collection: ReadonlyArray, - predicateFn: (value: T) => boolean = (value: T): boolean => Boolean(value), + predicate: (value: T) => boolean = (value: T): boolean => Boolean(value), ): boolean { for (const element of collection) { - if (!predicateFn(element)) { + if (!predicate(element)) { return false; } } @@ -16,48 +16,34 @@ export function all( return true; } -export function assertIn( - collection: ReadonlyArray, - item: T, - maybeMessage?: string, - maybeDetails?: object, -): number { +export function assertIn(collection: ReadonlyArray, item: T, message?: string, details?: object): number { const index: number = collection.indexOf(item); - Assert.isTrue(index !== -1, maybeMessage, maybeDetails ?? { item }); + Assert.isTrue(index !== -1, message, details ?? { item }); return index; } -export function assertGet( - collection: ReadonlyArray, - index: number, - maybeMessage?: string, - maybeDetails?: object, -): T { - return Assert.asDefined(collection[index], maybeMessage, maybeDetails); +export function assertGet(collection: ReadonlyArray, index: number, message?: string, details?: object): T { + return Assert.asDefined(collection[index], message, details); } export function assertIndexOfPredicate( collection: ReadonlyArray, - predicateFn: (element: T) => boolean, - maybeMessage?: string, - maybeDetails?: object, + predicate: (element: T) => boolean, + message?: string, + details?: object, ): number { - const index: number = indexOfPredicate(collection, predicateFn); - Assert.isTrue(index !== -1, maybeMessage, maybeDetails); + const index: number = indexOfPredicate(collection, predicate); + Assert.isTrue(index !== -1, message, details); return index; } -export function assertNonZeroLength( - collection: ReadonlyArray, - maybeMessage?: string, - maybeDetails?: object, -): void { +export function assertNonZeroLength(collection: ReadonlyArray, message?: string, details?: object): void { Assert.isTrue( collection.length > 0, - maybeMessage ?? `collection should have at least one element in it`, - maybeDetails ?? { + message ?? `collection should have at least one element in it`, + details ?? { collectionLength: collection.length, }, ); @@ -65,9 +51,9 @@ export function assertNonZeroLength( export async function mapAsync( collection: ReadonlyArray, - mapFn: (value: T) => Promise, + map: (value: T) => Promise, ): Promise> { - const tasks: ReadonlyArray> = collection.map(mapFn); + const tasks: ReadonlyArray> = collection.map(map); return await Promise.all(tasks); } @@ -102,11 +88,11 @@ export function findReverse(collection: ReadonlyArray, predicate: (t: T) = return undefined; } -export function includesPredicate(collection: ReadonlyArray, predicateFn: (element: T) => boolean): boolean { +export function includesPredicate(collection: ReadonlyArray, predicate: (element: T) => boolean): boolean { const numElements: number = collection.length; for (let index: number = 0; index < numElements; index += 1) { - if (predicateFn(collection[index])) { + if (predicate(collection[index])) { return true; } } @@ -117,16 +103,16 @@ export function includesPredicate(collection: ReadonlyArray, predicateFn: export function includesUnique( collection: ReadonlyArray, testValue: T, - equalityFn: (left: T, right: T) => boolean, + comparer: (left: T, right: T) => boolean, ): boolean { - return includesPredicate(collection, (collectionItem: T) => equalityFn(testValue, collectionItem)); + return includesPredicate(collection, (collectionItem: T) => comparer(testValue, collectionItem)); } -export function indexOfPredicate(collection: ReadonlyArray, predicateFn: (element: T) => boolean): number { +export function indexOfPredicate(collection: ReadonlyArray, predicate: (element: T) => boolean): number { const numElements: number = collection.length; for (let index: number = 0; index < numElements; index += 1) { - if (predicateFn(collection[index])) { + if (predicate(collection[index])) { return index; } } @@ -137,7 +123,7 @@ export function indexOfPredicate(collection: ReadonlyArray, predicateFn: ( export function isSubset( largerCollection: ReadonlyArray, smallerCollection: ReadonlyArray, - equalityFn: (left: T, right: T) => boolean = (left: T, right: T): boolean => left === right, + comparer: (left: T, right: T) => boolean = (left: T, right: T): boolean => left === right, ): boolean { if (smallerCollection.length > largerCollection.length) { return false; @@ -147,7 +133,7 @@ export function isSubset( let foundMatch: boolean = false; for (const largerCollectionValue of largerCollection) { - if (equalityFn(smallerCollectionValue, largerCollectionValue)) { + if (comparer(smallerCollectionValue, largerCollectionValue)) { foundMatch = true; break; } @@ -194,13 +180,13 @@ export function removeAtIndex(collection: ReadonlyArray, index: number): T export function split( collection: ReadonlyArray, - splitFn: (value: T) => boolean, + splitter: (value: T) => boolean, ): [ReadonlyArray, ReadonlyArray] { const left: T[] = []; const right: T[] = []; for (const value of collection) { - if (splitFn(value) === true) { + if (splitter(value) === true) { left.push(value); } else { right.push(value); diff --git a/src/powerquery-parser/common/assert.ts b/src/powerquery-parser/common/assert.ts index 01cbe953..e8fe095c 100644 --- a/src/powerquery-parser/common/assert.ts +++ b/src/powerquery-parser/common/assert.ts @@ -4,10 +4,10 @@ import { ErrorResult, OkResult, Result, ResultUtils } from "./result"; import { CommonError } from "."; -export function asDefined(maybeValue: T | undefined, maybeMessage?: string, maybeDetails?: object): NonNullable { - isDefined(maybeValue, maybeMessage, maybeDetails); +export function asDefined(value: T | undefined, message?: string, details?: object): NonNullable { + isDefined(value, message, details); - return maybeValue; + return value; } export function asInstanceofError(value: T): Error { @@ -16,15 +16,15 @@ export function asInstanceofError(value: T): Error { return value; } -export function isTrue(value: boolean, maybeMessage?: string, maybeDetails?: object): asserts value is true { +export function isTrue(value: boolean, message?: string, details?: object): asserts value is true { if (value !== true) { - throw new CommonError.InvariantError(maybeMessage ?? `assert failed, expected value to be true`, maybeDetails); + throw new CommonError.InvariantError(message ?? `assert failed, expected value to be true`, details); } } -export function isFalse(value: boolean, maybeMessage?: string, maybeDetails?: object): asserts value is false { +export function isFalse(value: boolean, message?: string, details?: object): asserts value is false { if (value !== false) { - throw new CommonError.InvariantError(maybeMessage ?? `assert failed, expected value to be false`, maybeDetails); + throw new CommonError.InvariantError(message ?? `assert failed, expected value to be false`, details); } } @@ -42,28 +42,18 @@ export function isInstanceofError(value: T | Error): asserts value is Error { } export function isDefined( - maybeValue: T | undefined, - maybeMessage?: string, - maybeDetails?: object, -): asserts maybeValue is NonNullable { - if (maybeValue === undefined) { - throw new CommonError.InvariantError( - maybeMessage ?? `assert failed, expected value to be defined`, - maybeDetails, - ); + value: T | undefined, + message?: string, + details?: object, +): asserts value is NonNullable { + if (value === undefined) { + throw new CommonError.InvariantError(message ?? `assert failed, expected value to be defined`, details); } } -export function isUndefined( - maybeValue: T | undefined, - maybeMessage?: string, - maybeDetails?: object, -): asserts maybeValue is undefined { - if (maybeValue !== undefined) { - throw new CommonError.InvariantError( - maybeMessage ?? `assert failed, expected value to be undefined`, - maybeDetails, - ); +export function isUndefined(value: T | undefined, message?: string, details?: object): asserts value is undefined { + if (value !== undefined) { + throw new CommonError.InvariantError(message ?? `assert failed, expected value to be undefined`, details); } } diff --git a/src/powerquery-parser/common/error.ts b/src/powerquery-parser/common/error.ts index 1dcb1ac2..f874a9f8 100644 --- a/src/powerquery-parser/common/error.ts +++ b/src/powerquery-parser/common/error.ts @@ -22,8 +22,8 @@ export class CancellationError extends Error { } export class InvariantError extends Error { - constructor(readonly invariantBroken: string, readonly maybeDetails?: object) { - super(Localization.error_common_invariantError(Templates.DefaultTemplates, invariantBroken, maybeDetails)); + constructor(readonly invariantBroken: string, readonly details?: object) { + super(Localization.error_common_invariantError(Templates.DefaultTemplates, invariantBroken, details)); Object.setPrototypeOf(this, InvariantError.prototype); } } diff --git a/src/powerquery-parser/common/immutableSet.ts b/src/powerquery-parser/common/immutableSet.ts index 97ed675a..780e8644 100644 --- a/src/powerquery-parser/common/immutableSet.ts +++ b/src/powerquery-parser/common/immutableSet.ts @@ -10,7 +10,7 @@ export class ImmutableSet { public constructor( iterable: Iterable = [], - private readonly equalityFn: (left: T, right: T) => boolean = (left: T, right: T): boolean => left === right, + private readonly comparer: (left: T, right: T) => boolean = (left: T, right: T): boolean => left === right, ) { this.internalCollection = [...iterable]; this.size = this.internalCollection.length; @@ -20,7 +20,7 @@ export class ImmutableSet { if (this.has(value)) { return this; } else { - return new ImmutableSet(new Set([...this.values(), value]), this.equalityFn); + return new ImmutableSet(new Set([...this.values(), value]), this.comparer); } } @@ -41,18 +41,18 @@ export class ImmutableSet { public delete(value: T): ImmutableSet { const values: ReadonlyArray = [...this.internalCollection.values()].filter( - (item: T) => !this.equalityFn(item, value), + (item: T) => !this.comparer(item, value), ); if (values.length === this.internalCollection.length) { return this; } else { - return new ImmutableSet(new Set(values), this.equalityFn); + return new ImmutableSet(new Set(values), this.comparer); } } public has(value: T): boolean { - return ArrayUtils.includesUnique(this.internalCollection, value, this.equalityFn); + return ArrayUtils.includesUnique(this.internalCollection, value, this.comparer); } public values(): IterableIterator { diff --git a/src/powerquery-parser/common/mapUtils.ts b/src/powerquery-parser/common/mapUtils.ts index ea37e2a4..6d7b2e1b 100644 --- a/src/powerquery-parser/common/mapUtils.ts +++ b/src/powerquery-parser/common/mapUtils.ts @@ -3,37 +3,31 @@ import { Assert } from "."; -export function assertDelete(map: Map, key: K, maybeMessage?: string, maybeDetails?: object): void { - Assert.isTrue(map.delete(key), maybeMessage ?? `failed to delete, key is absent`, maybeDetails ?? { key }); +export function assertDelete(map: Map, key: K, message?: string, details?: object): void { + Assert.isTrue(map.delete(key), message ?? `failed to delete, key is absent`, details ?? { key }); } -export function assertGet(map: Map, key: K, maybeMessage?: string, maybeDetails?: object): V { - return Assert.asDefined(map.get(key), maybeMessage ?? `key not found in given map`, maybeDetails ?? { key }); +export function assertGet(map: Map, key: K, message?: string, details?: object): V { + return Assert.asDefined(map.get(key), message ?? `key not found in given map`, details ?? { key }); } -export function assertIn(map: Map, key: K, maybeMessage?: string): void { - Assert.isTrue(map.has(key), maybeMessage ?? `key is absent`, { key }); +export function assertIn(map: Map, key: K, message?: string): void { + Assert.isTrue(map.has(key), message ?? `key is absent`, { key }); } -export function assertNotIn(map: Map, key: K, maybeMessage?: string): void { - Assert.isFalse(map.has(key), maybeMessage ?? `key is present`, { key }); +export function assertNotIn(map: Map, key: K, message?: string): void { + Assert.isFalse(map.has(key), message ?? `key is present`, { key }); } -export function isEqualMap( - left: Map, - right: Map, - valueCmpFn: (left: V, right: V) => boolean, -): boolean { +export function isEqualMap(left: Map, right: Map, comparer: (left: V, right: V) => boolean): boolean { if (left.size !== right.size) { return false; } for (const [leftKey, leftValue] of left.entries()) { - const maybeRightValue: V | undefined = right.get(leftKey); + const value: V | undefined = right.get(leftKey); - if (maybeRightValue === undefined) { - return false; - } else if (valueCmpFn(leftValue, maybeRightValue) === false) { + if (value === undefined || !comparer(leftValue, value)) { return false; } } @@ -44,16 +38,16 @@ export function isEqualMap( export function isSubsetMap( left: Map, right: Map, - valueCmpFn: (left: V, right: V) => boolean, + comparer: (left: V, right: V) => boolean, ): boolean { if (left.size > right.size) { return false; } for (const [key, leftType] of left.entries()) { - const maybeRightType: V | undefined = right.get(key); + const rightType: V | undefined = right.get(key); - if (maybeRightType === undefined || !valueCmpFn(leftType, maybeRightType)) { + if (rightType === undefined || !comparer(leftType, rightType)) { return false; } } diff --git a/src/powerquery-parser/common/orderedMap.ts b/src/powerquery-parser/common/orderedMap.ts index f08c01b8..47410084 100644 --- a/src/powerquery-parser/common/orderedMap.ts +++ b/src/powerquery-parser/common/orderedMap.ts @@ -53,9 +53,9 @@ export class OrderedMap implements Map { } } - public forEach(callbackfn: (value: V, key: K, map: Map) => void): void { + public forEach(callback: (value: V, key: K, map: Map) => void): void { for (const [key, value] of this.entries()) { - callbackfn(value, key, this.map); + callback(value, key, this.map); } } diff --git a/src/powerquery-parser/common/result/resultUtils.ts b/src/powerquery-parser/common/result/resultUtils.ts index 739899a6..00d0aa31 100644 --- a/src/powerquery-parser/common/result/resultUtils.ts +++ b/src/powerquery-parser/common/result/resultUtils.ts @@ -26,9 +26,9 @@ export function isError(result: Result): result is ErrorResult { return result.kind === ResultKind.Error; } -export function ensureResult(callbackFn: () => T, locale: string): Result { +export function ensureResult(callback: () => T, locale: string): Result { try { - return boxOk(callbackFn()); + return boxOk(callback()); } catch (error) { Assert.isInstanceofError(error); @@ -37,11 +37,11 @@ export function ensureResult(callbackFn: () => T, locale: string): Result( - callbackFn: () => Promise, + callback: () => Promise, locale: string, ): Promise> { try { - return boxOk(await callbackFn()); + return boxOk(await callback()); } catch (error) { Assert.isInstanceofError(error); diff --git a/src/powerquery-parser/common/setUtils.ts b/src/powerquery-parser/common/setUtils.ts index 481d968d..42fdcc27 100644 --- a/src/powerquery-parser/common/setUtils.ts +++ b/src/powerquery-parser/common/setUtils.ts @@ -1,19 +1,19 @@ import { Assert } from "."; -export function assertAddUnique(collection: Set, item: T, maybeMessage?: string, maybeDetails?: object): void { +export function assertAddUnique(collection: Set, item: T, message?: string, details?: object): void { Assert.isFalse( collection.has(item), - maybeMessage ?? `collection expected to not already contain the given item`, - maybeDetails ?? { item }, + message ?? `collection expected to not already contain the given item`, + details ?? { item }, ); collection.add(item); } -export function assertDelete(collection: Set, item: T, maybeMessage?: string, maybeDetails?: object): void { +export function assertDelete(collection: Set, item: T, message?: string, details?: object): void { Assert.isTrue( collection.delete(item), - maybeMessage ?? `collection expected to contain the given item`, - maybeDetails ?? { item }, + message ?? `collection expected to contain the given item`, + details ?? { item }, ); } diff --git a/src/powerquery-parser/common/stringUtils.ts b/src/powerquery-parser/common/stringUtils.ts index c7b62087..f724a052 100644 --- a/src/powerquery-parser/common/stringUtils.ts +++ b/src/powerquery-parser/common/stringUtils.ts @@ -7,7 +7,7 @@ import { Assert, CommonError, Pattern } from "."; export const graphemeSplitter: GraphemeSplitter = new GraphemeSplitter(); -export interface FoundQuote { +export interface FoundQuotes { readonly indexStart: number; readonly indexEnd: number; // Spans [indexStart, indexEnd) @@ -23,7 +23,7 @@ export interface GraphemePosition { readonly lineNumber: number; readonly lineCodeUnit: number; readonly columnNumber: number; - readonly maybeCodeUnit: number | undefined; + readonly codeUnit: number | undefined; } // A quick and dirty way to do string formatting. @@ -41,7 +41,7 @@ export function assertGetFormatted(template: string, args: Map): } export function ensureQuoted(text: string): string { - if (maybefindQuote(text, 0)) { + if (findQuotes(text, 0)) { return text; } @@ -78,21 +78,21 @@ export function graphemePositionFrom( text: string, lineCodeUnit: number, lineNumber: number, - maybeCodeUnit: number | undefined, + codeUnit: number | undefined, ): GraphemePosition { return { lineCodeUnit, lineNumber, columnNumber: columnNumberFrom(text, lineCodeUnit), - maybeCodeUnit, + codeUnit, }; } export function isNumeric(text: string): boolean { - return maybeRegexMatchLength(Pattern.Numeric, text, 0) === text.length; + return regexMatchLength(Pattern.Numeric, text, 0) === text.length; } -export function maybeRegexMatchLength(pattern: RegExp, text: string, index: number): number | undefined { +export function regexMatchLength(pattern: RegExp, text: string, index: number): number | undefined { pattern.lastIndex = index; const matches: RegExpExecArray | null = pattern.exec(text); @@ -101,7 +101,7 @@ export function maybeRegexMatchLength(pattern: RegExp, text: string, index: numb // Attempt to find quoted text at the given starting index. // Return undefined if the starting index isn't a quote or if there is no closing quotes. -export function maybefindQuote(text: string, indexStart: number): FoundQuote | undefined { +export function findQuotes(text: string, indexStart: number): FoundQuotes | undefined { const textLength: number = text.length; if ( @@ -151,7 +151,7 @@ export function maybefindQuote(text: string, indexStart: number): FoundQuote | u }; } -export function maybeNewlineKindAt(text: string, index: number): NewlineKind | undefined { +export function newlineKindAt(text: string, index: number): NewlineKind | undefined { const chr1: string = text[index]; switch (chr1) { @@ -171,13 +171,13 @@ export function maybeNewlineKindAt(text: string, index: number): NewlineKind | u } } -export function maybeNormalizeNumber(text: string): string | undefined { +export function normalizeNumber(text: string): string | undefined { const [isPositive, charOffset]: [boolean, number] = getSign(text); const allButUnaryOperators: string = text.slice(charOffset); if (isHex(allButUnaryOperators)) { return isPositive ? allButUnaryOperators.toLocaleLowerCase() : `-${allButUnaryOperators.toLocaleLowerCase()}`; - } else if (maybeRegexMatchLength(Pattern.Numeric, allButUnaryOperators, 0) !== allButUnaryOperators.length) { + } else if (regexMatchLength(Pattern.Numeric, allButUnaryOperators, 0) !== allButUnaryOperators.length) { return undefined; } else { return isPositive === true ? allButUnaryOperators : `-${allButUnaryOperators}`; @@ -185,7 +185,7 @@ export function maybeNormalizeNumber(text: string): string | undefined { } export function isHex(text: string): boolean { - return maybeRegexMatchLength(Pattern.Hex, text, 0) === text.length; + return regexMatchLength(Pattern.Hex, text, 0) === text.length; } export function getSign(text: string): [boolean, number] { diff --git a/src/powerquery-parser/common/trace.ts b/src/powerquery-parser/common/trace.ts index d84a1eca..fa2408b3 100644 --- a/src/powerquery-parser/common/trace.ts +++ b/src/powerquery-parser/common/trace.ts @@ -14,14 +14,14 @@ import performanceNow = require("performance-now"); // id: // Dynamic number. // Used to help identify uniqueness. Auto incrementing integer. -// maybeCorrelationId: +// correlationId: // Can be undefined. If truthy then it refers to a previously generated 'id' number. // Used to track execution flow. // message: // Static string. // Identifies what portion of a task you're in. // Examples: 'entry', 'partialEvaluation', 'traceExit'. -// maybeDetails: +// details: // Nullable object that is JSON serializable. // Contains dynamic data, such as function arguments. // If null, then `[Empty]` is used instead. @@ -53,55 +53,55 @@ export const enum TraceConstant { export class Trace { constructor( - protected readonly emitTraceFn: (trace: Trace, message: string, maybeDetails?: object) => void, + protected readonly emitter: (trace: Trace, message: string, details?: object) => void, public readonly phase: string, public readonly task: string, public readonly id: number, - public readonly maybeCorrelationId: number | undefined, - maybeDetails?: object, + public readonly correlationId: number | undefined, + details?: object, ) { - this.entry(maybeDetails); + this.entry(details); } - public entry(maybeDetails?: object): void { - this.trace(TraceConstant.Entry, maybeDetails); + public entry(details?: object): void { + this.trace(TraceConstant.Entry, details); } - public trace(message: string, maybeDetails?: object): void { - this.emitTraceFn(this, message, maybeDetails); + public trace(message: string, details?: object): void { + this.emitter(this, message, details); } - public exit(maybeDetails?: object): void { - this.trace(TraceConstant.Exit, maybeDetails); + public exit(details?: object): void { + this.trace(TraceConstant.Exit, details); } } // Tracing entries add the current time to its details field. export class BenchmarkTrace extends Trace { constructor( - emitTraceFn: (trace: Trace, message: string, maybeDetails?: object) => void, + emitTraceFn: (trace: Trace, message: string, details?: object) => void, phase: string, task: string, id: number, - maybeCorrelationId: number | undefined, - maybeDetails?: object, + correlationId: number | undefined, + details?: object, ) { - super(emitTraceFn, phase, task, id, maybeCorrelationId, maybeDetails); + super(emitTraceFn, phase, task, id, correlationId, details); } - public override trace(message: string, maybeDetails?: object): void { - super.trace(message, maybeDetails); + public override trace(message: string, details?: object): void { + super.trace(message, details); } } export class NoOpTrace extends Trace { // eslint-disable-next-line @typescript-eslint/no-empty-function - public override trace(_message: string, _maybeDetails?: object): void {} + public override trace(_message: string, _details?: object): void {} } export const NoOpTraceInstance: NoOpTrace = new NoOpTrace( // eslint-disable-next-line @typescript-eslint/no-empty-function - (_trace: Trace, _message: string, _maybeDetails?: object) => {}, + (_trace: Trace, _message: string, _details?: object) => {}, "", "", -1, @@ -109,24 +109,24 @@ export const NoOpTraceInstance: NoOpTrace = new NoOpTrace( ); export abstract class TraceManager { - protected readonly createIdFn: () => number = createAutoIncrementId(); + protected readonly idFactory: () => number = createAutoIncrementIdFactory(); constructor(protected readonly valueDelimiter: string = ",", protected readonly newline: "\n" | "\r\n" = "\r\n") {} - abstract emit(trace: Trace, message: string, maybeDetails?: object): void; + abstract emit(trace: Trace, message: string, details?: object): void; // Creates a new Trace instance and call its entry method. // Traces should be created at the start of a function, and further calls are made on Trace instance. - public entry(phase: string, task: string, maybeCorrelationId: number | undefined, maybeDetails?: object): Trace { - return this.create(phase, task, maybeCorrelationId, maybeDetails); + public entry(phase: string, task: string, correlationId: number | undefined, details?: object): Trace { + return this.create(phase, task, correlationId, details); } // Defaults to simple concatenation. - protected formatMessage(trace: Trace, message: string, maybeDetails?: object): string { - const details: string = maybeDetails !== undefined ? this.safeJsonStringify(maybeDetails) : TraceConstant.Empty; + protected formatMessage(trace: Trace, message: string, details?: object): string { + const detailsJson: string = details !== undefined ? this.safeJsonStringify(details) : TraceConstant.Empty; return ( - [trace.phase, trace.task, trace.id, trace.maybeCorrelationId, performanceNow(), message, details].join( + [trace.phase, trace.task, trace.id, trace.correlationId, performanceNow(), message, detailsJson].join( this.valueDelimiter, ) + this.newline ); @@ -135,13 +135,8 @@ export abstract class TraceManager { // The return to the TraceManager.start function. // Subclass this when the TraceManager needs a different subclass of Trace. // Eg. BenchmarkTraceManager returns a BenchmarkTrace instance. - protected create( - phase: string, - task: string, - maybeCorrelationId: number | undefined, - maybeDetails?: object, - ): Trace { - return new Trace(this.emit.bind(this), phase, task, this.createIdFn(), maybeCorrelationId, maybeDetails); + protected create(phase: string, task: string, correlationId: number | undefined, details?: object): Trace { + return new Trace(this.emit.bind(this), phase, task, this.idFactory(), correlationId, details); } // Copied signature from `JSON.stringify`. @@ -162,12 +157,12 @@ export abstract class TraceManager { // Each trace entry gets passed to a callback function. export class ReportTraceManager extends TraceManager { - constructor(private readonly outputFn: (message: string) => void, valueDelimiter: string = "\t") { + constructor(private readonly emitter: (message: string) => void, valueDelimiter: string = "\t") { super(valueDelimiter); } - emit(trace: Trace, message: string, maybeDetails?: object): void { - this.outputFn(this.formatMessage(trace, message, maybeDetails)); + emit(trace: Trace, message: string, details?: object): void { + this.emitter(this.formatMessage(trace, message, details)); } } @@ -180,30 +175,23 @@ export class BenchmarkTraceManager extends ReportTraceManager { protected override create( phase: string, task: string, - maybeCorrelationId: number | undefined, - maybeDetails?: object, + correlationId: number | undefined, + details?: object, ): BenchmarkTrace { - return new BenchmarkTrace( - this.emit.bind(this), - phase, - task, - this.createIdFn(), - maybeCorrelationId, - maybeDetails, - ); + return new BenchmarkTrace(this.emit.bind(this), phase, task, this.idFactory(), correlationId, details); } } // The TraceManager for DefaultSettings. export class NoOpTraceManager extends TraceManager { // eslint-disable-next-line @typescript-eslint/no-empty-function - emit(_tracer: Trace, _message: string, _maybeDetails?: object): void {} + emit(_tracer: Trace, _message: string, _details?: object): void {} protected override create( _phase: string, _task: string, - _maybeCorrelationId: number | undefined, - _maybeDetails?: object, + _correlationId: number | undefined, + _details?: object, ): Trace { return NoOpTraceInstance; } @@ -211,7 +199,7 @@ export class NoOpTraceManager extends TraceManager { export const NoOpTraceManagerInstance: NoOpTraceManager = new NoOpTraceManager(undefined, undefined); -function createAutoIncrementId(): () => number { +function createAutoIncrementIdFactory(): () => number { let counter: number = 0; return (): number => { diff --git a/src/powerquery-parser/common/traversal.ts b/src/powerquery-parser/common/traversal.ts index 74b3523a..54c4f256 100644 --- a/src/powerquery-parser/common/traversal.ts +++ b/src/powerquery-parser/common/traversal.ts @@ -13,7 +13,7 @@ export type TriedTraverse = Result, ResultType, Node, Return> = ( state: State, node: Node, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; export type TEarlyExitFn, ResultType, Node> = TVisitNodeFn< @@ -34,8 +34,8 @@ export const enum VisitNodeStrategy { DepthFirst = "DepthFirst", } -export interface ITraversalState extends Pick { - readonly maybeInitialCorrelationId: number | undefined; +export interface ITraversalState extends Pick { + readonly initialCorrelationId: number | undefined; result: T; } @@ -48,7 +48,7 @@ export function tryTraverse, ResultTyp strategy: VisitNodeStrategy, visitNodeFn: TVisitNodeFn, expandNodesFn: TExpandNodesFn, - maybeEarlyExitFn: TEarlyExitFn | undefined, + earlyExitFn: TEarlyExitFn | undefined, ): Promise> { return ResultUtils.ensureResultAsync(async () => { await traverseRecursion( @@ -58,8 +58,8 @@ export function tryTraverse, ResultTyp strategy, visitNodeFn, expandNodesFn, - maybeEarlyExitFn, - state.maybeInitialCorrelationId, + earlyExitFn, + state.initialCorrelationId, ); return state.result; @@ -74,7 +74,7 @@ export function tryTraverseAst, Result strategy: VisitNodeStrategy, visitNodeFn: TVisitNodeFn, expandNodesFn: TExpandNodesFn, - maybeEarlyExitFn: TEarlyExitFn | undefined, + earlyExitFn: TEarlyExitFn | undefined, ): Promise> { return tryTraverse( state, @@ -83,7 +83,7 @@ export function tryTraverseAst, Result strategy, visitNodeFn, expandNodesFn, - maybeEarlyExitFn, + earlyExitFn, ); } @@ -95,7 +95,7 @@ export function tryTraverseXor, Result strategy: VisitNodeStrategy, visitNodeFn: TVisitNodeFn, expandNodesFn: TExpandNodesFn, - maybeEarlyExitFn: TEarlyExitFn | undefined, + earlyExitFn: TEarlyExitFn | undefined, ): Promise> { return tryTraverse( state, @@ -104,7 +104,7 @@ export function tryTraverseXor, Result strategy, visitNodeFn, expandNodesFn, - maybeEarlyExitFn, + earlyExitFn, ); } @@ -115,10 +115,10 @@ export async function assertGetAllAstChildren> { - const maybeChildIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(astNode.id); + const childIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(astNode.id); - return maybeChildIds - ? maybeChildIds.map((nodeId: number) => NodeIdMapUtils.assertUnboxAst(nodeIdMapCollection.astNodeById, nodeId)) + return childIds + ? childIds.map((nodeId: number) => NodeIdMapUtils.assertUnboxAst(nodeIdMapCollection.astNodeById, nodeId)) : []; } @@ -133,14 +133,14 @@ export async function assertGetAllXorChildren( +export function expandXorParent( _state: T, xorNode: TXorNode, nodeIdMapCollection: NodeIdMap.Collection, ): Promise> { - const maybeParent: TXorNode | undefined = NodeIdMapUtils.maybeParentXor(nodeIdMapCollection, xorNode.node.id); + const parent: TXorNode | undefined = NodeIdMapUtils.parentXor(nodeIdMapCollection, xorNode.node.id); - return Promise.resolve(maybeParent !== undefined ? [maybeParent] : []); + return Promise.resolve(parent !== undefined ? [parent] : []); } const enum TraversalTraceConstant { @@ -153,41 +153,32 @@ async function traverseRecursion, Resu nodesById: NodesById, node: Node, strategy: VisitNodeStrategy, - visitNodeFn: TVisitNodeFn, - expandNodesFn: TExpandNodesFn, - maybeEarlyExitFn: TEarlyExitFn | undefined, - maybeCorrelationId: number | undefined, + visitNode: TVisitNodeFn, + visitOrderQueue: TExpandNodesFn, + isEarlyExit: TEarlyExitFn | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( TraversalTraceConstant.Traversal, traverseRecursion.name, - maybeCorrelationId, + correlationId, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); - if (maybeEarlyExitFn && (await maybeEarlyExitFn(state, node, trace.id))) { + if (isEarlyExit && (await isEarlyExit(state, node, trace.id))) { return; } else if (strategy === VisitNodeStrategy.BreadthFirst) { - await visitNodeFn(state, node, trace.id); + await visitNode(state, node, trace.id); } - for (const child of await expandNodesFn(state, node, nodesById)) { + for (const child of await visitOrderQueue(state, node, nodesById)) { // eslint-disable-next-line no-await-in-loop - await traverseRecursion( - state, - nodesById, - child, - strategy, - visitNodeFn, - expandNodesFn, - maybeEarlyExitFn, - trace.id, - ); + await traverseRecursion(state, nodesById, child, strategy, visitNode, visitOrderQueue, isEarlyExit, trace.id); } if (strategy === VisitNodeStrategy.DepthFirst) { - await visitNodeFn(state, node, trace.id); + await visitNode(state, node, trace.id); } trace.exit(); diff --git a/src/powerquery-parser/language/ast/ast.ts b/src/powerquery-parser/language/ast/ast.ts index 586901fa..489a2047 100644 --- a/src/powerquery-parser/language/ast/ast.ts +++ b/src/powerquery-parser/language/ast/ast.ts @@ -71,7 +71,7 @@ export const enum NodeKind { export interface INode { readonly kind: NodeKind; readonly id: number; - readonly maybeAttributeIndex: number | undefined; + readonly attributeIndex: number | undefined; // The [start, end) range of a Ast.TNode. readonly tokenRange: TokenRange; readonly isLeaf: boolean; @@ -223,9 +223,9 @@ export type TDocument = Section | TExpression; export interface Section extends INode { readonly kind: NodeKind.Section; readonly isLeaf: false; - readonly maybeLiteralAttributes: RecordLiteral | undefined; + readonly literalAttributes: RecordLiteral | undefined; readonly sectionConstant: IConstant; - readonly maybeName: Identifier | undefined; + readonly name: Identifier | undefined; readonly semicolonConstant: IConstant; readonly sectionMembers: IArrayWrapper; } @@ -233,8 +233,8 @@ export interface Section extends INode { export interface SectionMember extends INode { readonly kind: NodeKind.SectionMember; readonly isLeaf: false; - readonly maybeLiteralAttributes: RecordLiteral | undefined; - readonly maybeSharedConstant: IConstant | undefined; + readonly literalAttributes: RecordLiteral | undefined; + readonly sharedConstant: IConstant | undefined; readonly namePairedExpression: IdentifierPairedExpression; readonly semicolonConstant: IConstant; } @@ -376,7 +376,7 @@ export interface LiteralExpression extends INode { export interface IdentifierExpression extends INode { readonly kind: NodeKind.IdentifierExpression; readonly isLeaf: false; - readonly maybeInclusiveConstant: IConstant | undefined; + readonly inclusiveConstant: IConstant | undefined; readonly identifier: Identifier; } @@ -439,7 +439,7 @@ export type RecordExpression = IBracketWrapped< export interface ItemAccessExpression extends IBraceWrapped { // located after closeWrapperConstant - readonly maybeOptionalConstant: IConstant | undefined; + readonly optionalConstant: IConstant | undefined; } // -------------------------------------------------------- @@ -450,12 +450,12 @@ export type TFieldAccessExpression = FieldSelector | FieldProjection; export interface FieldSelector extends IBracketWrapped { // located after closeWrapperConstant - readonly maybeOptionalConstant: IConstant | undefined; + readonly optionalConstant: IConstant | undefined; } export interface FieldProjection extends IBracketWrapped> { // located after closeWrapperConstant - readonly maybeOptionalConstant: IConstant | undefined; + readonly optionalConstant: IConstant | undefined; } // --------------------------------------------------- @@ -466,7 +466,7 @@ export interface FunctionExpression extends INode { readonly kind: NodeKind.FunctionExpression; readonly isLeaf: false; readonly parameters: IParameterList; - readonly maybeFunctionReturnType: AsNullablePrimitiveType | undefined; + readonly functionReturnType: AsNullablePrimitiveType | undefined; readonly fatArrowConstant: IConstant; readonly expression: TExpression; } @@ -567,7 +567,7 @@ export interface IErrorHandlingExpression extends readonly isLeaf: false; readonly tryConstant: IConstant; readonly protectedExpression: TExpression; - readonly maybeHandler: H | undefined; + readonly handler: H | undefined; } export type ErrorHandlingCatchExpression = IErrorHandlingExpression; @@ -631,7 +631,7 @@ export type ICsvArray = IArrayWrapper>; export interface ICsv extends INode { readonly kind: NodeKind.Csv; readonly node: T; - readonly maybeCommaConstant: IConstant | undefined; + readonly commaConstant: IConstant | undefined; } export interface IKeyValuePair extends INode { @@ -803,9 +803,9 @@ export type IParameterList = IParenthesisWrapped< export interface IParameter extends INode { readonly kind: NodeKind.Parameter; readonly isLeaf: false; - readonly maybeOptionalConstant: IConstant | undefined; + readonly optionalConstant: IConstant | undefined; readonly name: Identifier; - readonly maybeParameterType: T; + readonly parameterType: T; } export type AsNullablePrimitiveType = IPairedConstant< @@ -852,14 +852,14 @@ export type NullCoalescingExpression = IBinOpExpression< export interface FieldSpecification extends INode { readonly kind: NodeKind.FieldSpecification; readonly isLeaf: false; - readonly maybeOptionalConstant: IConstant | undefined; + readonly optionalConstant: IConstant | undefined; readonly name: GeneralizedIdentifier; - readonly maybeFieldTypeSpecification: FieldTypeSpecification | undefined; + readonly fieldTypeSpecification: FieldTypeSpecification | undefined; } export interface FieldSpecificationList extends IBracketWrapped> { // located between content and closeWrapperConstant - readonly maybeOpenRecordMarkerConstant: IConstant | undefined; + readonly openRecordMarkerConstant: IConstant | undefined; } export interface FieldTypeSpecification extends INode { diff --git a/src/powerquery-parser/language/ast/astUtils/astUtils.ts b/src/powerquery-parser/language/ast/astUtils/astUtils.ts index d71543af..b6033204 100644 --- a/src/powerquery-parser/language/ast/astUtils/astUtils.ts +++ b/src/powerquery-parser/language/ast/astUtils/astUtils.ts @@ -8,10 +8,10 @@ export interface SimplifiedType { readonly primitiveTypeConstantKind: Constant.PrimitiveTypeConstant; } -export function maybeLiteralKindFrom( - maybeTokenKind: TokenKind | undefined, +export function literalKindFrom( + tokenKind: TokenKind | undefined, ): Ast.LiteralKind.Numeric | Ast.LiteralKind.Logical | Ast.LiteralKind.Null | Ast.LiteralKind.Text | undefined { - switch (maybeTokenKind) { + switch (tokenKind) { case TokenKind.HexLiteral: case TokenKind.KeywordHashNan: case TokenKind.KeywordHashInfinity: diff --git a/src/powerquery-parser/language/constant/constantUtils.ts b/src/powerquery-parser/language/constant/constantUtils.ts index 5abe40fe..c2435a34 100644 --- a/src/powerquery-parser/language/constant/constantUtils.ts +++ b/src/powerquery-parser/language/constant/constantUtils.ts @@ -2,8 +2,8 @@ import { Assert } from "../../common"; import { Constant } from "."; import { TokenKind } from "../token"; -export function maybeUnaryOperatorKindFrom(maybeTokenKind: TokenKind | undefined): Constant.UnaryOperator | undefined { - switch (maybeTokenKind) { +export function unaryOperatorKindFrom(tokenKind: TokenKind | undefined): Constant.UnaryOperator | undefined { + switch (tokenKind) { case TokenKind.Plus: return Constant.UnaryOperator.Positive; case TokenKind.Minus: @@ -15,10 +15,8 @@ export function maybeUnaryOperatorKindFrom(maybeTokenKind: TokenKind | undefined } } -export function maybeArithmeticOperatorKindFrom( - maybeTokenKind: TokenKind | undefined, -): Constant.ArithmeticOperator | undefined { - switch (maybeTokenKind) { +export function arithmeticOperatorKindFrom(tokenKind: TokenKind | undefined): Constant.ArithmeticOperator | undefined { + switch (tokenKind) { case TokenKind.Asterisk: return Constant.ArithmeticOperator.Multiplication; case TokenKind.Division: @@ -34,10 +32,8 @@ export function maybeArithmeticOperatorKindFrom( } } -export function maybeEqualityOperatorKindFrom( - maybeTokenKind: TokenKind | undefined, -): Constant.EqualityOperator | undefined { - switch (maybeTokenKind) { +export function equalityOperatorKindFrom(tokenKind: TokenKind | undefined): Constant.EqualityOperator | undefined { + switch (tokenKind) { case TokenKind.Equal: return Constant.EqualityOperator.EqualTo; case TokenKind.NotEqual: @@ -47,10 +43,8 @@ export function maybeEqualityOperatorKindFrom( } } -export function maybeLogicalOperatorKindFrom( - maybeTokenKind: TokenKind | undefined, -): Constant.LogicalOperator | undefined { - switch (maybeTokenKind) { +export function logicalOperatorKindFrom(tokenKind: TokenKind | undefined): Constant.LogicalOperator | undefined { + switch (tokenKind) { case TokenKind.KeywordAnd: return Constant.LogicalOperator.And; case TokenKind.KeywordOr: @@ -60,10 +54,8 @@ export function maybeLogicalOperatorKindFrom( } } -export function maybeRelationalOperatorKindFrom( - maybeTokenKind: TokenKind | undefined, -): Constant.RelationalOperator | undefined { - switch (maybeTokenKind) { +export function relationalOperatorKindFrom(tokenKind: TokenKind | undefined): Constant.RelationalOperator | undefined { + switch (tokenKind) { case TokenKind.LessThan: return Constant.RelationalOperator.LessThan; case TokenKind.LessThanEqualTo: @@ -77,10 +69,10 @@ export function maybeRelationalOperatorKindFrom( } } -export function maybeBinOpExpressionOperatorKindFrom( - maybeTokenKind: TokenKind | undefined, +export function binOpExpressionOperatorKindFrom( + tokenKind: TokenKind | undefined, ): Constant.TBinOpExpressionOperator | undefined { - switch (maybeTokenKind) { + switch (tokenKind) { // ArithmeticOperator case TokenKind.Asterisk: return Constant.ArithmeticOperator.Multiplication; diff --git a/src/powerquery-parser/language/textUtils.ts b/src/powerquery-parser/language/textUtils.ts index e13a5772..659055cb 100644 --- a/src/powerquery-parser/language/textUtils.ts +++ b/src/powerquery-parser/language/textUtils.ts @@ -34,23 +34,23 @@ export function identifierKind(text: string, allowTrailingPeriod: boolean): Iden } export function isGeneralizedIdentifier(text: string): boolean { - return maybeGeneralizedIdentifierLength(text, 0) === text.length; + return generalizedIdentifierLength(text, 0) === text.length; } export function isRegularIdentifier(text: string, allowTrailingPeriod: boolean): boolean { - return maybeIdentifierLength(text, 0, allowTrailingPeriod) === text.length; + return identifierLength(text, 0, allowTrailingPeriod) === text.length; } export function isQuotedIdentifier(text: string): boolean { - return maybeQuotedIdentifier(text, 0) !== undefined; + return quotedIdentifier(text, 0) !== undefined; } -export function maybeIdentifierLength(text: string, index: number, allowTrailingPeriod: boolean): number | undefined { +export function identifierLength(text: string, index: number, allowTrailingPeriod: boolean): number | undefined { const startingIndex: number = index; const textLength: number = text.length; let state: IdentifierRegexpState = IdentifierRegexpState.Start; - let maybeMatchLength: number | undefined; + let matchLength: number | undefined; while (state !== IdentifierRegexpState.Done) { if (index === textLength) { @@ -59,13 +59,13 @@ export function maybeIdentifierLength(text: string, index: number, allowTrailing switch (state) { case IdentifierRegexpState.Start: - maybeMatchLength = StringUtils.maybeRegexMatchLength(Pattern.IdentifierStartCharacter, text, index); + matchLength = StringUtils.regexMatchLength(Pattern.IdentifierStartCharacter, text, index); - if (maybeMatchLength === undefined) { + if (matchLength === undefined) { state = IdentifierRegexpState.Done; } else { state = IdentifierRegexpState.RegularIdentifier; - index += maybeMatchLength; + index += matchLength; } break; @@ -76,12 +76,12 @@ export function maybeIdentifierLength(text: string, index: number, allowTrailing index += 1; } - maybeMatchLength = StringUtils.maybeRegexMatchLength(Pattern.IdentifierPartCharacters, text, index); + matchLength = StringUtils.regexMatchLength(Pattern.IdentifierPartCharacters, text, index); - if (maybeMatchLength === undefined) { + if (matchLength === undefined) { state = IdentifierRegexpState.Done; } else { - index += maybeMatchLength; + index += matchLength; // Don't consider `..` or `...` part of an identifier. if (allowTrailingPeriod && text[index] === "." && text[index + 1] !== ".") { @@ -99,7 +99,7 @@ export function maybeIdentifierLength(text: string, index: number, allowTrailing return index !== startingIndex ? index - startingIndex : undefined; } -export function maybeGeneralizedIdentifierLength(text: string, index: number): number | undefined { +export function generalizedIdentifierLength(text: string, index: number): number | undefined { const startingIndex: number = index; const textLength: number = text.length; @@ -118,18 +118,18 @@ export function maybeGeneralizedIdentifierLength(text: string, index: number): n index += 1; } else { - const maybeMatchLength: number | undefined = StringUtils.maybeRegexMatchLength( + const matchLength: number | undefined = StringUtils.regexMatchLength( Pattern.IdentifierPartCharacters, text, index, ); - if (maybeMatchLength === undefined) { + if (matchLength === undefined) { continueMatching = false; break; } - index += maybeMatchLength; + index += matchLength; } if (index >= textLength) { @@ -140,12 +140,12 @@ export function maybeGeneralizedIdentifierLength(text: string, index: number): n return index !== startingIndex ? index - startingIndex : undefined; } -export function maybeQuotedIdentifier(text: string, index: number): StringUtils.FoundQuote | undefined { +export function quotedIdentifier(text: string, index: number): StringUtils.FoundQuotes | undefined { if (text[index] !== "#") { return undefined; } - return StringUtils.maybefindQuote(text, index + 1); + return StringUtils.findQuotes(text, index + 1); } export function normalizeIdentifier(text: string): string { @@ -169,9 +169,9 @@ export function unescape(text: string): string { } const enum IdentifierRegexpState { - Start, - RegularIdentifier, Done, + RegularIdentifier, + Start, } const EscapedWhitespaceRegexp: ReadonlyArray<[RegExp, string]> = [ diff --git a/src/powerquery-parser/language/type/type.ts b/src/powerquery-parser/language/type/type.ts index 92458c18..175e2bf7 100644 --- a/src/powerquery-parser/language/type/type.ts +++ b/src/powerquery-parser/language/type/type.ts @@ -223,13 +223,13 @@ export const enum ExtendedTypeKind { export interface IType { readonly kind: T; - readonly maybeExtendedKind: ExtendedTypeKind | undefined; + readonly extendedKind: ExtendedTypeKind | undefined; readonly isNullable: boolean; } export interface IExtendedType extends IType { readonly kind: TExtendedTypeKind; - readonly maybeExtendedKind: ExtendedTypeKind; + readonly extendedKind: ExtendedTypeKind; } export interface IPrimitiveLiteral extends IExtendedType { @@ -238,7 +238,7 @@ export interface IPrimitiveLiteral extends IExtendedType { } export interface IPrimitiveType extends IType { - readonly maybeExtendedKind: undefined; + readonly extendedKind: undefined; } // ------------------------------------------ @@ -266,7 +266,7 @@ export interface FunctionParameter { readonly nameLiteral: string; readonly isOptional: boolean; readonly isNullable: boolean; - readonly maybeType: TypeKind | undefined; + readonly type: TypeKind | undefined; } // ------------------------------------------- @@ -275,91 +275,91 @@ export interface FunctionParameter { export interface AnyUnion extends IExtendedType { readonly kind: TypeKind.Any; - readonly maybeExtendedKind: ExtendedTypeKind.AnyUnion; + readonly extendedKind: ExtendedTypeKind.AnyUnion; readonly unionedTypePairs: ReadonlyArray; } export type DefinedFunction = IExtendedType & FunctionSignature & { readonly kind: TypeKind.Function; - readonly maybeExtendedKind: ExtendedTypeKind.DefinedFunction; + readonly extendedKind: ExtendedTypeKind.DefinedFunction; }; // A list which has a finite number of elements. export interface DefinedList extends IExtendedType { readonly kind: TypeKind.List; - readonly maybeExtendedKind: ExtendedTypeKind.DefinedList; + readonly extendedKind: ExtendedTypeKind.DefinedList; readonly elements: ReadonlyArray; } // A ListType for DefinedList export interface DefinedListType extends IExtendedType { readonly kind: TypeKind.Type; - readonly maybeExtendedKind: ExtendedTypeKind.DefinedListType; + readonly extendedKind: ExtendedTypeKind.DefinedListType; readonly itemTypes: ReadonlyArray; } export type DefinedRecord = IExtendedType & FieldSpecificationList & { readonly kind: TypeKind.Record; - readonly maybeExtendedKind: ExtendedTypeKind.DefinedRecord; + readonly extendedKind: ExtendedTypeKind.DefinedRecord; }; export type DefinedTable = IExtendedType & FieldSpecificationList & { readonly kind: TypeKind.Table; - readonly maybeExtendedKind: ExtendedTypeKind.DefinedTable; + readonly extendedKind: ExtendedTypeKind.DefinedTable; }; export type FunctionType = IExtendedType & FunctionSignature & { readonly kind: TypeKind.Type; - readonly maybeExtendedKind: ExtendedTypeKind.FunctionType; + readonly extendedKind: ExtendedTypeKind.FunctionType; }; export interface ListType extends IExtendedType { readonly kind: TypeKind.Type; - readonly maybeExtendedKind: ExtendedTypeKind.ListType; + readonly extendedKind: ExtendedTypeKind.ListType; readonly itemType: TPowerQueryType; } export interface LogicalLiteral extends IPrimitiveLiteral { readonly kind: TypeKind.Logical; - readonly maybeExtendedKind: ExtendedTypeKind.LogicalLiteral; + readonly extendedKind: ExtendedTypeKind.LogicalLiteral; } export interface NumberLiteral extends IPrimitiveLiteral { readonly kind: TypeKind.Number; - readonly maybeExtendedKind: ExtendedTypeKind.NumberLiteral; + readonly extendedKind: ExtendedTypeKind.NumberLiteral; } export interface PrimaryPrimitiveType extends IExtendedType { readonly kind: TypeKind.Type; - readonly maybeExtendedKind: ExtendedTypeKind.PrimaryPrimitiveType; + readonly extendedKind: ExtendedTypeKind.PrimaryPrimitiveType; readonly primitiveType: TPrimitiveType; } export type RecordType = IExtendedType & FieldSpecificationList & { readonly kind: TypeKind.Type; - readonly maybeExtendedKind: ExtendedTypeKind.RecordType; + readonly extendedKind: ExtendedTypeKind.RecordType; }; export type TableType = IExtendedType & FieldSpecificationList & { readonly kind: TypeKind.Type; - readonly maybeExtendedKind: ExtendedTypeKind.TableType; + readonly extendedKind: ExtendedTypeKind.TableType; }; export interface TableTypePrimaryExpression extends IExtendedType { readonly kind: TypeKind.Type; - readonly maybeExtendedKind: ExtendedTypeKind.TableTypePrimaryExpression; + readonly extendedKind: ExtendedTypeKind.TableTypePrimaryExpression; readonly primaryExpression: TPowerQueryType; } export interface TextLiteral extends IPrimitiveLiteral { readonly kind: TypeKind.Text; - readonly maybeExtendedKind: ExtendedTypeKind.TextLiteral; + readonly extendedKind: ExtendedTypeKind.TextLiteral; } // ------------------------------------------------------- @@ -435,7 +435,7 @@ export const NullableTrueInstance: LogicalLiteral = createLogicalLiteral(true, t export const PrimitiveInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: false, unionedTypePairs: [ ActionInstance, @@ -463,7 +463,7 @@ export const PrimitiveInstance: AnyUnion = { export const NullablePrimitiveInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: true, unionedTypePairs: [ NullableActionInstance, @@ -489,14 +489,14 @@ export const NullablePrimitiveInstance: AnyUnion = { export const ExpressionInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: PrimitiveInstance.isNullable || NullablePrimitiveInstance.isNullable, unionedTypePairs: [...PrimitiveInstance.unionedTypePairs, ...NullablePrimitiveInstance.unionedTypePairs], }; export const LiteralExpressionInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: LogicalInstance.isNullable || NumberInstance.isNullable || TextInstance.isNullable || NullInstance.isNullable, unionedTypePairs: [LogicalInstance, NumberInstance, TextInstance, NullInstance], @@ -504,35 +504,35 @@ export const LiteralExpressionInstance: AnyUnion = { export const PrimaryExpressionInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: LiteralExpressionInstance.isNullable || ListInstance.isNullable || RecordInstance.isNullable, unionedTypePairs: [...LiteralExpressionInstance.unionedTypePairs, ListInstance, RecordInstance], }; export const PrimaryTypeInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: true, unionedTypePairs: [...PrimitiveInstance.unionedTypePairs, ...NullablePrimitiveInstance.unionedTypePairs], }; export const TypeProductionInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: ExpressionInstance.isNullable || PrimaryTypeInstance.isNullable, unionedTypePairs: [...ExpressionInstance.unionedTypePairs, ...PrimaryTypeInstance.unionedTypePairs], }; export const TypeExpressionInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: PrimaryExpressionInstance.isNullable || PrimaryTypeInstance.isNullable, unionedTypePairs: [PrimaryExpressionInstance, PrimaryTypeInstance], }; export const AnyLiteralInstance: AnyUnion = { kind: TypeKind.Any, - maybeExtendedKind: ExtendedTypeKind.AnyUnion, + extendedKind: ExtendedTypeKind.AnyUnion, isNullable: RecordInstance.isNullable || ListInstance.isNullable || @@ -551,7 +551,7 @@ export const AnyLiteralInstance: AnyUnion = { function createPrimitiveType(typeKind: T, isNullable: boolean): IPrimitiveType { return { kind: typeKind, - maybeExtendedKind: undefined, + extendedKind: undefined, isNullable, }; } @@ -560,7 +560,7 @@ function createLogicalLiteral(isNullable: boolean, normalizedLiteral: boolean): return { isNullable, kind: TypeKind.Logical, - maybeExtendedKind: ExtendedTypeKind.LogicalLiteral, + extendedKind: ExtendedTypeKind.LogicalLiteral, literal: normalizedLiteral ? "true" : "false", normalizedLiteral, }; diff --git a/src/powerquery-parser/language/type/typeUtils/assert.ts b/src/powerquery-parser/language/type/typeUtils/assert.ts index 22faf0e0..be6ba125 100644 --- a/src/powerquery-parser/language/type/typeUtils/assert.ts +++ b/src/powerquery-parser/language/type/typeUtils/assert.ts @@ -231,7 +231,7 @@ export function assertIsAction(type: Type.TPowerQueryType): asserts type is Type if (!isType.isAction(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Action, expectedExtendedTypeKind: undefined, }; @@ -244,7 +244,7 @@ export function assertIsAny(type: Type.TPowerQueryType): asserts type is Type.An if (!isType.isAny(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Any, expectedExtendedTypeKind: [undefined, Type.ExtendedTypeKind.AnyUnion], }; @@ -257,7 +257,7 @@ export function assertIsAnyUnion(type: Type.TPowerQueryType): asserts type is Ty if (!isType.isAnyUnion(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Any, expectedExtendedTypeKind: [Type.ExtendedTypeKind.AnyUnion], }; @@ -270,7 +270,7 @@ export function assertIsAnyNonNull(type: Type.TPowerQueryType): asserts type is if (!isType.isAnyNonNull(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.AnyNonNull, expectedExtendedTypeKind: undefined, }; @@ -283,7 +283,7 @@ export function assertIsBinary(type: Type.TPowerQueryType): asserts type is Type if (!isType.isBinary(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Binary, expectedExtendedTypeKind: undefined, }; @@ -296,7 +296,7 @@ export function assertIsDate(type: Type.TPowerQueryType): asserts type is Type.D if (!isType.isDate(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Date, expectedExtendedTypeKind: undefined, }; @@ -309,7 +309,7 @@ export function assertIsDateTime(type: Type.TPowerQueryType): asserts type is Ty if (!isType.isDateTime(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.DateTime, expectedExtendedTypeKind: undefined, }; @@ -322,7 +322,7 @@ export function assertIsDateTimeZone(type: Type.TPowerQueryType): asserts type i if (!isType.isDateTimeZone(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.DateTimeZone, expectedExtendedTypeKind: undefined, }; @@ -335,7 +335,7 @@ export function assertIsDefinedFunction(type: Type.TPowerQueryType): asserts typ if (!isType.isDefinedFunction(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Function, expectedExtendedTypeKind: [Type.ExtendedTypeKind.DefinedFunction], }; @@ -348,7 +348,7 @@ export function assertIsDefinedList(type: Type.TPowerQueryType): asserts type is if (!isType.isDefinedList(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.List, expectedExtendedTypeKind: [Type.ExtendedTypeKind.DefinedList], }; @@ -361,7 +361,7 @@ export function assertIsDefinedListType(type: Type.TPowerQueryType): asserts typ if (!isType.isDefinedListType(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Type, expectedExtendedTypeKind: [Type.ExtendedTypeKind.DefinedListType], }; @@ -374,7 +374,7 @@ export function assertIsDefinedRecord(type: Type.TPowerQueryType): asserts type if (!isType.isDefinedRecord(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Record, expectedExtendedTypeKind: [Type.ExtendedTypeKind.DefinedRecord], }; @@ -387,7 +387,7 @@ export function assertIsDefinedTable(type: Type.TPowerQueryType): asserts type i if (!isType.isDefinedTable(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Table, expectedExtendedTypeKind: [Type.ExtendedTypeKind.DefinedTable], }; @@ -400,7 +400,7 @@ export function assertIsDuration(type: Type.TPowerQueryType): asserts type is Ty if (!isType.isDuration(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Duration, expectedExtendedTypeKind: undefined, }; @@ -413,7 +413,7 @@ export function assertIsFunction(type: Type.TPowerQueryType): asserts type is Ty if (!isType.isFunction(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Function, expectedExtendedTypeKind: [undefined, Type.ExtendedTypeKind.DefinedFunction], }; @@ -426,7 +426,7 @@ export function assertIsFunctionType(type: Type.TPowerQueryType): asserts type i if (!isType.isFunctionType(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Type, expectedExtendedTypeKind: [Type.ExtendedTypeKind.FunctionType], }; @@ -439,7 +439,7 @@ export function assertIsList(type: Type.TPowerQueryType): asserts type is Type.T if (!isType.isList(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.List, expectedExtendedTypeKind: [undefined, Type.ExtendedTypeKind.DefinedList], }; @@ -452,7 +452,7 @@ export function assertIsLiteral(type: Type.TPowerQueryType): asserts type is Typ if (!isType.isLiteral(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: [Type.TypeKind.Number, Type.TypeKind.Text], expectedExtendedTypeKind: [Type.ExtendedTypeKind.NumberLiteral, Type.ExtendedTypeKind.TextLiteral], }; @@ -465,7 +465,7 @@ export function assertIsLogical(type: Type.TPowerQueryType): asserts type is Typ if (!isType.isLogical(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Logical, expectedExtendedTypeKind: [undefined, Type.ExtendedTypeKind.LogicalLiteral], }; @@ -478,7 +478,7 @@ export function assertIsLogicalLiteral(type: Type.TPowerQueryType): asserts type if (!isType.isLogicalLiteral(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Logical, expectedExtendedTypeKind: [Type.ExtendedTypeKind.LogicalLiteral], }; @@ -491,7 +491,7 @@ export function assertIsNone(type: Type.TPowerQueryType): asserts type is Type.N if (!isType.isNone(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.None, expectedExtendedTypeKind: undefined, }; @@ -504,7 +504,7 @@ export function assertIsNotApplicable(type: Type.TPowerQueryType): asserts type if (!isType.isNotApplicable(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.NotApplicable, expectedExtendedTypeKind: undefined, }; @@ -517,7 +517,7 @@ export function assertIsNull(type: Type.TPowerQueryType): asserts type is Type.N if (!isType.isNull(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Null, expectedExtendedTypeKind: undefined, }; @@ -530,7 +530,7 @@ export function assertIsNumber(type: Type.TPowerQueryType): asserts type is Type if (!isType.isNumber(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Number, expectedExtendedTypeKind: [undefined, Type.ExtendedTypeKind.NumberLiteral], }; @@ -543,7 +543,7 @@ export function assertIsNumberLiteral(type: Type.TPowerQueryType): asserts type if (!isType.isNumber(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Number, expectedExtendedTypeKind: [Type.ExtendedTypeKind.NumberLiteral], }; @@ -556,7 +556,7 @@ export function assertIsPrimaryPrimitiveType(type: Type.TPowerQueryType): assert if (!isType.isPrimaryPrimitiveType(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Type, expectedExtendedTypeKind: [Type.ExtendedTypeKind.PrimaryPrimitiveType], }; @@ -569,7 +569,7 @@ export function assertIsTPrimitiveType(type: Type.TPowerQueryType): asserts type if (!isType.isTPrimitiveType(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: [ Type.TypeKind.Action, Type.TypeKind.Any, @@ -604,7 +604,7 @@ export function assertIsRecord(type: Type.TPowerQueryType): asserts type is Type if (!isType.isRecord(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Record, expectedExtendedTypeKind: [undefined, Type.ExtendedTypeKind.DefinedRecord], }; @@ -617,7 +617,7 @@ export function assertIsRecordType(type: Type.TPowerQueryType): asserts type is if (!isType.isRecordType(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Type, expectedExtendedTypeKind: [Type.ExtendedTypeKind.RecordType], }; @@ -630,7 +630,7 @@ export function assertIsTable(type: Type.TPowerQueryType): asserts type is Type. if (!isType.isTable(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Table, expectedExtendedTypeKind: [undefined, Type.ExtendedTypeKind.DefinedTable], }; @@ -643,7 +643,7 @@ export function assertIsTableType(type: Type.TPowerQueryType): asserts type is T if (!isType.isTableType(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Type, expectedExtendedTypeKind: [Type.ExtendedTypeKind.TableType], }; @@ -658,7 +658,7 @@ export function assertIsTableTypePrimaryExpression( if (!isType.isTableTypePrimaryExpression(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Type, expectedExtendedTypeKind: [Type.ExtendedTypeKind.TableTypePrimaryExpression], }; @@ -671,7 +671,7 @@ export function assertIsText(type: Type.TPowerQueryType): asserts type is Type.T if (!isType.isText(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Text, expectedExtendedTypeKind: [undefined, Type.ExtendedTypeKind.TextLiteral], }; @@ -684,7 +684,7 @@ export function assertIsTextLiteral(type: Type.TPowerQueryType): asserts type is if (!isType.isText(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Text, expectedExtendedTypeKind: [Type.ExtendedTypeKind.TextLiteral], }; @@ -697,7 +697,7 @@ export function assertIsTime(type: Type.TPowerQueryType): asserts type is Type.T if (!isType.isTime(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Time, expectedExtendedTypeKind: undefined, }; @@ -710,7 +710,7 @@ export function assertIsType(type: Type.TPowerQueryType): asserts type is Type.T if (!isType.isType(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Type, expectedExtendedTypeKind: undefined, }; @@ -723,7 +723,7 @@ export function assertIsUnknown(type: Type.TPowerQueryType): asserts type is Typ if (!isType.isUnknown(type)) { const details: AssertErrorDetails = { givenTypeKind: type.kind, - givenExtendedTypeKind: type.maybeExtendedKind, + givenExtendedTypeKind: type.extendedKind, expectedTypeKind: Type.TypeKind.Unknown, expectedExtendedTypeKind: undefined, }; diff --git a/src/powerquery-parser/language/type/typeUtils/categorize.ts b/src/powerquery-parser/language/type/typeUtils/categorize.ts index 943ba5dd..47026325 100644 --- a/src/powerquery-parser/language/type/typeUtils/categorize.ts +++ b/src/powerquery-parser/language/type/typeUtils/categorize.ts @@ -50,27 +50,27 @@ export type NonExtendedCategory = | UnknownCategory; export interface CategorizedPowerQueryTypes { - readonly maybeAction: ActionCategory | undefined; - readonly maybeAnyNonNull: AnyNonNullCategory | undefined; - readonly maybeAny: AnyCategory | undefined; - readonly maybeBinary: BinaryCategory | undefined; - readonly maybeDate: DateCategory | undefined; - readonly maybeDateTime: DateTimeCategory | undefined; - readonly maybeDateTimeZone: DateTimeZoneCategory | undefined; - readonly maybeDuration: DurationCategory | undefined; - readonly maybeFunction: FunctionCategory | undefined; - readonly maybeList: ListCategory | undefined; - readonly maybeLogical: LogicalCategory | undefined; - readonly maybeNone: NoneCategory | undefined; - readonly maybeNotApplicable: NotApplicableCategory | undefined; - readonly maybeNumber: NumberCategory | undefined; - readonly maybeNull: NullCategory | undefined; - readonly maybeRecord: RecordCategory | undefined; - readonly maybeTable: TableCategory | undefined; - readonly maybeText: TextCategory | undefined; - readonly maybeTime: TimeCategory | undefined; - readonly maybeType: TypeCategory | undefined; - readonly maybeUnknown: UnknownCategory | undefined; + readonly actions: ActionCategory | undefined; + readonly anyNonNulls: AnyNonNullCategory | undefined; + readonly anys: AnyCategory | undefined; + readonly binaries: BinaryCategory | undefined; + readonly dates: DateCategory | undefined; + readonly dateTimes: DateTimeCategory | undefined; + readonly dateTimeZones: DateTimeZoneCategory | undefined; + readonly durations: DurationCategory | undefined; + readonly functions: FunctionCategory | undefined; + readonly lists: ListCategory | undefined; + readonly logicals: LogicalCategory | undefined; + readonly nones: NoneCategory | undefined; + readonly notApplicables: NotApplicableCategory | undefined; + readonly numbers: NumberCategory | undefined; + readonly nulls: NullCategory | undefined; + readonly records: RecordCategory | undefined; + readonly tables: TableCategory | undefined; + readonly texts: TextCategory | undefined; + readonly times: TimeCategory | undefined; + readonly types: TypeCategory | undefined; + readonly unknowns: UnknownCategory | undefined; } export type ActionCategory = ITypeKindCategory; @@ -138,44 +138,44 @@ export interface TypeCategory extends ITypeKindCategory { export function categorize( types: ReadonlyArray, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): CategorizedPowerQueryTypes { - const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.Categorize, categorize.name, maybeCorrelationId); + const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.Categorize, categorize.name, correlationId); const categoryByKind: Map = new Map(); for (const type of types) { - const maybeCategory: TCategory | undefined = categoryByKind.get(type.kind); + const category: TCategory | undefined = categoryByKind.get(type.kind); - if (maybeCategory === undefined) { + if (category === undefined) { categoryByKind.set(type.kind, createCategory(type, traceManager, trace.id)); } else { - categoryByKind.set(type.kind, addToCategory(maybeCategory, type, traceManager, trace.id)); + categoryByKind.set(type.kind, addToCategory(category, type, traceManager, trace.id)); } } const result: CategorizedPowerQueryTypes = { - maybeAction: categoryByKind.get(Type.TypeKind.Action) as ActionCategory, - maybeAny: categoryByKind.get(Type.TypeKind.Any) as AnyCategory, - maybeAnyNonNull: categoryByKind.get(Type.TypeKind.AnyNonNull) as AnyNonNullCategory, - maybeBinary: categoryByKind.get(Type.TypeKind.Binary) as BinaryCategory, - maybeDate: categoryByKind.get(Type.TypeKind.Date) as DateCategory, - maybeDateTime: categoryByKind.get(Type.TypeKind.DateTime) as DateTimeCategory, - maybeDateTimeZone: categoryByKind.get(Type.TypeKind.DateTimeZone) as DateTimeZoneCategory, - maybeDuration: categoryByKind.get(Type.TypeKind.Duration) as DurationCategory, - maybeFunction: categoryByKind.get(Type.TypeKind.Function) as FunctionCategory, - maybeList: categoryByKind.get(Type.TypeKind.List) as ListCategory, - maybeLogical: categoryByKind.get(Type.TypeKind.Logical) as LogicalCategory, - maybeNone: categoryByKind.get(Type.TypeKind.None) as NoneCategory, - maybeNotApplicable: categoryByKind.get(Type.TypeKind.NotApplicable) as NotApplicableCategory, - maybeNull: categoryByKind.get(Type.TypeKind.Null) as NullCategory, - maybeNumber: categoryByKind.get(Type.TypeKind.Number) as NumberCategory, - maybeRecord: categoryByKind.get(Type.TypeKind.Record) as RecordCategory, - maybeTable: categoryByKind.get(Type.TypeKind.Table) as TableCategory, - maybeText: categoryByKind.get(Type.TypeKind.Text) as TextCategory, - maybeTime: categoryByKind.get(Type.TypeKind.Time) as TimeCategory, - maybeType: categoryByKind.get(Type.TypeKind.Type) as TypeCategory, - maybeUnknown: categoryByKind.get(Type.TypeKind.Unknown) as UnknownCategory, + actions: categoryByKind.get(Type.TypeKind.Action) as ActionCategory, + anys: categoryByKind.get(Type.TypeKind.Any) as AnyCategory, + anyNonNulls: categoryByKind.get(Type.TypeKind.AnyNonNull) as AnyNonNullCategory, + binaries: categoryByKind.get(Type.TypeKind.Binary) as BinaryCategory, + dates: categoryByKind.get(Type.TypeKind.Date) as DateCategory, + dateTimes: categoryByKind.get(Type.TypeKind.DateTime) as DateTimeCategory, + dateTimeZones: categoryByKind.get(Type.TypeKind.DateTimeZone) as DateTimeZoneCategory, + durations: categoryByKind.get(Type.TypeKind.Duration) as DurationCategory, + functions: categoryByKind.get(Type.TypeKind.Function) as FunctionCategory, + lists: categoryByKind.get(Type.TypeKind.List) as ListCategory, + logicals: categoryByKind.get(Type.TypeKind.Logical) as LogicalCategory, + nones: categoryByKind.get(Type.TypeKind.None) as NoneCategory, + notApplicables: categoryByKind.get(Type.TypeKind.NotApplicable) as NotApplicableCategory, + nulls: categoryByKind.get(Type.TypeKind.Null) as NullCategory, + numbers: categoryByKind.get(Type.TypeKind.Number) as NumberCategory, + records: categoryByKind.get(Type.TypeKind.Record) as RecordCategory, + tables: categoryByKind.get(Type.TypeKind.Table) as TableCategory, + texts: categoryByKind.get(Type.TypeKind.Text) as TextCategory, + times: categoryByKind.get(Type.TypeKind.Time) as TimeCategory, + types: categoryByKind.get(Type.TypeKind.Type) as TypeCategory, + unknowns: categoryByKind.get(Type.TypeKind.Unknown) as UnknownCategory, }; trace.exit(); @@ -322,7 +322,7 @@ function addToCategory( function addTypeIfUniqueAny(category: AnyCategory, type: Type.TAny): AnyCategory { assertIsCategoryForType(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.AnyUnion: return { ...category, @@ -341,7 +341,7 @@ function addTypeIfUniqueAny(category: AnyCategory, type: Type.TAny): AnyCategory function addToCategoryForFunction(category: FunctionCategory, type: Type.TFunction): FunctionCategory { assertIsCategoryForType(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedFunction: { return { ...category, @@ -364,7 +364,7 @@ function addToCategoryForFunction(category: FunctionCategory, type: Type.TFuncti function addToCategoryForList(category: ListCategory, type: Type.TList): ListCategory { assertIsCategoryForType(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedList: { return { ...category, @@ -387,7 +387,7 @@ function addToCategoryForList(category: ListCategory, type: Type.TList): ListCat function addToCategoryForLogical(category: LogicalCategory, type: Type.TLogical): LogicalCategory { assertIsCategoryForType(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.LogicalLiteral: { return { ...category, @@ -417,7 +417,7 @@ function addToCategoryForLogical(category: LogicalCategory, type: Type.TLogical) function addToCategoryForNumber(category: NumberCategory, type: Type.TNumber): NumberCategory { assertIsCategoryForType(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.NumberLiteral: { return { ...category, @@ -452,7 +452,7 @@ function addToCategoryForPrimitive(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedRecord: { return { ...category, @@ -475,7 +475,7 @@ function addToCategoryForRecord(category: RecordCategory, type: Type.TRecord): R function addToCategoryForTable(category: TableCategory, type: Type.TTable): TableCategory { assertIsCategoryForType(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedTable: { return { ...category, @@ -498,7 +498,7 @@ function addToCategoryForTable(category: TableCategory, type: Type.TTable): Tabl function addToCategoryForText(category: TextCategory, type: Type.TText): TextCategory { assertIsCategoryForType(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.TextLiteral: { return { ...category, @@ -521,7 +521,7 @@ function addToCategoryForText(category: TextCategory, type: Type.TText): TextCat function addTypeIfUniqueType(category: TypeCategory, type: Type.TType): TypeCategory { assertIsCategoryForType(category, type); - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedListType: { return { ...category, @@ -695,7 +695,7 @@ function createCategory(type: Type.TPowerQueryType, traceManager: TraceManager, } function createCategoryForAny(type: Type.TAny): AnyCategory { - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.AnyUnion: { return { kind: Type.TypeKind.Any, @@ -720,7 +720,7 @@ function createCategoryForAny(type: Type.TAny): AnyCategory { } function createCategoryForFunction(type: Type.TFunction): FunctionCategory { - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedFunction: { return { kind: Type.TypeKind.Function, @@ -743,7 +743,7 @@ function createCategoryForFunction(type: Type.TFunction): FunctionCategory { } function createCategoryForList(type: Type.TList): ListCategory { - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedList: { return { kind: Type.TypeKind.List, @@ -766,7 +766,7 @@ function createCategoryForList(type: Type.TList): ListCategory { } function createCategoryForLogical(type: Type.TLogical): LogicalCategory { - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.LogicalLiteral: { return { kind: Type.TypeKind.Logical, @@ -795,7 +795,7 @@ function createCategoryForLogical(type: Type.TLogical): LogicalCategory { } function createCategoryForNumber(type: Type.TNumber): NumberCategory { - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.NumberLiteral: { return { kind: Type.TypeKind.Number, @@ -825,7 +825,7 @@ function createCategoryForPrimitive(type: T): IT } function createCategoryForRecord(type: Type.TRecord): RecordCategory { - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedRecord: { return { kind: Type.TypeKind.Record, @@ -848,7 +848,7 @@ function createCategoryForRecord(type: Type.TRecord): RecordCategory { } function createCategoryForTable(type: Type.TTable): TableCategory { - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedTable: { return { kind: Type.TypeKind.Table, @@ -871,7 +871,7 @@ function createCategoryForTable(type: Type.TTable): TableCategory { } function createCategoryForText(type: Type.TText): TextCategory { - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.TextLiteral: { return { kind: Type.TypeKind.Text, @@ -903,7 +903,7 @@ function createCategoryForType(type: Type.TType): TypeCategory { let tablePrimaryExpressionTypes: ReadonlyArray = []; let tableTypes: ReadonlyArray = []; - switch (type.maybeExtendedKind) { + switch (type.extendedKind) { case Type.ExtendedTypeKind.DefinedListType: definedListTypes = [type]; break; @@ -961,7 +961,7 @@ function flattenAnyUnion(anyUnion: Type.AnyUnion): ReadonlyArray(isNullable: boolean export function createAnyUnion( unionedTypePairs: ReadonlyArray, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Type.TPowerQueryType { - const trace: Trace = traceManager.entry( - TypeUtilsTraceConstant.CreateAnyUnion, - createAnyUnion.name, - maybeCorrelationId, - ); + const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.CreateAnyUnion, createAnyUnion.name, correlationId); const simplified: ReadonlyArray = simplify(unionedTypePairs, traceManager, trace.id); @@ -40,7 +36,7 @@ export function createAnyUnion( const result: Type.AnyUnion = { kind: Type.TypeKind.Any, - maybeExtendedKind: Type.ExtendedTypeKind.AnyUnion, + extendedKind: Type.ExtendedTypeKind.AnyUnion, isNullable: unionedTypePairs.find((ttype: Type.TPowerQueryType) => ttype.isNullable === true) !== undefined, unionedTypePairs: simplified, }; @@ -57,7 +53,7 @@ export function createDefinedFunction( ): Type.DefinedFunction { return { kind: Type.TypeKind.Function, - maybeExtendedKind: Type.ExtendedTypeKind.DefinedFunction, + extendedKind: Type.ExtendedTypeKind.DefinedFunction, isNullable, parameters, returnType, @@ -70,7 +66,7 @@ export function createDefinedList( ): Type.DefinedList { return { kind: Type.TypeKind.List, - maybeExtendedKind: Type.ExtendedTypeKind.DefinedList, + extendedKind: Type.ExtendedTypeKind.DefinedList, isNullable, elements, }; @@ -82,7 +78,7 @@ export function createDefinedListType( ): Type.DefinedListType { return { kind: Type.TypeKind.Type, - maybeExtendedKind: Type.ExtendedTypeKind.DefinedListType, + extendedKind: Type.ExtendedTypeKind.DefinedListType, isNullable, itemTypes, }; @@ -95,7 +91,7 @@ export function createDefinedRecord( ): Type.DefinedRecord { return { kind: Type.TypeKind.Record, - maybeExtendedKind: Type.ExtendedTypeKind.DefinedRecord, + extendedKind: Type.ExtendedTypeKind.DefinedRecord, isNullable, fields, isOpen, @@ -109,7 +105,7 @@ export function createDefinedTable( ): Type.DefinedTable { return { kind: Type.TypeKind.Table, - maybeExtendedKind: Type.ExtendedTypeKind.DefinedTable, + extendedKind: Type.ExtendedTypeKind.DefinedTable, isNullable, fields, isOpen, @@ -123,7 +119,7 @@ export function createFunctionType( ): Type.FunctionType { return { kind: Type.TypeKind.Type, - maybeExtendedKind: Type.ExtendedTypeKind.FunctionType, + extendedKind: Type.ExtendedTypeKind.FunctionType, isNullable, parameters, returnType, @@ -147,7 +143,7 @@ export function createLogicalLiteral(isNullable: boolean, literal: string | bool return { isNullable, kind: Type.TypeKind.Logical, - maybeExtendedKind: Type.ExtendedTypeKind.LogicalLiteral, + extendedKind: Type.ExtendedTypeKind.LogicalLiteral, literal: parsedLiteral, normalizedLiteral, }; @@ -156,7 +152,7 @@ export function createLogicalLiteral(isNullable: boolean, literal: string | bool export function createListType(isNullable: boolean, itemType: Type.TPowerQueryType): Type.ListType { return { kind: Type.TypeKind.Type, - maybeExtendedKind: Type.ExtendedTypeKind.ListType, + extendedKind: Type.ExtendedTypeKind.ListType, isNullable, itemType, }; @@ -171,13 +167,13 @@ export function createNumberLiteral(isNullable: boolean, literal: string | numbe normalizedLiteral = literal; } else { parsedLiteral = literal; - normalizedLiteral = Number.parseFloat(Assert.asDefined(StringUtils.maybeNormalizeNumber(literal))); + normalizedLiteral = Number.parseFloat(Assert.asDefined(StringUtils.normalizeNumber(literal))); } return { isNullable, kind: Type.TypeKind.Number, - maybeExtendedKind: Type.ExtendedTypeKind.NumberLiteral, + extendedKind: Type.ExtendedTypeKind.NumberLiteral, literal: parsedLiteral, normalizedLiteral, }; @@ -189,7 +185,7 @@ export function createPrimaryPrimitiveType( ): Type.PrimaryPrimitiveType { return { kind: Type.TypeKind.Type, - maybeExtendedKind: Type.ExtendedTypeKind.PrimaryPrimitiveType, + extendedKind: Type.ExtendedTypeKind.PrimaryPrimitiveType, isNullable, primitiveType, }; @@ -202,7 +198,7 @@ export function createRecordType( ): Type.RecordType { return { kind: Type.TypeKind.Type, - maybeExtendedKind: Type.ExtendedTypeKind.RecordType, + extendedKind: Type.ExtendedTypeKind.RecordType, isNullable, fields, isOpen, @@ -216,7 +212,7 @@ export function createTableType( ): Type.TableType { return { kind: Type.TypeKind.Type, - maybeExtendedKind: Type.ExtendedTypeKind.TableType, + extendedKind: Type.ExtendedTypeKind.TableType, isNullable, fields, isOpen, @@ -229,7 +225,7 @@ export function createTextLiteral(isNullable: boolean, literal: string): Type.Te return { isNullable, kind: Type.TypeKind.Text, - maybeExtendedKind: Type.ExtendedTypeKind.TextLiteral, + extendedKind: Type.ExtendedTypeKind.TextLiteral, literal, normalizedLiteral: literal, }; @@ -241,7 +237,7 @@ export function createTableTypePrimary( ): Type.TableTypePrimaryExpression { return { kind: Type.TypeKind.Type, - maybeExtendedKind: Type.ExtendedTypeKind.TableTypePrimaryExpression, + extendedKind: Type.ExtendedTypeKind.TableTypePrimaryExpression, isNullable, primaryExpression, }; diff --git a/src/powerquery-parser/language/type/typeUtils/isCompatible.ts b/src/powerquery-parser/language/type/typeUtils/isCompatible.ts index 768d74fe..9c7ecf5a 100644 --- a/src/powerquery-parser/language/type/typeUtils/isCompatible.ts +++ b/src/powerquery-parser/language/type/typeUtils/isCompatible.ts @@ -17,9 +17,9 @@ export function isCompatible( left: Type.TPowerQueryType, right: Type.TPowerQueryType, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): boolean | undefined { - const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.IsCompatible, isCompatible.name, maybeCorrelationId); + const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.IsCompatible, isCompatible.name, correlationId); let result: boolean | undefined; @@ -125,11 +125,11 @@ export function isCompatibleWithFunctionParameter( return false; } else { return ( - !right.maybeType || - right.maybeType === Type.TypeKind.Any || + !right.type || + right.type === Type.TypeKind.Any || left.kind === Type.TypeKind.Any || (left.kind === Type.TypeKind.Null && right.isNullable) || - left.kind === right.maybeType + left.kind === right.type ); } } @@ -148,7 +148,7 @@ function isCompatibleWithAny( let result: boolean | undefined; - switch (right.maybeExtendedKind) { + switch (right.extendedKind) { case undefined: result = true; break; @@ -208,7 +208,7 @@ function isCompatibleWithDefinedList( if (left.kind !== right.kind) { result = false; } else { - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case undefined: result = false; break; @@ -245,7 +245,7 @@ function isCompatibleWithDefinedListType( if (left.kind !== right.kind) { result = false; } else { - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case Type.ExtendedTypeKind.DefinedListType: result = isCompatibleDefinedListOrDefinedListType(left, right, traceManager, trace.id); break; @@ -290,7 +290,7 @@ function isCompatibleWithDefinedRecord( if (left.kind !== right.kind) { result = false; } else { - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case undefined: result = false; break; @@ -326,7 +326,7 @@ function isCompatibleWithDefinedTable( if (left.kind !== right.kind) { result = false; } else { - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case undefined: result = false; break; @@ -397,7 +397,7 @@ function isCompatibleWithFunction( if (left.kind !== right.kind) { result = false; } else { - switch (right.maybeExtendedKind) { + switch (right.extendedKind) { case undefined: result = true; break; @@ -433,9 +433,9 @@ function isCompatibleWithList( if (left.kind !== right.kind) { result = false; } else { - switch (right.maybeExtendedKind) { + switch (right.extendedKind) { case undefined: - result = left.maybeExtendedKind === undefined; + result = left.extendedKind === undefined; break; case Type.ExtendedTypeKind.DefinedList: @@ -469,7 +469,7 @@ function isCompatibleWithListType( if (left.kind !== right.kind) { result = false; } else { - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case Type.ExtendedTypeKind.DefinedListType: result = isDefinedListTypeCompatibleWithListType(left, right, traceManager, trace.id); break; @@ -502,7 +502,7 @@ function isCompatibleWithPrimaryPrimitiveType(left: Type.TPowerQueryType, right: return false; } - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case Type.ExtendedTypeKind.PrimaryPrimitiveType: return left.primitiveType === right.primitiveType; @@ -537,7 +537,7 @@ function isCompatibleWithRecord( if (left.kind !== right.kind) { result = false; } else { - switch (right.maybeExtendedKind) { + switch (right.extendedKind) { case undefined: result = true; break; @@ -573,7 +573,7 @@ function isCompatibleWithRecordType( if (left.kind !== right.kind) { result = false; } else { - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case Type.ExtendedTypeKind.RecordType: result = isCompatibleWithFieldSpecificationList(left, right, traceManager, trace.id); break; @@ -615,7 +615,7 @@ function isCompatibleWithTable( if (left.kind !== right.kind) { result = false; } else { - switch (right.maybeExtendedKind) { + switch (right.extendedKind) { case undefined: result = true; break; @@ -651,7 +651,7 @@ function isCompatibleWithTableType( if (left.kind !== right.kind) { result = false; } else { - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case undefined: result = false; break; @@ -696,7 +696,7 @@ function isCompatibleWithTableTypePrimaryExpression( if (left.kind !== right.kind) { result = false; } else { - switch (left.maybeExtendedKind) { + switch (left.extendedKind) { case undefined: result = false; break; @@ -725,7 +725,7 @@ function isCompatibleWithTableTypePrimaryExpression( } function isCompatibleWithLiteral(left: Type.TPowerQueryType, right: T): boolean { - if (left.kind !== right.kind || !left.maybeExtendedKind || left.maybeExtendedKind !== right.maybeExtendedKind) { + if (left.kind !== right.kind || !left.extendedKind || left.extendedKind !== right.extendedKind) { return false; } else { return left.normalizedLiteral === right.normalizedLiteral; @@ -748,14 +748,14 @@ function isCompatibleDefinedListOrDefinedListType; if ( - left.maybeExtendedKind === Type.ExtendedTypeKind.DefinedList && - right.maybeExtendedKind === Type.ExtendedTypeKind.DefinedList + left.extendedKind === Type.ExtendedTypeKind.DefinedList && + right.extendedKind === Type.ExtendedTypeKind.DefinedList ) { leftElements = left.elements; rightElements = right.elements; } else if ( - left.maybeExtendedKind === Type.ExtendedTypeKind.DefinedListType && - right.maybeExtendedKind === Type.ExtendedTypeKind.DefinedListType + left.extendedKind === Type.ExtendedTypeKind.DefinedListType && + right.extendedKind === Type.ExtendedTypeKind.DefinedListType ) { leftElements = left.itemTypes; rightElements = right.itemTypes; @@ -763,8 +763,8 @@ function isCompatibleDefinedListOrDefinedListType nameOfFunctionParameter(parameter, traceManager, trace.id)) diff --git a/src/powerquery-parser/language/type/typeUtils/primitive.ts b/src/powerquery-parser/language/type/typeUtils/primitive.ts index d2232bef..fe8c90dd 100644 --- a/src/powerquery-parser/language/type/typeUtils/primitive.ts +++ b/src/powerquery-parser/language/type/typeUtils/primitive.ts @@ -5,7 +5,7 @@ import { Assert } from "../../../common"; import { Constant } from "../../constant"; import { Type } from ".."; -export function maybePrimitiveTypeConstantKindFromTypeKind( +export function primitiveTypeConstantKindFromTypeKind( typeKind: Type.TypeKind, ): Constant.PrimitiveTypeConstant | undefined { switch (typeKind) { diff --git a/src/powerquery-parser/language/type/typeUtils/simplify.ts b/src/powerquery-parser/language/type/typeUtils/simplify.ts index 91311094..7c385855 100644 --- a/src/powerquery-parser/language/type/typeUtils/simplify.ts +++ b/src/powerquery-parser/language/type/typeUtils/simplify.ts @@ -23,44 +23,44 @@ import { TypeUtilsTraceConstant } from "./typeTraceConstant"; export function simplify( types: ReadonlyArray, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): ReadonlyArray { - const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.Simplify, simplify.name, maybeCorrelationId); + const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.Simplify, simplify.name, correlationId); const categorized: CategorizedPowerQueryTypes = categorize(types, traceManager, trace.id); // If an `any` exists then that's as simplified as we can make it. - const maybeAny: Type.Any | undefined = maybeFindAnyPrimitive(categorized); + const any: Type.Any | undefined = findAnyPrimitive(categorized); - if (maybeAny) { - return [maybeAny]; + if (any) { + return [any]; } const partial: Type.TPowerQueryType[] = [ - ...(categorized.maybeAction?.primitives.values() ?? []), - ...(categorized.maybeAnyNonNull?.primitives.values() ?? []), - ...(categorized.maybeBinary?.primitives.values() ?? []), - ...(categorized.maybeDate?.primitives.values() ?? []), - ...(categorized.maybeDateTime?.primitives.values() ?? []), - ...(categorized.maybeDateTimeZone?.primitives.values() ?? []), - ...(categorized.maybeDuration?.primitives.values() ?? []), - ...(categorized.maybeNone?.primitives.values() ?? []), - ...(categorized.maybeNotApplicable?.primitives.values() ?? []), - ...(categorized.maybeNull?.primitives.values() ?? []), - ...(categorized.maybeTime?.primitives.values() ?? []), - ...(categorized.maybeUnknown?.primitives.values() ?? []), - - ...simplifyFunctionCategory(categorized.maybeFunction), - ...simplifyListCategory(categorized.maybeList), - ...simplifyLogicalCategory(categorized.maybeLogical), - ...simplifyNumberCategory(categorized.maybeNumber), - ...simplifyRecordCategory(categorized.maybeRecord), - ...simplifyTableCategory(categorized.maybeTable), - ...simplifyTextCategory(categorized.maybeText), - ...simplifyTypeCategory(categorized.maybeType), + ...(categorized.actions?.primitives.values() ?? []), + ...(categorized.anyNonNulls?.primitives.values() ?? []), + ...(categorized.binaries?.primitives.values() ?? []), + ...(categorized.dates?.primitives.values() ?? []), + ...(categorized.dateTimes?.primitives.values() ?? []), + ...(categorized.dateTimeZones?.primitives.values() ?? []), + ...(categorized.durations?.primitives.values() ?? []), + ...(categorized.nones?.primitives.values() ?? []), + ...(categorized.notApplicables?.primitives.values() ?? []), + ...(categorized.nulls?.primitives.values() ?? []), + ...(categorized.times?.primitives.values() ?? []), + ...(categorized.unknowns?.primitives.values() ?? []), + + ...simplifyFunctionCategory(categorized.functions), + ...simplifyListCategory(categorized.lists), + ...simplifyLogicalCategory(categorized.logicals), + ...simplifyNumberCategory(categorized.numbers), + ...simplifyRecordCategory(categorized.records), + ...simplifyTableCategory(categorized.tables), + ...simplifyTextCategory(categorized.texts), + ...simplifyTypeCategory(categorized.types), ]; - for (const flattenedValue of simplifyAnyCategory(categorized.maybeAny)) { + for (const flattenedValue of simplifyAnyCategory(categorized.anys)) { if (!ArrayUtils.includesUnique(partial, flattenedValue, isEqualType)) { partial.push(flattenedValue); } @@ -85,107 +85,79 @@ function firstNullableElseFirst(immutableSet: Im return setValues[0]; } -function maybeFindAnyPrimitive(categorized: CategorizedPowerQueryTypes): Type.Any | undefined { - const maybeAnySet: ImmutableSet | undefined = categorized.maybeAny?.primitives; +function findAnyPrimitive(categorized: CategorizedPowerQueryTypes): Type.Any | undefined { + const anySet: ImmutableSet | undefined = categorized.anys?.primitives; - if (maybeAnySet === undefined) { - return undefined; - } - - return firstNullableElseFirst(maybeAnySet); + return anySet ? firstNullableElseFirst(anySet) : undefined; } -function simplifyAnyCategory(maybeCategory: AnyCategory | undefined): ReadonlyArray { - if (!maybeCategory?.flattenedAnyUnions) { +function simplifyAnyCategory(category: AnyCategory | undefined): ReadonlyArray { + if (!category?.flattenedAnyUnions) { return []; } else { - const flattnedAnyUnions: ImmutableSet = maybeCategory?.flattenedAnyUnions; + const flattnedAnyUnions: ImmutableSet = category?.flattenedAnyUnions; return [...flattnedAnyUnions.values()]; } } -function simplifyFunctionCategory(maybeCategory: FunctionCategory | undefined): ReadonlyArray { - if (maybeCategory === undefined) { - return []; - } - - return simplifyExtendedType(maybeCategory.primitives, maybeCategory.definedFunctions); +function simplifyFunctionCategory(category: FunctionCategory | undefined): ReadonlyArray { + return category ? simplifyExtendedType(category.primitives, category.definedFunctions) : []; } -function simplifyListCategory(maybeCategory: ListCategory | undefined): ReadonlyArray { - if (maybeCategory === undefined) { - return []; - } - - return simplifyExtendedType(maybeCategory.primitives, maybeCategory.definedLists); +function simplifyListCategory(category: ListCategory | undefined): ReadonlyArray { + return category ? simplifyExtendedType(category.primitives, category.definedLists) : []; } -function simplifyLogicalCategory(maybeCategory: LogicalCategory | undefined): ReadonlyArray { - if (maybeCategory === undefined) { +function simplifyLogicalCategory(category: LogicalCategory | undefined): ReadonlyArray { + if (category === undefined) { return []; } else if ( - (maybeCategory.hasFalsyNullableLiteral || maybeCategory.hasFalsyNonNullableLiteral) && - (maybeCategory.hasTruthyNullableLiteral || maybeCategory.hasTruthyNonNullableLiteral) + (category.hasFalsyNullableLiteral || category.hasFalsyNonNullableLiteral) && + (category.hasTruthyNullableLiteral || category.hasTruthyNonNullableLiteral) ) { - return maybeCategory.hasFalsyNullableLiteral || maybeCategory.hasTruthyNullableLiteral + return category.hasFalsyNullableLiteral || category.hasTruthyNullableLiteral ? [Type.NullableLogicalInstance] : [Type.LogicalInstance]; } else { - const maybeType: Type.Logical | undefined = firstNullableElseFirst(maybeCategory.primitives); + const type: Type.Logical | undefined = firstNullableElseFirst(category.primitives); - return maybeType ? [maybeType] : []; + return type ? [type] : []; } } -function simplifyNumberCategory(maybeCategory: NumberCategory | undefined): ReadonlyArray { - if (maybeCategory === undefined) { - return []; - } - - return simplifyExtendedType(maybeCategory.primitives, maybeCategory.literals); +function simplifyNumberCategory(category: NumberCategory | undefined): ReadonlyArray { + return category ? simplifyExtendedType(category.primitives, category.literals) : []; } -function simplifyRecordCategory(maybeCategory: RecordCategory | undefined): ReadonlyArray { - if (maybeCategory === undefined) { - return []; - } - - return simplifyExtendedType(maybeCategory.primitives, maybeCategory.definedRecords); +function simplifyRecordCategory(category: RecordCategory | undefined): ReadonlyArray { + return category ? simplifyExtendedType(category.primitives, category.definedRecords) : []; } -function simplifyTableCategory(maybeCategory: TableCategory | undefined): ReadonlyArray { - if (maybeCategory === undefined) { - return []; - } - - return simplifyExtendedType(maybeCategory.primitives, maybeCategory.definedTables); +function simplifyTableCategory(category: TableCategory | undefined): ReadonlyArray { + return category ? simplifyExtendedType(category.primitives, category.definedTables) : []; } -function simplifyTextCategory(maybeCategory: TextCategory | undefined): ReadonlyArray { - if (maybeCategory === undefined) { - return []; - } - - return simplifyExtendedType(maybeCategory.primitives, maybeCategory.literals); +function simplifyTextCategory(category: TextCategory | undefined): ReadonlyArray { + return category ? simplifyExtendedType(category.primitives, category.literals) : []; } -function simplifyTypeCategory(maybeCategory: TypeCategory | undefined): ReadonlyArray { - if (maybeCategory === undefined) { +function simplifyTypeCategory(category: TypeCategory | undefined): ReadonlyArray { + if (category === undefined) { return []; - } else if (maybeCategory.primitives.size) { - const maybeType: Type.Type | undefined | undefined = firstNullableElseFirst(maybeCategory.primitives); + } else if (category.primitives.size) { + const typeType: Type.Type | undefined | undefined = firstNullableElseFirst(category.primitives); - return maybeType ? [maybeType] : []; + return typeType ? [typeType] : []; } else { return [ - ...maybeCategory.definedListTypes.values(), - ...maybeCategory.functionTypes.values(), - ...maybeCategory.listTypes.values(), - ...maybeCategory.primaryPrimitiveTypes.values(), - ...maybeCategory.recordTypes.values(), - ...maybeCategory.tablePrimaryExpressionTypes.values(), - ...maybeCategory.tableTypes.values(), + ...category.definedListTypes.values(), + ...category.functionTypes.values(), + ...category.listTypes.values(), + ...category.primaryPrimitiveTypes.values(), + ...category.recordTypes.values(), + ...category.tablePrimaryExpressionTypes.values(), + ...category.tableTypes.values(), ]; } } @@ -195,9 +167,9 @@ function simplifyExtendedType, ): ReadonlyArray | ReadonlyArray { if (primitives.size) { - const maybeType: T | undefined = firstNullableElseFirst(primitives); + const type: T | undefined = firstNullableElseFirst(primitives); - return maybeType ? [maybeType] : []; + return type ? [type] : []; } else if (literals.size) { return [...literals.values()]; } else { diff --git a/src/powerquery-parser/language/type/typeUtils/typeCheck.ts b/src/powerquery-parser/language/type/typeUtils/typeCheck.ts index 6c49be49..ebd1ed03 100644 --- a/src/powerquery-parser/language/type/typeUtils/typeCheck.ts +++ b/src/powerquery-parser/language/type/typeUtils/typeCheck.ts @@ -66,13 +66,9 @@ export function typeCheckFunction( valueType: Type.DefinedFunction, schemaType: Type.FunctionType, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): CheckedDefinedFunction { - const trace: Trace = traceManager.entry( - TypeUtilsTraceConstant.TypeCheck, - typeCheckFunction.name, - maybeCorrelationId, - ); + const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.TypeCheck, typeCheckFunction.name, correlationId); const result: CheckedDefinedFunction = { ...typeCheckFunctionSignature(valueType, schemaType, traceManager, trace.id), @@ -89,12 +85,12 @@ export function typeCheckFunctionSignature( valueType: Type.FunctionSignature, schemaType: Type.FunctionSignature, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): CheckedFunctionSignature { const trace: Trace = traceManager.entry( TypeUtilsTraceConstant.TypeCheck, typeCheckFunctionSignature.name, - maybeCorrelationId, + correlationId, ); const result: CheckedFunctionSignature = typeCheckGenericNumber( @@ -114,13 +110,9 @@ export function typeCheckInvocation( args: ReadonlyArray, definedFunction: Type.DefinedFunction, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): CheckedInvocation { - const trace: Trace = traceManager.entry( - TypeUtilsTraceConstant.TypeCheck, - typeCheckInvocation.name, - maybeCorrelationId, - ); + const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.TypeCheck, typeCheckInvocation.name, correlationId); const parameters: ReadonlyArray = definedFunction.parameters; const numArgs: number = args.length; @@ -134,15 +126,15 @@ export function typeCheckInvocation( const invalidArgs: Map = new Map(); for (let index: number = 0; index < numParameters; index += 1) { - const maybeArg: Type.TPowerQueryType | undefined = args[index]; + const arg: Type.TPowerQueryType | undefined = args[index]; const parameter: Type.FunctionParameter = parameters[index]; - if (isCompatibleWithFunctionParameter(maybeArg, parameter)) { + if (isCompatibleWithFunctionParameter(arg, parameter)) { validArgs.push(index); - } else if (maybeArg !== undefined) { + } else if (arg !== undefined) { invalidArgs.set(index, { expected: parameter, - actual: maybeArg, + actual: arg, }); } else { missingArgs.push(index); @@ -165,12 +157,12 @@ export function typeCheckListWithListType( valueType: Type.DefinedList, schemaType: Type.ListType, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): CheckedDefinedList { const trace: Trace = traceManager.entry( TypeUtilsTraceConstant.TypeCheck, typeCheckListWithListType.name, - maybeCorrelationId, + correlationId, ); const validArgs: number[] = []; @@ -209,45 +201,27 @@ export function typeCheckListWithDefinedListType( valueType: Type.DefinedList, schemaType: Type.DefinedListType, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): CheckedDefinedList { - return typeCheckGenericNumber( - valueType.elements, - schemaType.itemTypes, - isCompatible, - traceManager, - maybeCorrelationId, - ); + return typeCheckGenericNumber(valueType.elements, schemaType.itemTypes, isCompatible, traceManager, correlationId); } export function typeCheckRecord( valueType: Type.DefinedRecord, schemaType: Type.RecordType, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): CheckedDefinedRecord { - return typeCheckRecordOrTable( - valueType.fields, - schemaType.fields, - schemaType.isOpen, - traceManager, - maybeCorrelationId, - ); + return typeCheckRecordOrTable(valueType.fields, schemaType.fields, schemaType.isOpen, traceManager, correlationId); } export function typeCheckTable( valueType: Type.DefinedTable, schemaType: Type.TableType, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): CheckedDefinedTable { - return typeCheckRecordOrTable( - valueType.fields, - schemaType.fields, - schemaType.isOpen, - traceManager, - maybeCorrelationId, - ); + return typeCheckRecordOrTable(valueType.fields, schemaType.fields, schemaType.isOpen, traceManager, correlationId); } function typeCheckGenericNumber< @@ -256,12 +230,7 @@ function typeCheckGenericNumber< >( valueElements: ReadonlyArray, schemaItemTypes: ReadonlyArray, - valueCmpFn: ( - left: Value, - right: Schema, - traceManager: TraceManager, - maybeCorrelationId: number, - ) => boolean | undefined, + comparer: (left: Value, right: Schema, traceManager: TraceManager, correlationId: number) => boolean | undefined, traceManager: TraceManager, correlationId: number | undefined, ): IChecked> { @@ -295,7 +264,7 @@ function typeCheckGenericNumber< const element: Value = valueElements[index]; const schemaItemType: Schema = schemaItemTypes[index]; - if (valueCmpFn(element, schemaItemType, traceManager, trace.id)) { + if (comparer(element, schemaItemType, traceManager, trace.id)) { validIndices.push(index); } else { mismatches.set(index, { @@ -322,12 +291,12 @@ function typeCheckRecordOrTable( schemaFields: Map, schemaIsOpen: boolean, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): IChecked> { const trace: Trace = traceManager.entry( TypeUtilsTraceConstant.TypeCheck, typeCheckRecordOrTable.name, - maybeCorrelationId, + correlationId, ); const validFields: string[] = []; @@ -339,11 +308,9 @@ function typeCheckRecordOrTable( ); for (const [key, type] of valueFields.entries()) { - const maybeSchemaValueType: Type.TPowerQueryType | undefined = schemaFields.get(key); - - if (maybeSchemaValueType !== undefined) { - const schemaValueType: Type.TPowerQueryType = maybeSchemaValueType; + const schemaValueType: Type.TPowerQueryType | undefined = schemaFields.get(key); + if (schemaValueType !== undefined) { if (isCompatible(type, schemaValueType, traceManager, trace.id)) { validFields.push(key); } else { diff --git a/src/powerquery-parser/language/type/typeUtils/typeUtils.ts b/src/powerquery-parser/language/type/typeUtils/typeUtils.ts index d34fd3d5..959837d7 100644 --- a/src/powerquery-parser/language/type/typeUtils/typeUtils.ts +++ b/src/powerquery-parser/language/type/typeUtils/typeUtils.ts @@ -78,13 +78,9 @@ export function isValidInvocation( functionType: Type.DefinedFunction, args: ReadonlyArray, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): boolean { - const trace: Trace = traceManager.entry( - TypeUtilsTraceConstant.TypeUtils, - isValidInvocation.name, - maybeCorrelationId, - ); + const trace: Trace = traceManager.entry(TypeUtilsTraceConstant.TypeUtils, isValidInvocation.name, correlationId); // You can't provide more arguments than are on the function signature. if (args.length > functionType.parameters.length) { @@ -96,14 +92,12 @@ export function isValidInvocation( for (let index: number = 1; index < numParameters; index += 1) { const parameter: Type.FunctionParameter = Assert.asDefined(parameters[index]); - const maybeArgType: Type.TPowerQueryType | undefined = args[index]; - - if (maybeArgType !== undefined) { - const argType: Type.TPowerQueryType = maybeArgType; + const argType: Type.TPowerQueryType | undefined = args[index]; + if (argType !== undefined) { const parameterType: Type.TPowerQueryType = createPrimitiveType( parameter.isNullable, - Assert.asDefined(parameter.maybeType), + Assert.asDefined(parameter.type), ); if (!isCompatible(argType, parameterType, traceManager, trace.id)) { @@ -143,25 +137,23 @@ export function inspectParameter( function inspectAstParameter(node: Ast.TParameter): Type.FunctionParameter { let isNullable: boolean; - let maybeType: Type.TypeKind | undefined; - - const maybeParameterType: Ast.TParameterType | undefined = node.maybeParameterType; + let type: Type.TypeKind | undefined; - if (maybeParameterType !== undefined) { - const parameterType: Ast.TParameterType = maybeParameterType; + const parameterType: Ast.TParameterType | undefined = node.parameterType; + if (parameterType !== undefined) { switch (parameterType.kind) { case Ast.NodeKind.AsNullablePrimitiveType: { const simplified: AstUtils.SimplifiedType = AstUtils.simplifyAsNullablePrimitiveType(parameterType); isNullable = simplified.isNullable; - maybeType = typeKindFromPrimitiveTypeConstantKind(simplified.primitiveTypeConstantKind); + type = typeKindFromPrimitiveTypeConstantKind(simplified.primitiveTypeConstantKind); break; } case Ast.NodeKind.AsType: { const simplified: AstUtils.SimplifiedType = AstUtils.simplifyType(parameterType.paired); isNullable = simplified.isNullable; - maybeType = typeKindFromPrimitiveTypeConstantKind(simplified.primitiveTypeConstantKind); + type = typeKindFromPrimitiveTypeConstantKind(simplified.primitiveTypeConstantKind); break; } @@ -170,14 +162,14 @@ function inspectAstParameter(node: Ast.TParameter): Type.FunctionParameter { } } else { isNullable = true; - maybeType = undefined; + type = undefined; } return { nameLiteral: node.name.literal, isNullable, - isOptional: node.maybeOptionalConstant !== undefined, - maybeType, + isOptional: node.optionalConstant !== undefined, + type, }; } @@ -186,49 +178,48 @@ function inspectContextParameter( parameter: ParseContext.Node, ): Type.FunctionParameter | undefined { let isNullable: boolean; - let maybeType: Type.TypeKind | undefined; + let type: Type.TypeKind | undefined; - const maybeName: Ast.Identifier | undefined = NodeIdMapUtils.maybeUnboxNthChildIfAstChecked( + const name: Ast.Identifier | undefined = NodeIdMapUtils.unboxNthChildIfAstChecked( nodeIdMapCollection, parameter.id, 1, Ast.NodeKind.Identifier, ); - if (maybeName === undefined) { + if (name === undefined) { return undefined; } - const maybeOptional: Ast.TConstant | undefined = NodeIdMapUtils.maybeUnboxNthChildIfAstChecked( + const optionalConstant: Ast.TConstant | undefined = NodeIdMapUtils.unboxNthChildIfAstChecked( nodeIdMapCollection, parameter.id, 0, Ast.NodeKind.Constant, ); - const isOptional: boolean = maybeOptional !== undefined; + const isOptional: boolean = optionalConstant !== undefined; - const maybeParameterType: Ast.AsNullablePrimitiveType | undefined = NodeIdMapUtils.maybeUnboxNthChildIfAstChecked( + const parameterType: Ast.AsNullablePrimitiveType | undefined = NodeIdMapUtils.unboxNthChildIfAstChecked( nodeIdMapCollection, parameter.id, 2, Ast.NodeKind.AsNullablePrimitiveType, ); - if (maybeParameterType !== undefined) { - const parameterType: Ast.AsNullablePrimitiveType = maybeParameterType; + if (parameterType !== undefined) { const simplified: AstUtils.SimplifiedType = AstUtils.simplifyAsNullablePrimitiveType(parameterType); isNullable = simplified.isNullable; - maybeType = typeKindFromPrimitiveTypeConstantKind(simplified.primitiveTypeConstantKind); + type = typeKindFromPrimitiveTypeConstantKind(simplified.primitiveTypeConstantKind); } else { isNullable = true; - maybeType = undefined; + type = undefined; } return { - nameLiteral: maybeName.literal, + nameLiteral: name.literal, isOptional, isNullable, - maybeType, + type, }; } diff --git a/src/powerquery-parser/lexer/lexer.ts b/src/powerquery-parser/lexer/lexer.ts index 62c401ba..9c809cc3 100644 --- a/src/powerquery-parser/lexer/lexer.ts +++ b/src/powerquery-parser/lexer/lexer.ts @@ -63,7 +63,7 @@ export const enum LineMode { export interface State { readonly lines: ReadonlyArray; readonly locale: string; - readonly maybeCancellationToken: ICancellationToken | undefined; + readonly cancellationToken: ICancellationToken | undefined; } export interface ILexerLine { @@ -207,7 +207,7 @@ export function isErrorLine(line: TLine): line is TErrorLine { } } -export function maybeErrorLineMap(state: State): ErrorLineMap | undefined { +export function errorLineMap(state: State): ErrorLineMap | undefined { const errorLines: ErrorLineMap = state.lines.reduce((errorLineMap: ErrorLineMap, line: TLine, index: number) => { if (isErrorLine(line)) { errorLineMap.set(index, line); @@ -312,25 +312,25 @@ function lex(settings: LexSettings, text: string): State { splitLines, LineMode.Default, settings.locale, - settings.maybeCancellationToken, + settings.cancellationToken, ); return { lines: tokenizedLines, locale: settings.locale, - maybeCancellationToken: settings.maybeCancellationToken, + cancellationToken: settings.cancellationToken, }; } function appendLine(state: State, text: string, lineTerminator: string): State { - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const lines: ReadonlyArray = state.lines; const numLines: number = lines.length; - const maybeLatestLine: TLine | undefined = lines[numLines - 1]; - const lineModeStart: LineMode = maybeLatestLine ? maybeLatestLine.lineModeEnd : LineMode.Default; + const latestLine: TLine | undefined = lines[numLines - 1]; + const lineModeStart: LineMode = latestLine ? latestLine.lineModeEnd : LineMode.Default; const untokenizedLine: UntouchedLine = lineFrom(text, lineTerminator, lineModeStart); - const tokenizedLine: TLine = tokenize(untokenizedLine, numLines, state.locale, state.maybeCancellationToken); + const tokenizedLine: TLine = tokenize(untokenizedLine, numLines, state.locale, state.cancellationToken); return { ...state, @@ -339,12 +339,12 @@ function appendLine(state: State, text: string, lineTerminator: string): State { } function updateLine(state: State, lineNumber: number, text: string): State { - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); - const maybeError: LexError.BadLineNumberError | undefined = testLineNumberError(state, lineNumber); + const error: LexError.BadLineNumberError | undefined = testLineNumberError(state, lineNumber); - if (maybeError !== undefined) { - throw maybeError; + if (error !== undefined) { + throw error; } const line: TLine = state.lines[lineNumber]; @@ -354,11 +354,12 @@ function updateLine(state: State, lineNumber: number, text: string): State { } function updateRange(state: State, range: Range, text: string): State { - state.maybeCancellationToken?.throwIfCancelled(); - const maybeError: LexError.BadRangeError | undefined = testBadRangeError(state, range); + state.cancellationToken?.throwIfCancelled(); - if (maybeError !== undefined) { - throw maybeError; + const error: LexError.BadRangeError | undefined = testBadRangeError(state, range); + + if (error !== undefined) { + throw error; } const splitLines: SplitLine[] = splitOnLineTerminators(text); @@ -377,14 +378,14 @@ function updateRange(state: State, range: Range, text: string): State { // make sure we have a line terminator lastSplitLine.lineTerminator = lineEnd.lineTerminator; - const maybePreviousLine: TLine | undefined = state.lines[rangeStart.lineNumber - 1]; - const previousLineModeEnd: LineMode = maybePreviousLine?.lineModeEnd ?? LineMode.Default; + const previousLine: TLine | undefined = state.lines[rangeStart.lineNumber - 1]; + const previousLineModeEnd: LineMode = previousLine?.lineModeEnd ?? LineMode.Default; const newLines: ReadonlyArray = tokenizedLinesFrom( splitLines, previousLineModeEnd, state.locale, - state.maybeCancellationToken, + state.cancellationToken, ); const lines: ReadonlyArray = [ @@ -396,17 +397,17 @@ function updateRange(state: State, range: Range, text: string): State { return { lines, locale: state.locale, - maybeCancellationToken: state.maybeCancellationToken, + cancellationToken: state.cancellationToken, }; } function deleteLine(state: State, lineNumber: number): State { - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); - const maybeError: LexError.BadLineNumberError | undefined = testLineNumberError(state, lineNumber); + const error: LexError.BadLineNumberError | undefined = testLineNumberError(state, lineNumber); - if (maybeError !== undefined) { - throw maybeError; + if (error !== undefined) { + throw error; } return { @@ -447,7 +448,7 @@ function tokenizedLinesFrom( splitLines: ReadonlyArray, previousLineModeEnd: LineMode, locale: string, - maybeCancellationToken: ICancellationToken | undefined, + cancellationToken: ICancellationToken | undefined, ): ReadonlyArray { const numLines: number = splitLines.length; const tokenizedLines: TLine[] = []; @@ -455,7 +456,7 @@ function tokenizedLinesFrom( for (let lineNumber: number = 0; lineNumber < numLines; lineNumber += 1) { const splitLine: SplitLine = splitLines[lineNumber]; const untokenizedLine: UntouchedLine = lineFrom(splitLine.text, splitLine.lineTerminator, previousLineModeEnd); - const tokenizedLine: TLine = tokenize(untokenizedLine, lineNumber, locale, maybeCancellationToken); + const tokenizedLine: TLine = tokenize(untokenizedLine, lineNumber, locale, cancellationToken); tokenizedLines.push(tokenizedLine); previousLineModeEnd = tokenizedLine.lineModeEnd; } @@ -478,10 +479,10 @@ function retokenizeLines(state: State, lineNumber: number, previousLineModeEnd: if (previousLineModeEnd !== lines[lineNumber].lineModeStart) { const offsetLineNumber: number = lineNumber; - let maybeCurrentLine: TLine | undefined = lines[lineNumber]; + let currentLine: TLine | undefined = lines[lineNumber]; - while (maybeCurrentLine) { - const line: TLine = maybeCurrentLine; + while (currentLine) { + const line: TLine = currentLine; if (previousLineModeEnd !== line.lineModeStart) { const untokenizedLine: UntouchedLine = lineFrom(line.text, line.lineTerminator, previousLineModeEnd); @@ -490,13 +491,13 @@ function retokenizeLines(state: State, lineNumber: number, previousLineModeEnd: untokenizedLine, offsetLineNumber, state.locale, - state.maybeCancellationToken, + state.cancellationToken, ); retokenizedLines.push(retokenizedLine); previousLineModeEnd = retokenizedLine.lineModeEnd; lineNumber += 1; - maybeCurrentLine = lines[lineNumber]; + currentLine = lines[lineNumber]; } else { return [...retokenizedLines, ...lines.slice(lineNumber + 1)]; } @@ -513,9 +514,9 @@ function tokenize( line: TLine, lineNumber: number, locale: string, - maybeCancellationToken: ICancellationToken | undefined, + cancellationToken: ICancellationToken | undefined, ): TLine { - maybeCancellationToken?.throwIfCancelled(); + cancellationToken?.throwIfCancelled(); switch (line.kind) { // Cannot tokenize something that ended with an error, @@ -579,14 +580,14 @@ function tokenize( const newTokens: Token.LineToken[] = []; let continueLexing: boolean = currentPosition !== text.length; - let maybeError: LexError.TLexError | undefined; + let lexError: LexError.TLexError | undefined; // While neither eof nor having encountered an error: // * Lex according to lineModeStart, starting from currentPosition. // * Update currentPosition and lineMode. // * Drain whitespace. while (continueLexing) { - maybeCancellationToken?.throwIfCancelled(); + cancellationToken?.throwIfCancelled(); try { let readOutcome: LineModeAlteringRead; @@ -636,23 +637,23 @@ function tokenize( } continueLexing = false; - maybeError = error; + lexError = error; } } let partialTokenizeResult: PartialResult; - if (maybeError) { + if (lexError) { if (newTokens.length) { partialTokenizeResult = PartialResultUtils.createMixed( { tokens: newTokens, lineModeEnd: lineMode, }, - maybeError, + lexError, ); } else { - partialTokenizeResult = PartialResultUtils.createError(maybeError); + partialTokenizeResult = PartialResultUtils.createError(lexError); } } else { partialTokenizeResult = PartialResultUtils.createOk({ @@ -769,18 +770,16 @@ function tokenizeQuotedIdentifierContentOrEnd(line: TLine, currentPosition: numb // Read until either string literal end or eof function tokenizeTextLiteralContentOrEnd(line: TLine, currentPosition: number): LineModeAlteringRead { const text: string = line.text; - const maybePositionEnd: number | undefined = maybeIndexOfTextEnd(text, currentPosition); + const positionEnd: number | undefined = indexOfTextEnd(text, currentPosition); - if (maybePositionEnd === undefined) { + if (positionEnd === undefined) { return { token: readRestOfLine(Token.LineTokenKind.TextLiteralContent, text, currentPosition), lineMode: LineMode.Text, }; } else { - const positionEnd: number = maybePositionEnd + 1; - return { - token: readTokenFrom(Token.LineTokenKind.TextLiteralEnd, text, currentPosition, positionEnd), + token: readTokenFrom(Token.LineTokenKind.TextLiteralEnd, text, currentPosition, positionEnd + 1), lineMode: LineMode.Default, }; } @@ -924,10 +923,10 @@ function drainWhitespace(text: string, position: number): number { let continueDraining: boolean = text[position] !== undefined; while (continueDraining) { - const maybeLength: number | undefined = StringUtils.maybeRegexMatchLength(Pattern.Whitespace, text, position); + const length: number | undefined = StringUtils.regexMatchLength(Pattern.Whitespace, text, position); - if (maybeLength) { - position += maybeLength; + if (length) { + position += length; } else { continueDraining = false; } @@ -937,13 +936,11 @@ function drainWhitespace(text: string, position: number): number { } function readOrStartTextLiteral(text: string, currentPosition: number): LineModeAlteringRead { - const maybePositionEnd: number | undefined = maybeIndexOfTextEnd(text, currentPosition + 1); - - if (maybePositionEnd !== undefined) { - const positionEnd: number = maybePositionEnd + 1; + const positionEnd: number | undefined = indexOfTextEnd(text, currentPosition + 1); + if (positionEnd !== undefined) { return { - token: readTokenFrom(Token.LineTokenKind.TextLiteral, text, currentPosition, positionEnd), + token: readTokenFrom(Token.LineTokenKind.TextLiteral, text, currentPosition, positionEnd + 1), lineMode: LineMode.Default, }; } else { @@ -955,9 +952,9 @@ function readOrStartTextLiteral(text: string, currentPosition: number): LineMode } function readHexLiteral(text: string, lineNumber: number, positionStart: number, locale: string): Token.LineToken { - const maybePositionEnd: number | undefined = maybeIndexOfRegexEnd(Pattern.Hex, text, positionStart); + const positionEnd: number | undefined = indexOfRegexEnd(Pattern.Hex, text, positionStart); - if (maybePositionEnd === undefined) { + if (positionEnd === undefined) { throw new LexError.ExpectedError( graphemePositionFrom(text, lineNumber, positionStart), LexError.ExpectedKind.HexLiteral, @@ -965,15 +962,13 @@ function readHexLiteral(text: string, lineNumber: number, positionStart: number, ); } - const positionEnd: number = maybePositionEnd; - return readTokenFrom(Token.LineTokenKind.HexLiteral, text, positionStart, positionEnd); } function readNumericLiteral(text: string, lineNumber: number, positionStart: number, locale: string): Token.LineToken { - const maybePositionEnd: number | undefined = maybeIndexOfRegexEnd(Pattern.Numeric, text, positionStart); + const positionEnd: number | undefined = indexOfRegexEnd(Pattern.Numeric, text, positionStart); - if (maybePositionEnd === undefined) { + if (positionEnd === undefined) { throw new LexError.ExpectedError( graphemePositionFrom(text, lineNumber, positionStart), LexError.ExpectedKind.Numeric, @@ -981,8 +976,6 @@ function readNumericLiteral(text: string, lineNumber: number, positionStart: num ); } - const positionEnd: number = maybePositionEnd; - return readTokenFrom(Token.LineTokenKind.NumericLiteral, text, positionStart, positionEnd); } @@ -1009,34 +1002,32 @@ function readOrStartMultilineComment(text: string, positionStart: number): LineM } function readKeyword(text: string, lineNumber: number, positionStart: number, locale: string): Token.LineToken { - const maybeLineToken: Token.LineToken | undefined = maybeReadKeyword(text, positionStart); + const lineToken: Token.LineToken | undefined = readKeywordHelper(text, positionStart); - if (maybeLineToken) { - return maybeLineToken; + if (lineToken) { + return lineToken; } else { throw unexpectedReadError(locale, text, lineNumber, positionStart); } } -function maybeReadKeyword(text: string, currentPosition: number): Token.LineToken | undefined { +function readKeywordHelper(text: string, currentPosition: number): Token.LineToken | undefined { const identifierPositionStart: number = text[currentPosition] === "#" ? currentPosition + 1 : currentPosition; - const maybeIdentifierPositionEnd: number | undefined = maybeIndexOfIdentifierEnd(text, identifierPositionStart); + const identifierPositionEnd: number | undefined = indexOfIdentifierEnd(text, identifierPositionStart); - if (maybeIdentifierPositionEnd === undefined) { + if (identifierPositionEnd === undefined) { return undefined; } - const identifierPositionEnd: number = maybeIdentifierPositionEnd; - const data: string = text.substring(currentPosition, identifierPositionEnd); - const maybeKeywordTokenKind: Token.LineTokenKind | undefined = maybeKeywordLineTokenKindFrom(data); + const keywordTokenKind: Token.LineTokenKind | undefined = keywordLineTokenKindFrom(data); - if (maybeKeywordTokenKind === undefined) { + if (keywordTokenKind === undefined) { return undefined; } else { return { - kind: maybeKeywordTokenKind, + kind: keywordTokenKind, positionStart: currentPosition, positionEnd: identifierPositionEnd, data, @@ -1045,13 +1036,11 @@ function maybeReadKeyword(text: string, currentPosition: number): Token.LineToke } function readOrStartQuotedIdentifier(text: string, currentPosition: number): LineModeAlteringRead { - const maybePositionEnd: number | undefined = maybeIndexOfTextEnd(text, currentPosition + 2); - - if (maybePositionEnd !== undefined) { - const positionEnd: number = maybePositionEnd + 1; + const positionEnd: number | undefined = indexOfTextEnd(text, currentPosition + 2); + if (positionEnd !== undefined) { return { - token: readTokenFrom(Token.LineTokenKind.Identifier, text, currentPosition, positionEnd), + token: readTokenFrom(Token.LineTokenKind.Identifier, text, currentPosition, positionEnd + 1), lineMode: LineMode.Default, }; } else { @@ -1076,9 +1065,9 @@ function readKeywordOrIdentifier( } // either keyword or identifier else { - const maybePositionEnd: number | undefined = maybeIndexOfIdentifierEnd(text, positionStart); + const positionEnd: number | undefined = indexOfIdentifierEnd(text, positionStart); - if (maybePositionEnd === undefined) { + if (positionEnd === undefined) { throw new LexError.ExpectedError( graphemePositionFrom(text, lineNumber, positionStart), LexError.ExpectedKind.KeywordOrIdentifier, @@ -1086,14 +1075,13 @@ function readKeywordOrIdentifier( ); } - const positionEnd: number = maybePositionEnd; const data: string = text.substring(positionStart, positionEnd); - const maybeKeywordTokenKind: Token.LineTokenKind | undefined = maybeKeywordLineTokenKindFrom(data); + const keywordTokenKind: Token.LineTokenKind | undefined = keywordLineTokenKindFrom(data); let tokenKind: Token.LineTokenKind; - if (maybeKeywordTokenKind !== undefined) { - tokenKind = maybeKeywordTokenKind; + if (keywordTokenKind !== undefined) { + tokenKind = keywordTokenKind; } else if (data === "null") { tokenKind = Token.LineTokenKind.NullLiteral; } else { @@ -1140,88 +1128,119 @@ function readRestOfLine(lineTokenKind: Token.LineTokenKind, text: string, positi return readTokenFrom(lineTokenKind, text, positionStart, positionEnd); } -function maybeIndexOfRegexEnd(pattern: RegExp, text: string, positionStart: number): number | undefined { - const maybeLength: number | undefined = StringUtils.maybeRegexMatchLength(pattern, text, positionStart); +function indexOfRegexEnd(pattern: RegExp, text: string, positionStart: number): number | undefined { + const length: number | undefined = StringUtils.regexMatchLength(pattern, text, positionStart); - return maybeLength !== undefined ? positionStart + maybeLength : undefined; + return length !== undefined ? positionStart + length : undefined; } -function maybeIndexOfIdentifierEnd(text: string, positionStart: number): number | undefined { - const maybeLength: number | undefined = TextUtils.maybeIdentifierLength(text, positionStart, true); +function indexOfIdentifierEnd(text: string, positionStart: number): number | undefined { + const length: number | undefined = TextUtils.identifierLength(text, positionStart, true); - return maybeLength !== undefined ? positionStart + maybeLength : undefined; + return length !== undefined ? positionStart + length : undefined; } -function maybeKeywordLineTokenKindFrom(data: string): Token.LineTokenKind | undefined { +function keywordLineTokenKindFrom(data: string): Token.LineTokenKind | undefined { switch (data) { case Keyword.KeywordKind.And: return Token.LineTokenKind.KeywordAnd; + case Keyword.KeywordKind.As: return Token.LineTokenKind.KeywordAs; + case Keyword.KeywordKind.Each: return Token.LineTokenKind.KeywordEach; + case Keyword.KeywordKind.Else: return Token.LineTokenKind.KeywordElse; + case Keyword.KeywordKind.Error: return Token.LineTokenKind.KeywordError; + case Keyword.KeywordKind.False: return Token.LineTokenKind.KeywordFalse; + case Keyword.KeywordKind.If: return Token.LineTokenKind.KeywordIf; + case Keyword.KeywordKind.In: return Token.LineTokenKind.KeywordIn; + case Keyword.KeywordKind.Is: return Token.LineTokenKind.KeywordIs; + case Keyword.KeywordKind.Let: return Token.LineTokenKind.KeywordLet; + case Keyword.KeywordKind.Meta: return Token.LineTokenKind.KeywordMeta; + case Keyword.KeywordKind.Not: return Token.LineTokenKind.KeywordNot; + case Keyword.KeywordKind.Or: return Token.LineTokenKind.KeywordOr; + case Keyword.KeywordKind.Otherwise: return Token.LineTokenKind.KeywordOtherwise; + case Keyword.KeywordKind.Section: return Token.LineTokenKind.KeywordSection; + case Keyword.KeywordKind.Shared: return Token.LineTokenKind.KeywordShared; + case Keyword.KeywordKind.Then: return Token.LineTokenKind.KeywordThen; + case Keyword.KeywordKind.True: return Token.LineTokenKind.KeywordTrue; + case Keyword.KeywordKind.Try: return Token.LineTokenKind.KeywordTry; + case Keyword.KeywordKind.Type: return Token.LineTokenKind.KeywordType; + case Keyword.KeywordKind.HashBinary: return Token.LineTokenKind.KeywordHashBinary; + case Keyword.KeywordKind.HashDate: return Token.LineTokenKind.KeywordHashDate; + case Keyword.KeywordKind.HashDateTime: return Token.LineTokenKind.KeywordHashDateTime; + case Keyword.KeywordKind.HashDateTimeZone: return Token.LineTokenKind.KeywordHashDateTimeZone; + case Keyword.KeywordKind.HashDuration: return Token.LineTokenKind.KeywordHashDuration; + case Keyword.KeywordKind.HashInfinity: return Token.LineTokenKind.KeywordHashInfinity; + case Keyword.KeywordKind.HashNan: return Token.LineTokenKind.KeywordHashNan; + case Keyword.KeywordKind.HashSections: return Token.LineTokenKind.KeywordHashSections; + case Keyword.KeywordKind.HashShared: return Token.LineTokenKind.KeywordHashShared; + case Keyword.KeywordKind.HashTable: return Token.LineTokenKind.KeywordHashTable; + case Keyword.KeywordKind.HashTime: return Token.LineTokenKind.KeywordHashTime; + default: return undefined; } } -function maybeIndexOfTextEnd(text: string, positionStart: number): number | undefined { +function indexOfTextEnd(text: string, positionStart: number): number | undefined { let indexLow: number = positionStart; let positionEnd: number = text.indexOf('"', indexLow); @@ -1274,23 +1293,21 @@ function testBadRangeError(state: State, range: Range): LexError.BadRangeError | const end: RangePosition = range.end; const numLines: number = state.lines.length; - let maybeKind: LexError.BadRangeKind | undefined; + let kind: LexError.BadRangeKind | undefined; if (start.lineNumber === end.lineNumber && start.lineCodeUnit > end.lineCodeUnit) { - maybeKind = LexError.BadRangeKind.SameLine_LineCodeUnitStart_Higher; + kind = LexError.BadRangeKind.SameLine_LineCodeUnitStart_Higher; } else if (start.lineNumber > end.lineNumber) { - maybeKind = LexError.BadRangeKind.LineNumberStart_GreaterThan_LineNumberEnd; + kind = LexError.BadRangeKind.LineNumberStart_GreaterThan_LineNumberEnd; } else if (start.lineNumber < 0) { - maybeKind = LexError.BadRangeKind.LineNumberStart_LessThan_Zero; + kind = LexError.BadRangeKind.LineNumberStart_LessThan_Zero; } else if (start.lineNumber >= numLines) { - maybeKind = LexError.BadRangeKind.LineNumberStart_GreaterThan_NumLines; + kind = LexError.BadRangeKind.LineNumberStart_GreaterThan_NumLines; } else if (end.lineNumber >= numLines) { - maybeKind = LexError.BadRangeKind.LineNumberEnd_GreaterThan_NumLines; + kind = LexError.BadRangeKind.LineNumberEnd_GreaterThan_NumLines; } - if (maybeKind !== undefined) { - const kind: LexError.BadRangeKind = maybeKind; - + if (kind !== undefined) { return new LexError.BadRangeError(range, kind, state.locale); } @@ -1302,13 +1319,13 @@ function testBadRangeError(state: State, range: Range): LexError.BadRangeError | const lineEnd: TLine = lines[rangeEnd.lineNumber]; if (rangeStart.lineCodeUnit > lineStart.text.length) { - maybeKind = LexError.BadRangeKind.LineCodeUnitStart_GreaterThan_LineLength; + kind = LexError.BadRangeKind.LineCodeUnitStart_GreaterThan_LineLength; } else if (rangeEnd.lineCodeUnit > lineEnd.text.length) { - maybeKind = LexError.BadRangeKind.LineCodeUnitEnd_GreaterThan_LineLength; + kind = LexError.BadRangeKind.LineCodeUnitEnd_GreaterThan_LineLength; } - if (maybeKind !== undefined) { - return new LexError.BadRangeError(range, maybeKind, state.locale); + if (kind !== undefined) { + return new LexError.BadRangeError(range, kind, state.locale); } return undefined; diff --git a/src/powerquery-parser/lexer/lexerSnapshot.ts b/src/powerquery-parser/lexer/lexerSnapshot.ts index a25bd73f..9a35959a 100644 --- a/src/powerquery-parser/lexer/lexerSnapshot.ts +++ b/src/powerquery-parser/lexer/lexerSnapshot.ts @@ -91,12 +91,12 @@ function createSnapshot(state: Lexer.State): LexerSnapshot { const flatTokens: ReadonlyArray = flattenedLines.flatLineTokens; const numFlatTokens: number = flatTokens.length; const text: string = flattenedLines.text; - const maybeCancellationToken: ICancellationToken | undefined = state.maybeCancellationToken; + const cancellationToken: ICancellationToken | undefined = state.cancellationToken; let flatIndex: number = 0; while (flatIndex < numFlatTokens) { - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const flatToken: FlatLineToken = flatTokens[flatIndex]; @@ -114,7 +114,7 @@ function createSnapshot(state: Lexer.State): LexerSnapshot { flattenedLines, flatToken, state.locale, - maybeCancellationToken, + cancellationToken, ); comments.push(concatenatedTokenRead.comment); @@ -127,7 +127,7 @@ function createSnapshot(state: Lexer.State): LexerSnapshot { flattenedLines, flatToken, state.locale, - maybeCancellationToken, + cancellationToken, ); tokens.push(concatenatedTokenRead.token); @@ -140,7 +140,7 @@ function createSnapshot(state: Lexer.State): LexerSnapshot { flattenedLines, flatToken, state.locale, - maybeCancellationToken, + cancellationToken, ); tokens.push(concatenatedTokenRead.token); @@ -198,29 +198,28 @@ function readMultilineComment( flattenedLines: FlattenedLines, tokenStart: FlatLineToken, locale: string, - maybeCancellationToken: ICancellationToken | undefined, + cancellationToken: ICancellationToken | undefined, ): ConcatenatedCommentRead { const collection: FlatLineCollection = collectWhileContent( flattenedLines.flatLineTokens, tokenStart, Token.LineTokenKind.MultilineCommentContent, - maybeCancellationToken, + cancellationToken, ); - const maybeTokenEnd: FlatLineToken | undefined = collection.maybeTokenEnd; + const tokenEnd: FlatLineToken | undefined = collection.tokenEnd; - if (!maybeTokenEnd) { + if (!tokenEnd) { throw new LexError.UnterminatedMultilineTokenError( locale, LexerSnapshot.graphemePositionStartFrom(flattenedLines.text, flattenedLines.lineTerminators, tokenStart), LexError.UnterminatedMultilineTokenKind.MultilineComment, ); - } else if (maybeTokenEnd.kind !== Token.LineTokenKind.MultilineCommentEnd) { - const details: { foundTokenEnd: FlatLineToken | undefined } = { foundTokenEnd: maybeTokenEnd }; + } else if (tokenEnd.kind !== Token.LineTokenKind.MultilineCommentEnd) { + const details: { foundTokenEnd: FlatLineToken | undefined } = { foundTokenEnd: tokenEnd }; const message: string = ErrorMessageNoEndToken; throw new CommonError.InvariantError(message, details); } else { - const tokenEnd: FlatLineToken = maybeTokenEnd; const positionStart: Token.TokenPosition = tokenStart.positionStart; const positionEnd: Token.TokenPosition = tokenEnd.positionEnd; @@ -241,29 +240,28 @@ function readQuotedIdentifier( flattenedLines: FlattenedLines, tokenStart: FlatLineToken, locale: string, - maybeCancellationToken: ICancellationToken | undefined, + cancellationToken: ICancellationToken | undefined, ): ConcatenatedTokenRead { const collection: FlatLineCollection = collectWhileContent( flattenedLines.flatLineTokens, tokenStart, Token.LineTokenKind.QuotedIdentifierContent, - maybeCancellationToken, + cancellationToken, ); - const maybeTokenEnd: FlatLineToken | undefined = collection.maybeTokenEnd; + const tokenEnd: FlatLineToken | undefined = collection.tokenEnd; - if (!maybeTokenEnd) { + if (!tokenEnd) { throw new LexError.UnterminatedMultilineTokenError( locale, LexerSnapshot.graphemePositionStartFrom(flattenedLines.text, flattenedLines.lineTerminators, tokenStart), LexError.UnterminatedMultilineTokenKind.QuotedIdentifier, ); - } else if (maybeTokenEnd.kind !== Token.LineTokenKind.QuotedIdentifierEnd) { - const details: { foundTokenEnd: FlatLineToken } = { foundTokenEnd: maybeTokenEnd }; + } else if (tokenEnd.kind !== Token.LineTokenKind.QuotedIdentifierEnd) { + const details: { foundTokenEnd: FlatLineToken } = { foundTokenEnd: tokenEnd }; const message: string = ErrorMessageNoEndToken; throw new CommonError.InvariantError(message, details); } else { - const tokenEnd: FlatLineToken = maybeTokenEnd; const positionStart: Token.TokenPosition = tokenStart.positionStart; const positionEnd: Token.TokenPosition = tokenEnd.positionEnd; @@ -283,29 +281,28 @@ function readTextLiteral( flattenedLines: FlattenedLines, tokenStart: FlatLineToken, locale: string, - maybeCancellationToken: ICancellationToken | undefined, + cancellationToken: ICancellationToken | undefined, ): ConcatenatedTokenRead { const collection: FlatLineCollection = collectWhileContent( flattenedLines.flatLineTokens, tokenStart, Token.LineTokenKind.TextLiteralContent, - maybeCancellationToken, + cancellationToken, ); - const maybeTokenEnd: FlatLineToken | undefined = collection.maybeTokenEnd; + const tokenEnd: FlatLineToken | undefined = collection.tokenEnd; - if (!maybeTokenEnd) { + if (!tokenEnd) { throw new LexError.UnterminatedMultilineTokenError( locale, LexerSnapshot.graphemePositionStartFrom(flattenedLines.text, flattenedLines.lineTerminators, tokenStart), LexError.UnterminatedMultilineTokenKind.Text, ); - } else if (maybeTokenEnd.kind !== Token.LineTokenKind.TextLiteralEnd) { - const details: { foundTokenEnd: FlatLineToken } = { foundTokenEnd: maybeTokenEnd }; + } else if (tokenEnd.kind !== Token.LineTokenKind.TextLiteralEnd) { + const details: { foundTokenEnd: FlatLineToken } = { foundTokenEnd: tokenEnd }; const message: string = ErrorMessageNoEndToken; throw new CommonError.InvariantError(message, details); } else { - const tokenEnd: FlatLineToken = maybeTokenEnd; const positionStart: Token.TokenPosition = tokenStart.positionStart; const positionEnd: Token.TokenPosition = tokenEnd.positionEnd; @@ -325,7 +322,7 @@ function collectWhileContent( flatTokens: ReadonlyArray, tokenStart: FlatLineToken, contentKind: KindVariant, - maybeCancellationToken: ICancellationToken | undefined, + cancellationToken: ICancellationToken | undefined, ): FlatLineCollection { const collectedTokens: FlatLineToken[] = []; const numTokens: number = flatTokens.length; @@ -333,7 +330,7 @@ function collectWhileContent( let flatIndex: number = tokenStart.flatIndex + 1; while (flatIndex < numTokens) { - maybeCancellationToken?.throwIfCancelled(); + cancellationToken?.throwIfCancelled(); const token: FlatLineToken = flatTokens[flatIndex]; @@ -348,7 +345,7 @@ function collectWhileContent( return { tokenStart, collectedTokens, - maybeTokenEnd: flatTokens[flatIndex], + tokenEnd: flatTokens[flatIndex], }; } @@ -431,7 +428,7 @@ interface ConcatenatedTokenRead { interface FlatLineCollection { readonly tokenStart: FlatLineToken; readonly collectedTokens: ReadonlyArray; - readonly maybeTokenEnd: FlatLineToken | undefined; + readonly tokenEnd: FlatLineToken | undefined; } interface LineTerminator { diff --git a/src/powerquery-parser/localization/localization.ts b/src/powerquery-parser/localization/localization.ts index 0f96416e..05645576 100644 --- a/src/powerquery-parser/localization/localization.ts +++ b/src/powerquery-parser/localization/localization.ts @@ -14,7 +14,7 @@ interface ILocalization { readonly error_common_invariantError: ( templates: ILocalizationTemplates, reason: string, - maybeJsonifyableDetails: object | undefined, + jsonDetails: object | undefined, ) => string; readonly error_common_unknown: (templates: ILocalizationTemplates, message: string) => string; readonly error_lex_badLineNumber: (templates: ILocalizationTemplates, kind: LexError.BadLineNumberKind) => string; @@ -36,7 +36,7 @@ interface ILocalization { readonly error_parse_expectAnyTokenKind: ( templates: ILocalizationTemplates, expectedAnyTokenKinds: ReadonlyArray, - maybeFoundToken: TokenWithColumnNumber | undefined, + foundToken: TokenWithColumnNumber | undefined, ) => string; readonly error_parse_expectCommaOrKind: ( templates: ILocalizationTemplates, @@ -44,12 +44,12 @@ interface ILocalization { ) => string; readonly error_parse_expectGeneralizedIdentifier: ( templates: ILocalizationTemplates, - maybeFoundToken: TokenWithColumnNumber | undefined, + foundToken: TokenWithColumnNumber | undefined, ) => string; readonly error_parse_expectTokenKind: ( templates: ILocalizationTemplates, expectedTokenKind: Token.TokenKind, - maybeFoundToken: TokenWithColumnNumber | undefined, + foundToken: TokenWithColumnNumber | undefined, ) => string; readonly error_parse_invalidCatchFunction: (templates: ILocalizationTemplates) => string; readonly error_parse_invalidPrimitiveType: (templates: ILocalizationTemplates, token: Token.Token) => string; @@ -199,14 +199,14 @@ export const Localization: ILocalization = { error_common_invariantError: ( templates: ILocalizationTemplates, invariantBroken: string, - maybeJsonifyableDetails: object | undefined, + jsonDetails: object | undefined, ) => { - if (maybeJsonifyableDetails !== undefined) { + if (jsonDetails !== undefined) { return StringUtils.assertGetFormatted( templates.error_common_invariantError_1_details, new Map([ ["invariantBroken", invariantBroken], - ["details", JSON.stringify(maybeJsonifyableDetails, undefined, 4)], + ["details", JSON.stringify(jsonDetails, undefined, 4)], ]), ); } else { @@ -328,17 +328,17 @@ export const Localization: ILocalization = { error_parse_expectAnyTokenKind: ( templates: ILocalizationTemplates, expectedAnyTokenKinds: ReadonlyArray, - maybeFoundToken: TokenWithColumnNumber | undefined, + foundToken: TokenWithColumnNumber | undefined, ) => { const localizedExpectedAnyTokenKinds: string = expectedAnyTokenKinds .map((tokenKind: Token.TokenKind) => localizeTokenKind(templates, tokenKind)) .join(", "); - if (maybeFoundToken !== undefined) { + if (foundToken !== undefined) { return StringUtils.assertGetFormatted( templates.error_parse_expectAnyTokenKind_1_other, new Map([ - ["foundTokenKind", localizeTokenKind(templates, maybeFoundToken.token.kind)], + ["foundTokenKind", localizeTokenKind(templates, foundToken.token.kind)], ["expectedAnyTokenKinds", localizedExpectedAnyTokenKinds], ]), ); @@ -361,9 +361,9 @@ export const Localization: ILocalization = { error_parse_expectGeneralizedIdentifier: ( templates: ILocalizationTemplates, - maybeFoundToken: TokenWithColumnNumber | undefined, + foundToken: TokenWithColumnNumber | undefined, ) => { - if (maybeFoundToken !== undefined) { + if (foundToken !== undefined) { return templates.error_parse_expectGeneralizedIdentifier_1_other; } else { return templates.error_parse_expectGeneralizedIdentifier_2_endOfStream; @@ -373,16 +373,16 @@ export const Localization: ILocalization = { error_parse_expectTokenKind: ( templates: ILocalizationTemplates, expectedTokenKind: Token.TokenKind, - maybeFoundToken: TokenWithColumnNumber | undefined, + foundToken: TokenWithColumnNumber | undefined, ) => { const localizedExpectedTokenKind: string = localizeTokenKind(templates, expectedTokenKind); - if (maybeFoundToken !== undefined) { + if (foundToken !== undefined) { return StringUtils.assertGetFormatted( templates.error_parse_expectTokenKind_1_other, new Map([ ["expectedTokenKind", localizedExpectedTokenKind], - ["foundTokenKind", localizeTokenKind(templates, maybeFoundToken.token.kind)], + ["foundTokenKind", localizeTokenKind(templates, foundToken.token.kind)], ]), ); } else { diff --git a/src/powerquery-parser/parser/context/context.ts b/src/powerquery-parser/parser/context/context.ts index a313a1bd..b7aa66dd 100644 --- a/src/powerquery-parser/parser/context/context.ts +++ b/src/powerquery-parser/parser/context/context.ts @@ -17,7 +17,7 @@ import { NodeIdMap } from ".."; // For each sub-Ast.TNode that begins evaluation another Context is created and linked as a child of the original. // This means if a Ast.TNode has N attributes of type Ast.TNode, then the Ast.TNode is fully evaluated there should be N // child contexts created belonging under the original Context. -// Once the Ast.TNode evaluation is complete the result is saved on the Context under its maybeAstNode attribute. +// Once the Ast.TNode evaluation is complete the result is saved on the Context under its astNode attribute. // // Back to the scenario listed above, where the user has entered `{1,}`, you could examine the context state to find: // An incomplete ListExpression context with 3 children @@ -27,7 +27,7 @@ import { NodeIdMap } from ".."; export interface State { readonly nodeIdMapCollection: NodeIdMap.Collection; - maybeRoot: Node | undefined; + root: Node | undefined; idCounter: number; leafIds: Set; } @@ -36,11 +36,11 @@ export interface Node { readonly id: number; readonly kind: T["kind"]; readonly tokenIndexStart: number; - readonly maybeTokenStart: Token.Token | undefined; + readonly tokenStart: Token.Token | undefined; // Incremented for each child context created with the Node as its parent, // and decremented for each child context deleted. attributeCounter: number; - maybeAttributeIndex: number | undefined; + attributeIndex: number | undefined; isClosed: boolean; } diff --git a/src/powerquery-parser/parser/context/contextUtils.ts b/src/powerquery-parser/parser/context/contextUtils.ts index b916823b..864c8908 100644 --- a/src/powerquery-parser/parser/context/contextUtils.ts +++ b/src/powerquery-parser/parser/context/contextUtils.ts @@ -26,23 +26,22 @@ export function createState(): ParseContext.State { childIdsById: new Map(), contextNodeById: new Map(), leafIds: new Set(), - maybeRightMostLeaf: undefined, + rightMostLeaf: undefined, idsByNodeKind: new Map(), parentIdById: new Map(), }, - maybeRoot: undefined, + root: undefined, idCounter: 0, leafIds: new Set(), }; } export function copyState(state: ParseContext.State): ParseContext.State { - const maybeRoot: ParseContext.TNode | undefined = - state.maybeRoot !== undefined ? { ...state.maybeRoot } : undefined; + const root: ParseContext.TNode | undefined = state.root !== undefined ? { ...state.root } : undefined; return { ...state, - maybeRoot, + root, nodeIdMapCollection: NodeIdMapUtils.copy(state.nodeIdMapCollection), }; } @@ -71,27 +70,25 @@ export function startContext( state: ParseContext.State, nodeKind: Ast.NodeKind, tokenIndexStart: number, - maybeTokenStart: Token.Token | undefined, - maybeParentNode: ParseContext.TNode | undefined, + tokenStart: Token.Token | undefined, + parentNode: ParseContext.TNode | undefined, ): ParseContext.Node { const nodeIdMapCollection: NodeIdMap.Collection = state.nodeIdMapCollection; - let maybeAttributeIndex: number | undefined; + let attributeIndex: number | undefined; const nodeId: number = nextId(state); // If a parent context Node exists, update the parent/child mapping attributes and attributeCounter. - if (maybeParentNode) { + if (parentNode) { const childIdsById: NodeIdMap.ChildIdsById = nodeIdMapCollection.childIdsById; - const parentNode: ParseContext.TNode = maybeParentNode; const parentId: number = parentNode.id; - maybeAttributeIndex = nextAttributeIndex(parentNode); + attributeIndex = nextAttributeIndex(parentNode); nodeIdMapCollection.parentIdById.set(nodeId, parentId); - const maybeExistingChildren: ReadonlyArray | undefined = childIdsById.get(parentId); + const existingChildren: ReadonlyArray | undefined = childIdsById.get(parentId); - if (maybeExistingChildren) { - const existingChildren: ReadonlyArray = maybeExistingChildren; + if (existingChildren) { childIdsById.set(parentId, [...existingChildren, nodeId]); } else { childIdsById.set(parentId, [nodeId]); @@ -102,23 +99,23 @@ export function startContext( id: nodeId, kind: nodeKind, tokenIndexStart, - maybeTokenStart, + tokenStart, attributeCounter: 0, isClosed: false, - maybeAttributeIndex, + attributeIndex, }; nodeIdMapCollection.contextNodeById.set(nodeId, contextNode); - if (state.maybeRoot === undefined) { - state.maybeRoot = contextNode; + if (state.root === undefined) { + state.root = contextNode; } const idsByNodeKind: NodeIdMap.IdsByNodeKind = nodeIdMapCollection.idsByNodeKind; - const maybeIdsForSpecificNodeKind: Set | undefined = idsByNodeKind.get(nodeKind); + const idsForSpecificNodeKind: Set | undefined = idsByNodeKind.get(nodeKind); - if (maybeIdsForSpecificNodeKind) { - maybeIdsForSpecificNodeKind.add(nodeId); + if (idsForSpecificNodeKind) { + idsForSpecificNodeKind.add(nodeId); } else { idsByNodeKind.set(nodeKind, new Set([nodeId])); } @@ -134,7 +131,7 @@ export function endContext( ): ParseContext.TNode | undefined { const nodeIdMapCollection: NodeIdMap.Collection = state.nodeIdMapCollection; - if (state.maybeRoot?.id === astNode.id) { + if (state.root?.id === astNode.id) { Assert.isTrue( state.nodeIdMapCollection.contextNodeById.size === 1, "failed to endContext on the root node as at least one other context node exists", @@ -154,10 +151,10 @@ export function endContext( } // Ending a context should return the context's parent node (if one exists). - const maybeParentId: number | undefined = nodeIdMapCollection.parentIdById.get(contextNode.id); + const parentId: number | undefined = nodeIdMapCollection.parentIdById.get(contextNode.id); - const maybeParentNode: ParseContext.TNode | undefined = - maybeParentId !== undefined ? nodeIdMapCollection.contextNodeById.get(maybeParentId) : undefined; + const parentNode: ParseContext.TNode | undefined = + parentId !== undefined ? nodeIdMapCollection.contextNodeById.get(parentId) : undefined; // Move nodeId from contextNodeMap to astNodeMap. MapUtils.assertDelete( @@ -169,18 +166,18 @@ export function endContext( nodeIdMapCollection.astNodeById.set(astNode.id, astNode); - // Update maybeRightMostLeaf when applicable + // Update rightMostLeaf when applicable if (astNode.isLeaf) { if ( - nodeIdMapCollection.maybeRightMostLeaf === undefined || - nodeIdMapCollection.maybeRightMostLeaf.tokenRange.tokenIndexStart < astNode.tokenRange.tokenIndexStart + nodeIdMapCollection.rightMostLeaf === undefined || + nodeIdMapCollection.rightMostLeaf.tokenRange.tokenIndexStart < astNode.tokenRange.tokenIndexStart ) { const unsafeNodeIdMapCollection: TypeScriptUtils.StripReadonly = nodeIdMapCollection; - unsafeNodeIdMapCollection.maybeRightMostLeaf = astNode; + unsafeNodeIdMapCollection.rightMostLeaf = astNode; } } - return maybeParentNode; + return parentNode; } export function deleteAst(state: ParseContext.State, nodeId: number, parentWillBeDeleted: boolean): void { @@ -208,26 +205,24 @@ export function deleteAst(state: ParseContext.State, nodeId: number, parentWillB ); } - const maybeParentId: number | undefined = parentIdById.get(nodeId); - const maybeChildIds: ReadonlyArray | undefined = childIdsById.get(nodeId); + const parentId: number | undefined = parentIdById.get(nodeId); + const childIds: ReadonlyArray | undefined = childIdsById.get(nodeId); // Not a leaf node. Assert.isUndefined( - maybeChildIds, + childIds, `failed to deleteAst as the given nodeId has one ore more children which must be deleted first`, { nodeId, - childIds: maybeChildIds, + childIds, }, ); // Is a leaf node, not root node. // Delete the node from the list of children under the node's parent. - if (maybeParentId) { - const parentId: number = maybeParentId; - + if (parentId) { Assert.isFalse( - astNodeById.has(maybeParentId) && !parentWillBeDeleted, + astNodeById.has(parentId) && !parentWillBeDeleted, `parent is an Ast node not marked for deletion`, { parentId, @@ -255,52 +250,46 @@ export function deleteContext(state: ParseContext.State, nodeId: number): ParseC const leafIds: Set = nodeIdMapCollection.leafIds; const parentIdById: NodeIdMap.ParentIdById = nodeIdMapCollection.parentIdById; - const maybeContextNode: ParseContext.TNode | undefined = contextNodeById.get(nodeId); + const contextNode: ParseContext.TNode | undefined = contextNodeById.get(nodeId); - if (maybeContextNode === undefined) { + if (contextNode === undefined) { throw new CommonError.InvariantError(`failed to deleteContext as the given nodeId isn't a valid context node`, { nodeId, }); } - const contextNode: ParseContext.TNode = maybeContextNode; - - const maybeParentId: number | undefined = parentIdById.get(nodeId); - const maybeChildIds: ReadonlyArray | undefined = childIdsById.get(nodeId); + const parentId: number | undefined = parentIdById.get(nodeId); + const childIds: ReadonlyArray | undefined = childIdsById.get(nodeId); // Not a leaf node. - if (maybeChildIds !== undefined) { - const childIds: ReadonlyArray = maybeChildIds; + if (childIds !== undefined) { ArrayUtils.assertNonZeroLength(childIds); const childId: number = childIds[0]; // Not a leaf node, is the Root node. // Promote the child to the root if it's a Context node. - if (maybeParentId === undefined) { + if (parentId === undefined) { parentIdById.delete(childId); - const maybeChildContext: ParseContext.TNode | undefined = contextNodeById.get(childId); + const childContext: ParseContext.TNode | undefined = contextNodeById.get(childId); - if (maybeChildContext) { - const childContext: ParseContext.TNode = maybeChildContext; - state.maybeRoot = childContext; + if (childContext) { + state.root = childContext; } } // Not a leaf node, not the Root node. // Replace the node from the list of children under the node's parent using the node's child else { - const parentId: number = maybeParentId; removeOrReplaceChildId(nodeIdMapCollection, parentId, nodeId, childId); } // The child Node inherits the attributeIndex. const childXorNode: TXorNode = NodeIdMapUtils.assertGetXor(state.nodeIdMapCollection, childId); const mutableChildXorNode: TypeScriptUtils.StripReadonly = childXorNode.node; - mutableChildXorNode.maybeAttributeIndex = contextNode.maybeAttributeIndex; + mutableChildXorNode.attributeIndex = contextNode.attributeIndex; } // Is a leaf node, not root node. // Delete the node from the list of children under the node's parent. - else if (maybeParentId) { - const parentId: number = maybeParentId; + else if (parentId) { removeOrReplaceChildId(nodeIdMapCollection, parentId, nodeId, undefined); } // Else is root node, is leaf node. @@ -314,7 +303,7 @@ export function deleteContext(state: ParseContext.State, nodeId: number): ParseC leafIds.delete(nodeId); // Return the node's parent if it exits - return maybeParentId !== undefined ? NodeIdMapUtils.assertUnboxContext(contextNodeById, maybeParentId) : undefined; + return parentId !== undefined ? NodeIdMapUtils.assertUnboxContext(contextNodeById, parentId) : undefined; } function deleteFromKindMap(nodeIdMapCollection: NodeIdMap.Collection, nodeId: number): void { @@ -343,7 +332,7 @@ function removeOrReplaceChildId( nodeIdMapCollection: NodeIdMap.Collection, parentId: number, childId: number, - maybeReplacementId: number | undefined, + replacementId: number | undefined, ): void { const childIdsById: NodeIdMap.ChildIdsById = nodeIdMapCollection.childIdsById; const childIds: ReadonlyArray = NodeIdMapIterator.assertIterChildIds(childIdsById, parentId); @@ -361,33 +350,31 @@ function removeOrReplaceChildId( const beforeChildId: ReadonlyArray = childIds.slice(0, replacementIndex); const afterChildId: ReadonlyArray = childIds.slice(replacementIndex + 1); - let maybeNewChildIds: ReadonlyArray | undefined; + let newChildIds: ReadonlyArray | undefined; - if (maybeReplacementId) { - const replacementId: number = maybeReplacementId; + if (replacementId) { nodeIdMapCollection.parentIdById.set(replacementId, parentId); if (childIds.length === 1) { - maybeNewChildIds = [replacementId]; + newChildIds = [replacementId]; } else { - maybeNewChildIds = [...beforeChildId, replacementId, ...afterChildId]; + newChildIds = [...beforeChildId, replacementId, ...afterChildId]; } } else if (childIds.length === 1) { - maybeNewChildIds = undefined; + newChildIds = undefined; } else { - maybeNewChildIds = [...beforeChildId, ...afterChildId]; + newChildIds = [...beforeChildId, ...afterChildId]; } - if (maybeNewChildIds) { - const newChildIds: ReadonlyArray = maybeNewChildIds; + if (newChildIds) { childIdsById.set(parentId, newChildIds); } else { childIdsById.delete(parentId); } - const maybeParent: ParseContext.TNode | undefined = nodeIdMapCollection.contextNodeById.get(parentId); + const parent: ParseContext.TNode | undefined = nodeIdMapCollection.contextNodeById.get(parentId); - if (maybeParent !== undefined && maybeReplacementId === undefined) { - maybeParent.attributeCounter -= 1; + if (parent !== undefined && replacementId === undefined) { + parent.attributeCounter -= 1; } } diff --git a/src/powerquery-parser/parser/disambiguation/disambiguationUtils.ts b/src/powerquery-parser/parser/disambiguation/disambiguationUtils.ts index dc7a050b..7ed6be40 100644 --- a/src/powerquery-parser/parser/disambiguation/disambiguationUtils.ts +++ b/src/powerquery-parser/parser/disambiguation/disambiguationUtils.ts @@ -23,33 +23,33 @@ import { ParseError } from ".."; export async function readAmbiguous( state: ParseState, parser: Parser, - parseFns: ReadonlyArray<(state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => Promise>, - maybeCorrelationId: number | undefined, + parseCallbacks: ReadonlyArray<(state: ParseState, parser: Parser, correlationId: number | undefined) => Promise>, + correlationId: number | undefined, ): Promise> { const trace: Trace = state.traceManager.entry( DisambiguationTraceConstant.Disambiguation, readAmbiguous.name, - maybeCorrelationId, + correlationId, { - [TraceConstant.Length]: parseFns.length, + [TraceConstant.Length]: parseCallbacks.length, }, ); - ArrayUtils.assertNonZeroLength(parseFns, "requires at least one parse function"); + ArrayUtils.assertNonZeroLength(parseCallbacks, "requires at least one parse function"); - let maybeBestMatch: AmbiguousParse | undefined = undefined; + let bestMatch: AmbiguousParse | undefined = undefined; - for (const parseFn of parseFns) { + for (const parseCallback of parseCallbacks) { // eslint-disable-next-line no-await-in-loop const variantState: ParseState = await parser.copyState(state); - let maybeNode: T | undefined; + let node: T | undefined; let variantResult: Result; try { // eslint-disable-next-line no-await-in-loop - maybeNode = await parseFn(variantState, parser, trace.id); - variantResult = ResultUtils.boxOk(maybeNode); + node = await parseCallback(variantState, parser, trace.id); + variantResult = ResultUtils.boxOk(node); } catch (error) { if (!ParseError.isTInnerParseError(error)) { throw error; @@ -63,13 +63,13 @@ export async function readAmbiguous( result: variantResult, }; - maybeBestMatch = bestAmbiguousParseMatch(maybeBestMatch, candiate); + bestMatch = bestAmbiguousParseMatch(bestMatch, candiate); } - Assert.isDefined(maybeBestMatch); + Assert.isDefined(bestMatch); trace.exit(); - return maybeBestMatch; + return bestMatch; } // Peeks at the token stream and either performs an explicit read or an ambiguous read. @@ -77,27 +77,21 @@ export async function readAmbiguousBracket( state: ParseState, parser: Parser, allowedVariants: ReadonlyArray, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( DisambiguationTraceConstant.Disambiguation, readAmbiguousBracket.name, - maybeCorrelationId, + correlationId, ); // We might be able to peek at tokens to disambiguate what bracketed expression is next. - const maybeDisambiguation: BracketDisambiguation | undefined = maybeDisambiguateBracket( - state, - allowedVariants, - trace.id, - ); + const disambiguation: BracketDisambiguation | undefined = disambiguateBracket(state, allowedVariants, trace.id); // Peeking gave us a concrete answer as to what's next. let ambiguousBracket: TAmbiguousBracketNode; - if (maybeDisambiguation !== undefined) { - const disambiguation: BracketDisambiguation = maybeDisambiguation; - + if (disambiguation !== undefined) { switch (disambiguation) { case BracketDisambiguation.FieldProjection: ambiguousBracket = await parser.readFieldProjection(state, parser, trace.id); @@ -141,16 +135,16 @@ export async function readAmbiguousBracket( export async function readAmbiguousParenthesis( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( DisambiguationTraceConstant.Disambiguation, readAmbiguousParenthesis.name, - maybeCorrelationId, + correlationId, ); // We might be able to peek at tokens to disambiguate what parenthesized expression is next. - const maybeDisambiguation: ParenthesisDisambiguation | undefined = await maybeDisambiguateParenthesis( + const disambiguation: ParenthesisDisambiguation | undefined = await disambiguateParenthesis( state, parser, trace.id, @@ -159,9 +153,7 @@ export async function readAmbiguousParenthesis( // Peeking gave us a concrete answer as to what's next. let ambiguousParenthesis: TAmbiguousParenthesisNode; - if (maybeDisambiguation !== undefined) { - const disambiguation: ParenthesisDisambiguation = maybeDisambiguation; - + if (disambiguation !== undefined) { switch (disambiguation) { case ParenthesisDisambiguation.FunctionExpression: ambiguousParenthesis = await parser.readFunctionExpression(state, parser, trace.id); @@ -200,15 +192,15 @@ export async function readAmbiguousParenthesis( } // Peeks at tokens which might give a concrete disambiguation. -export async function maybeDisambiguateParenthesis( +export async function disambiguateParenthesis( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( DisambiguationTraceConstant.Disambiguation, - maybeDisambiguateParenthesis.name, - maybeCorrelationId, + disambiguateParenthesis.name, + correlationId, ); const initialTokenIndex: number = state.tokenIndex; @@ -226,7 +218,7 @@ export async function maybeDisambiguateParenthesis( nestedDepth -= 1; } - let maybeDisambiguation: ParenthesisDisambiguation | undefined = undefined; + let disambiguation: ParenthesisDisambiguation | undefined = undefined; if (nestedDepth === 0) { // '(x as number) as number' could either be either case, @@ -251,24 +243,24 @@ export async function maybeDisambiguateParenthesis( } if (ParseStateUtils.isOnTokenKind(state, Token.TokenKind.FatArrow)) { - maybeDisambiguation = ParenthesisDisambiguation.FunctionExpression; + disambiguation = ParenthesisDisambiguation.FunctionExpression; } else { - maybeDisambiguation = ParenthesisDisambiguation.ParenthesizedExpression; + disambiguation = ParenthesisDisambiguation.ParenthesizedExpression; } // eslint-disable-next-line no-await-in-loop await parser.restoreCheckpoint(state, checkpoint); } else if (ParseStateUtils.isTokenKind(state, Token.TokenKind.FatArrow, offsetTokenIndex + 1)) { - maybeDisambiguation = ParenthesisDisambiguation.FunctionExpression; + disambiguation = ParenthesisDisambiguation.FunctionExpression; } else { - maybeDisambiguation = ParenthesisDisambiguation.ParenthesizedExpression; + disambiguation = ParenthesisDisambiguation.ParenthesizedExpression; } } - if (maybeDisambiguation) { - trace.exit({ [TraceConstant.Result]: maybeDisambiguation }); + if (disambiguation) { + trace.exit({ [TraceConstant.Result]: disambiguation }); - return maybeDisambiguation; + return disambiguation; } offsetTokenIndex += 1; @@ -279,27 +271,25 @@ export async function maybeDisambiguateParenthesis( return undefined; } -export function maybeDisambiguateBracket( +export function disambiguateBracket( state: ParseState, allowedVariants: ReadonlyArray, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): BracketDisambiguation | undefined { const trace: Trace = state.traceManager.entry( DisambiguationTraceConstant.Disambiguation, - maybeDisambiguateBracket.name, - maybeCorrelationId, + disambiguateBracket.name, + correlationId, ); let offsetTokenIndex: number = state.tokenIndex + 1; const tokens: ReadonlyArray = state.lexerSnapshot.tokens; - const maybeOffsetToken: Token.Token | undefined = tokens[offsetTokenIndex]; + const offsetToken: Token.Token | undefined = tokens[offsetTokenIndex]; - if (maybeOffsetToken === undefined) { + if (offsetToken === undefined) { return undefined; } - const offsetToken: Token.Token = maybeOffsetToken; - let offsetTokenKind: Token.TokenKind = offsetToken.kind; let result: BracketDisambiguation | undefined; @@ -342,12 +332,12 @@ async function thoroughReadAmbiguousBracket( state: ParseState, parser: Parser, allowedVariants: ReadonlyArray, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( DisambiguationTraceConstant.Disambiguation, readAmbiguousBracket.name, - maybeCorrelationId, + correlationId, ); const ambiguousBracket: TAmbiguousBracketNode = await thoroughReadAmbiguous( @@ -368,26 +358,26 @@ async function thoroughReadAmbiguousBracket( async function thoroughReadAmbiguousParenthesis( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { return await thoroughReadAmbiguous( state, parser, [parser.readFunctionExpression, readParenthesizedExpressionOrBinOpExpression], - maybeCorrelationId, + correlationId, ); } async function thoroughReadAmbiguous( state: ParseState, parser: Parser, - parseFns: ReadonlyArray<(state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => Promise>, - maybeCorrelationId: number | undefined, + parseFns: ReadonlyArray<(state: ParseState, parser: Parser, correlationId: number | undefined) => Promise>, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( DisambiguationTraceConstant.Disambiguation, thoroughReadAmbiguous.name, - maybeCorrelationId, + correlationId, { [TraceConstant.Length]: parseFns.length, }, @@ -422,7 +412,7 @@ function bracketDisambiguationParseFunctions( parser: Parser, allowedVariants: ReadonlyArray, ): ReadonlyArray< - (state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => Promise + (state: ParseState, parser: Parser, correlationId: number | undefined) => Promise > { return allowedVariants.map((bracketDisambiguation: BracketDisambiguation) => { switch (bracketDisambiguation) { @@ -447,12 +437,12 @@ function bracketDisambiguationParseFunctions( async function readParenthesizedExpressionOrBinOpExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( DisambiguationTraceConstant.Disambiguation, readParenthesizedExpressionOrBinOpExpression.name, - maybeCorrelationId, + correlationId, ); const node: Ast.TNode = await parser.readLogicalExpression(state, parser, trace.id); @@ -482,27 +472,27 @@ function unsafeMoveTo(state: ParseState, tokenIndex: number): void { state.tokenIndex = tokenIndex; if (tokenIndex < tokens.length) { - state.maybeCurrentToken = tokens[tokenIndex]; - state.maybeCurrentTokenKind = state.maybeCurrentToken.kind; + state.currentToken = tokens[tokenIndex]; + state.currentTokenKind = state.currentToken.kind; } else { - state.maybeCurrentToken = undefined; - state.maybeCurrentTokenKind = undefined; + state.currentToken = undefined; + state.currentTokenKind = undefined; } } function bestAmbiguousParseMatch( - maybeBest: AmbiguousParse | undefined, + best: AmbiguousParse | undefined, candidate: AmbiguousParse, ): AmbiguousParse { - if (maybeBest === undefined || maybeBest.parseState.tokenIndex < candidate.parseState.tokenIndex) { + if (best === undefined || best.parseState.tokenIndex < candidate.parseState.tokenIndex) { return candidate; } else if ( - maybeBest.parseState.tokenIndex === candidate.parseState.tokenIndex && - ResultUtils.isError(maybeBest.result) && + best.parseState.tokenIndex === candidate.parseState.tokenIndex && + ResultUtils.isError(best.result) && ResultUtils.isOk(candidate.result) ) { return candidate; } else { - return maybeBest; + return best; } } diff --git a/src/powerquery-parser/parser/error.ts b/src/powerquery-parser/parser/error.ts index 38eb8889..a009f665 100644 --- a/src/powerquery-parser/parser/error.ts +++ b/src/powerquery-parser/parser/error.ts @@ -40,7 +40,7 @@ export class ParseError extends Error { export class ExpectedCsvContinuationError extends Error { constructor( readonly kind: CsvContinuationKind, - readonly maybeFoundToken: TokenWithColumnNumber | undefined, + readonly foundToken: TokenWithColumnNumber | undefined, locale: string, ) { super(Localization.error_parse_csvContinuation(LocalizationUtils.getLocalizationTemplates(locale), kind)); @@ -51,14 +51,14 @@ export class ExpectedCsvContinuationError extends Error { export class ExpectedAnyTokenKindError extends Error { constructor( readonly expectedAnyTokenKinds: ReadonlyArray, - readonly maybeFoundToken: TokenWithColumnNumber | undefined, + readonly foundToken: TokenWithColumnNumber | undefined, locale: string, ) { super( Localization.error_parse_expectAnyTokenKind( LocalizationUtils.getLocalizationTemplates(locale), expectedAnyTokenKinds, - maybeFoundToken, + foundToken, ), ); @@ -69,7 +69,7 @@ export class ExpectedAnyTokenKindError extends Error { export class ExpectedClosingTokenKind extends Error { constructor( readonly expectedTokenKind: Token.TokenKind, - readonly maybeFoundToken: TokenWithColumnNumber | undefined, + readonly foundToken: TokenWithColumnNumber | undefined, locale: string, ) { super( @@ -86,14 +86,14 @@ export class ExpectedClosingTokenKind extends Error { export class ExpectedTokenKindError extends Error { constructor( readonly expectedTokenKind: Token.TokenKind, - readonly maybeFoundToken: TokenWithColumnNumber | undefined, + readonly foundToken: TokenWithColumnNumber | undefined, locale: string, ) { super( Localization.error_parse_expectTokenKind( LocalizationUtils.getLocalizationTemplates(locale), expectedTokenKind, - maybeFoundToken, + foundToken, ), ); @@ -102,11 +102,11 @@ export class ExpectedTokenKindError extends Error { } export class ExpectedGeneralizedIdentifierError extends Error { - constructor(readonly maybeFoundToken: TokenWithColumnNumber | undefined, locale: string) { + constructor(readonly foundToken: TokenWithColumnNumber | undefined, locale: string) { super( Localization.error_parse_expectGeneralizedIdentifier( LocalizationUtils.getLocalizationTemplates(locale), - maybeFoundToken, + foundToken, ), ); @@ -207,7 +207,7 @@ export function isTInnerParseError(x: any): x is TInnerParseError { ); } -export function maybeTokenFrom(error: TInnerParseError): Token.Token | undefined { +export function tokenFrom(error: TInnerParseError): Token.Token | undefined { if ( error instanceof ExpectedAnyTokenKindError || error instanceof ExpectedClosingTokenKind || @@ -215,7 +215,7 @@ export function maybeTokenFrom(error: TInnerParseError): Token.Token | undefined error instanceof ExpectedGeneralizedIdentifierError || error instanceof ExpectedTokenKindError ) { - return error.maybeFoundToken?.token; + return error.foundToken?.token; } else if (error instanceof InvalidPrimitiveTypeError) { return error.token; } else if (error instanceof RequiredParameterAfterOptionalParameterError) { diff --git a/src/powerquery-parser/parser/nodeIdMap/ancestryUtils.ts b/src/powerquery-parser/parser/nodeIdMap/ancestryUtils.ts index 92c7ba7f..b8a8c726 100644 --- a/src/powerquery-parser/parser/nodeIdMap/ancestryUtils.ts +++ b/src/powerquery-parser/parser/nodeIdMap/ancestryUtils.ts @@ -10,12 +10,11 @@ import { Ast } from "../../language"; export function assertGetAncestry(nodeIdMapCollection: NodeIdMap.Collection, nodeId: number): ReadonlyArray { const ancestryIds: number[] = [nodeId]; - let maybeParentId: number | undefined = nodeIdMapCollection.parentIdById.get(nodeId); + let parentId: number | undefined = nodeIdMapCollection.parentIdById.get(nodeId); - while (maybeParentId) { - const parentId: number = maybeParentId; + while (parentId) { ancestryIds.push(parentId); - maybeParentId = nodeIdMapCollection.parentIdById.get(parentId); + parentId = nodeIdMapCollection.parentIdById.get(parentId); } return NodeIdMapIterator.assertIterXor(nodeIdMapCollection, ancestryIds); @@ -107,7 +106,7 @@ export function assertGetNthPreviousXorChecked( } export function assertGetNthXor(ancestry: ReadonlyArray, ancestryIndex: number): TXorNode { - return Assert.asDefined(maybeNthXor(ancestry, ancestryIndex), "ancestryIndex is out of bounds", { + return Assert.asDefined(nthXor(ancestry, ancestryIndex), "ancestryIndex is out of bounds", { ancestryLength: ancestry.length, ancestryIndex, }); @@ -121,107 +120,107 @@ export function assertGetNthXorChecked( return assertGetNthXorChecked(ancestry, ancestryIndex, expectedNodeKinds); } -export function maybeNthXor(ancestry: ReadonlyArray, ancestryIndex: number): TXorNode | undefined { +export function nthXor(ancestry: ReadonlyArray, ancestryIndex: number): TXorNode | undefined { return ancestry[ancestryIndex]; } -export function maybeNthXorChecked( +export function nthXorChecked( ancestry: ReadonlyArray, ancestryIndex: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeNthXor(ancestry, ancestryIndex); + const xorNode: TXorNode | undefined = nthXor(ancestry, ancestryIndex); - return maybeXorNode && XorNodeUtils.isNodeKind(maybeXorNode, expectedNodeKinds) ? maybeXorNode : undefined; + return xorNode && XorNodeUtils.isNodeKind(xorNode, expectedNodeKinds) ? xorNode : undefined; } -export function maybeNextXor(ancestry: ReadonlyArray, ancestryIndex: number): TXorNode | undefined { - return maybeNthXor(ancestry, ancestryIndex + 1); +export function nextXor(ancestry: ReadonlyArray, ancestryIndex: number): TXorNode | undefined { + return nthXor(ancestry, ancestryIndex + 1); } -export function maybeNextXorChecked( +export function nextXorChecked( ancestry: ReadonlyArray, ancestryIndex: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode | undefined { - return maybeNthXorChecked(ancestry, ancestryIndex + 1, expectedNodeKinds); + return nthXorChecked(ancestry, ancestryIndex + 1, expectedNodeKinds); } -export function maybePreviousXor(ancestry: ReadonlyArray, ancestryIndex: number): TXorNode | undefined { - return maybeNthXor(ancestry, ancestryIndex - 1); +export function previousXor(ancestry: ReadonlyArray, ancestryIndex: number): TXorNode | undefined { + return nthXor(ancestry, ancestryIndex - 1); } -export function maybePreviousXorChecked( +export function previousXorChecked( ancestry: ReadonlyArray, ancestryIndex: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode | undefined { - return maybeNthXorChecked(ancestry, ancestryIndex - 1, expectedNodeKinds); + return nthXorChecked(ancestry, ancestryIndex - 1, expectedNodeKinds); } -export function maybeNthNextXor( +export function nthNextXor( ancestry: ReadonlyArray, ancestryIndex: number, offset: number = 1, ): TXorNode | undefined { - return maybeNthXor(ancestry, ancestryIndex + offset); + return nthXor(ancestry, ancestryIndex + offset); } -export function maybeNthNextXorChecked( +export function nthNextXorChecked( ancestry: ReadonlyArray, ancestryIndex: number, offset: number = 1, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode | undefined { - return maybeNthXorChecked(ancestry, ancestryIndex + offset, expectedNodeKinds); + return nthXorChecked(ancestry, ancestryIndex + offset, expectedNodeKinds); } -export function maybeNthPreviousXor( +export function nthPreviousXor( ancestry: ReadonlyArray, ancestryIndex: number, offset: number = 1, ): TXorNode | undefined { - return maybeNthXor(ancestry, ancestryIndex - offset); + return nthXor(ancestry, ancestryIndex - offset); } -export function maybeNthPreviousXorChecked( +export function nthPreviousXorChecked( ancestry: ReadonlyArray, ancestryIndex: number, offset: number = 1, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode | undefined { - return maybeNthXorChecked(ancestry, ancestryIndex - offset, expectedNodeKinds); + return nthXorChecked(ancestry, ancestryIndex - offset, expectedNodeKinds); } -export function maybeFirstXorOfNodeKind( +export function findXorOfNodeKind( ancestry: ReadonlyArray, nodeKind: T["kind"], ): XorNode | undefined { - const maybeNode: TXorNode | undefined = ancestry.find((xorNode: TXorNode) => xorNode.node.kind === nodeKind); + const node: TXorNode | undefined = ancestry.find((xorNode: TXorNode) => xorNode.node.kind === nodeKind); - if (maybeNode === undefined || !XorNodeUtils.isNodeKind(maybeNode, nodeKind)) { + if (node === undefined || !XorNodeUtils.isNodeKind(node, nodeKind)) { return undefined; } - return maybeNode; + return node; } -export function maybeFirstIndexOfNodeKind( +export function findIndexOfNodeKind( ancestry: ReadonlyArray, nodeKind: T["kind"], ): number | undefined { - const maybeIndex: number = ancestry.findIndex((xorNode: TXorNode) => XorNodeUtils.isNodeKind(xorNode, nodeKind)); + const index: number = ancestry.findIndex((xorNode: TXorNode) => XorNodeUtils.isNodeKind(xorNode, nodeKind)); - return maybeIndex !== -1 ? maybeIndex : undefined; + return index !== -1 ? index : undefined; } -export function maybeFirstXorAndIndexOfNodeKind( +export function findXorAndIndexOfNodeKind( ancestry: ReadonlyArray, nodeKind: T["kind"], ): [XorNode, number] | undefined { - const maybeIndex: number | undefined = maybeFirstIndexOfNodeKind(ancestry, nodeKind); + const index: number | undefined = findIndexOfNodeKind(ancestry, nodeKind); - return maybeIndex !== undefined - ? [XorNodeUtils.assertAsNodeKind(Assert.asDefined(ancestry[maybeIndex]), nodeKind), maybeIndex] + return index !== undefined + ? [XorNodeUtils.assertAsNodeKind(Assert.asDefined(ancestry[index]), nodeKind), index] : undefined; } diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMap.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMap.ts index ffcd900f..d7651edf 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMap.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMap.ts @@ -26,7 +26,7 @@ export interface Collection { readonly parentIdById: ParentIdById; // The right most Ast in the parse context, which under normal circumstances is the most recently parsed node. - readonly maybeRightMostLeaf: Ast.TNode | undefined; + readonly rightMostLeaf: Ast.TNode | undefined; } type NumberMap = Map; diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapIterator.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapIterator.ts index c12cbc3f..93e3de84 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapIterator.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapIterator.ts @@ -5,7 +5,7 @@ import { Assert, MapUtils } from "../../common"; import { Ast, Constant, TextUtils } from "../../language"; import { NodeIdMap, NodeIdMapUtils, TXorNode, XorNodeKind, XorNodeUtils } from "."; import { IConstant } from "../../language/ast/ast"; -import { maybeUnboxIdentifier } from "./nodeIdMapUtils"; +import { unboxIdentifier } from "./nodeIdMapUtils"; import { XorNode } from "./xorNode"; export type TKeyValuePair = FieldSpecificationKeyValuePair | LetKeyValuePair | RecordKeyValuePair | SectionKeyValuePair; @@ -16,12 +16,12 @@ export interface IKeyValuePair { readonly pairKind: PairKind.FieldSpecification; - readonly maybeOptional: IConstant | undefined; + readonly optional: IConstant | undefined; } export interface LetKeyValuePair extends IKeyValuePair { @@ -72,13 +72,13 @@ export function assertIterChildrenXor( nodeIdMapCollection: NodeIdMap.Collection, parentId: number, ): ReadonlyArray { - const maybeChildIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(parentId); + const childIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(parentId); - if (maybeChildIds === undefined) { + if (childIds === undefined) { return []; } - return assertIterXor(nodeIdMapCollection, maybeChildIds); + return assertIterXor(nodeIdMapCollection, childIds); } // Given a list of nodeIds, assert the existence of then return them as XorNodes. @@ -90,39 +90,39 @@ export function assertIterXor( } // If any exist, returns all Ast nodes under the given node. -export function maybeIterChildrenAst( +export function iterChildrenAst( nodeIdMapCollection: NodeIdMap.Collection, parentId: number, ): ReadonlyArray | undefined { - const maybeChildIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(parentId); + const childIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(parentId); - if (maybeChildIds === undefined) { + if (childIds === undefined) { return undefined; } const astNodeById: NodeIdMap.AstNodeById = nodeIdMapCollection.astNodeById; - return maybeChildIds.map((childId: number) => NodeIdMapUtils.assertUnboxAst(astNodeById, childId)); + return childIds.map((childId: number) => NodeIdMapUtils.assertUnboxAst(astNodeById, childId)); } -export function maybeNextSiblingXor(nodeIdMapCollection: NodeIdMap.Collection, nodeId: number): TXorNode | undefined { - return maybeNthSiblingXor(nodeIdMapCollection, nodeId, 1); +export function nextSiblingXor(nodeIdMapCollection: NodeIdMap.Collection, nodeId: number): TXorNode | undefined { + return nthSiblingXor(nodeIdMapCollection, nodeId, 1); } // Grabs the parent for the given nodeId, then returns the nth child of the parent where that child's attributeIndex is -// (givenNode.maybeAttributeIndex + offset) as an XorNode if such a child exists. -export function maybeNthSiblingXor( +// (givenNode.attributeIndex + offset) as an XorNode if such a child exists. +export function nthSiblingXor( nodeIdMapCollection: NodeIdMap.Collection, nodeId: number, offset: number, ): TXorNode | undefined { const childXorNode: TXorNode = NodeIdMapUtils.assertGetXor(nodeIdMapCollection, nodeId); - if (childXorNode.node.maybeAttributeIndex === undefined) { + if (childXorNode.node.attributeIndex === undefined) { return undefined; } - const attributeIndex: number = childXorNode.node.maybeAttributeIndex + offset; + const attributeIndex: number = childXorNode.node.attributeIndex + offset; if (attributeIndex < 0) { return undefined; @@ -135,7 +135,7 @@ export function maybeNthSiblingXor( return undefined; } - return NodeIdMapUtils.maybeXor(nodeIdMapCollection, childIds[attributeIndex]); + return NodeIdMapUtils.xor(nodeIdMapCollection, childIds[attributeIndex]); } // ------------------------------------------ @@ -164,14 +164,10 @@ export function iterArrayWrapper( break; case XorNodeKind.Context: { - const maybeChild: TXorNode | undefined = NodeIdMapUtils.maybeNthChild( - nodeIdMapCollection, - csvXorNode.node.id, - 0, - ); - - if (maybeChild !== undefined) { - partial.push(maybeChild); + const child: TXorNode | undefined = NodeIdMapUtils.nthChild(nodeIdMapCollection, csvXorNode.node.id, 0); + + if (child !== undefined) { + partial.push(child); } break; @@ -192,12 +188,12 @@ export function iterFieldProjection( ): ReadonlyArray { XorNodeUtils.assertIsNodeKind(fieldProjection, Ast.NodeKind.FieldProjection); - const maybeArrayWrapper: XorNode | undefined = NodeIdMapUtils.maybeUnboxArrayWrapper( + const arrayWrapper: XorNode | undefined = NodeIdMapUtils.unboxArrayWrapper( nodeIdMapCollection, fieldProjection.node.id, ); - return maybeArrayWrapper === undefined ? [] : iterArrayWrapper(nodeIdMapCollection, maybeArrayWrapper); + return arrayWrapper === undefined ? [] : iterArrayWrapper(nodeIdMapCollection, arrayWrapper); } // Return all FieldSelector names under the given FieldProjection. @@ -208,15 +204,15 @@ export function iterFieldProjectionNames( const result: string[] = []; for (const selector of iterFieldProjection(nodeIdMapCollection, fieldProjection)) { - const maybeIdentifier: XorNode | undefined = - NodeIdMapUtils.maybeUnboxWrappedContentChecked( + const identifier: XorNode | undefined = + NodeIdMapUtils.unboxWrappedContentChecked( nodeIdMapCollection, selector.node.id, Ast.NodeKind.GeneralizedIdentifier, ); - if (maybeIdentifier && XorNodeUtils.isAstXor(maybeIdentifier)) { - result.push(maybeIdentifier.node.literal); + if (identifier && XorNodeUtils.isAstXor(identifier)) { + result.push(identifier.node.literal); } } @@ -236,19 +232,18 @@ export function iterFunctionExpressionParameters( ); } - const maybeParameterList: XorNode | undefined = - NodeIdMapUtils.maybeNthChildChecked( - nodeIdMapCollection, - functionExpression.node.id, - 0, - Ast.NodeKind.ParameterList, - ); + const parameterList: XorNode | undefined = NodeIdMapUtils.nthChildChecked( + nodeIdMapCollection, + functionExpression.node.id, + 0, + Ast.NodeKind.ParameterList, + ); - if (maybeParameterList === undefined) { + if (parameterList === undefined) { return []; } - return iterArrayWrapperInWrappedContent(nodeIdMapCollection, maybeParameterList); + return iterArrayWrapperInWrappedContent(nodeIdMapCollection, parameterList); } export function iterFunctionExpressionParameterNames( @@ -258,13 +253,13 @@ export function iterFunctionExpressionParameterNames( const result: Ast.Identifier[] = []; for (const parameter of iterFunctionExpressionParameters(nodeIdMapCollection, functionExpression)) { - const maybeName: Ast.Identifier | undefined = maybeUnboxIdentifier(nodeIdMapCollection, parameter); + const name: Ast.Identifier | undefined = unboxIdentifier(nodeIdMapCollection, parameter); - if (maybeName === undefined) { + if (name === undefined) { break; } - result.push(maybeName); + result.push(name); } return result; @@ -292,40 +287,40 @@ export function iterFieldSpecificationList( const result: FieldSpecificationKeyValuePair[] = []; for (const fieldSpecification of iterArrayWrapperInWrappedContent(nodeIdMapCollection, fieldSpecificationList)) { - const maybeKey: Ast.GeneralizedIdentifier | undefined = NodeIdMapUtils.maybeUnboxNthChildIfAstChecked( + const key: Ast.GeneralizedIdentifier | undefined = NodeIdMapUtils.unboxNthChildIfAstChecked( nodeIdMapCollection, fieldSpecification.node.id, 1, Ast.NodeKind.GeneralizedIdentifier, ); - if (maybeKey === undefined) { + if (key === undefined) { break; } - const maybeOptional: Ast.IConstant | undefined = - NodeIdMapUtils.maybeUnboxNthChildIfAstChecked>( + const optional: Ast.IConstant | undefined = + NodeIdMapUtils.unboxNthChildIfAstChecked>( nodeIdMapCollection, fieldSpecification.node.id, 0, Ast.NodeKind.Constant, ); - const maybeValue: XorNode | undefined = - NodeIdMapUtils.maybeNthChildChecked( + const value: XorNode | undefined = + NodeIdMapUtils.nthChildChecked( nodeIdMapCollection, fieldSpecification.node.id, 2, Ast.NodeKind.FieldSpecification, ); - const keyLiteral: string = maybeKey.literal; + const keyLiteral: string = key.literal; result.push({ - key: maybeKey, + key, keyLiteral, - maybeOptional, - maybeValue, + optional, + value, normalizedKeyLiteral: TextUtils.normalizeIdentifier(keyLiteral), pairKind: PairKind.FieldSpecification, source: fieldSpecification, @@ -351,18 +346,18 @@ export function iterLetExpression( ): ReadonlyArray { XorNodeUtils.assertIsNodeKind(letExpression, Ast.NodeKind.LetExpression); - const maybeArrayWrapper: TXorNode | undefined = NodeIdMapUtils.maybeUnboxArrayWrapper( + const arrayWrapper: TXorNode | undefined = NodeIdMapUtils.unboxArrayWrapper( nodeIdMapCollection, letExpression.node.id, ); - if (maybeArrayWrapper === undefined) { + if (arrayWrapper === undefined) { return []; } return iterKeyValuePairs( nodeIdMapCollection, - maybeArrayWrapper, + arrayWrapper, PairKind.LetExpression, ); } @@ -381,18 +376,18 @@ export function iterRecord( ): ReadonlyArray { XorNodeUtils.assertIsRecord(record); - const maybeArrayWrapper: XorNode | undefined = NodeIdMapUtils.maybeUnboxArrayWrapper( + const arrayWrapper: XorNode | undefined = NodeIdMapUtils.unboxArrayWrapper( nodeIdMapCollection, record.node.id, ); - if (maybeArrayWrapper === undefined) { + if (arrayWrapper === undefined) { return []; } return iterKeyValuePairs( nodeIdMapCollection, - maybeArrayWrapper, + arrayWrapper, PairKind.Record, ); } @@ -403,19 +398,19 @@ export function iterRecordType( ): ReadonlyArray { XorNodeUtils.assertIsRecordType(recordType); - const maybeFields: XorNode | undefined = - NodeIdMapUtils.maybeNthChildChecked( + const fields: XorNode | undefined = + NodeIdMapUtils.nthChildChecked( nodeIdMapCollection, recordType.node.id, 0, Ast.NodeKind.FieldSpecificationList, ); - if (maybeFields === undefined) { + if (fields === undefined) { return []; } - return iterFieldSpecificationList(nodeIdMapCollection, maybeFields); + return iterFieldSpecificationList(nodeIdMapCollection, fields); } // Return all key-value-pair children under the given Section. @@ -435,56 +430,53 @@ export function iterSection( key: namePairedExpression.key, keyLiteral, normalizedKeyLiteral: TextUtils.normalizeIdentifier(keyLiteral), - maybeValue: XorNodeUtils.boxAst(namePairedExpression.value), + value: XorNodeUtils.boxAst(namePairedExpression.value), pairKind: PairKind.SectionMember, }; }); } - const maybeSectionMemberArrayWrapper: XorNode | undefined = - NodeIdMapUtils.maybeNthChildChecked( + const sectionMemberArrayWrapper: XorNode | undefined = + NodeIdMapUtils.nthChildChecked( nodeIdMapCollection, section.node.id, 4, Ast.NodeKind.ArrayWrapper, ); - if (maybeSectionMemberArrayWrapper === undefined) { + if (sectionMemberArrayWrapper === undefined) { return []; } - const sectionMemberArrayWrapper: TXorNode = maybeSectionMemberArrayWrapper; - const partial: SectionKeyValuePair[] = []; for (const sectionMember of assertIterChildrenXor(nodeIdMapCollection, sectionMemberArrayWrapper.node.id)) { - const maybeKeyValuePair: XorNode | undefined = - NodeIdMapUtils.maybeNthChildChecked( + const keyValuePair: XorNode | undefined = + NodeIdMapUtils.nthChildChecked( nodeIdMapCollection, sectionMember.node.id, 2, Ast.NodeKind.IdentifierPairedExpression, ); - if (maybeKeyValuePair === undefined) { + if (keyValuePair === undefined) { continue; } - const keyValuePair: TXorNode = maybeKeyValuePair; const keyValuePairNodeId: number = keyValuePair.node.id; - const maybeKey: Ast.Identifier | undefined = NodeIdMapUtils.maybeUnboxNthChildIfAstChecked( + const keyKey: Ast.Identifier | undefined = NodeIdMapUtils.unboxNthChildIfAstChecked( nodeIdMapCollection, - keyValuePairNodeId, + keyValuePair.node.id, 0, Ast.NodeKind.Identifier, ); - if (maybeKey === undefined) { + if (keyKey === undefined) { continue; } - const key: Ast.Identifier = maybeKey; + const key: Ast.Identifier = keyKey; const keyLiteral: string = key.literal; partial.push({ @@ -492,7 +484,7 @@ export function iterSection( key, keyLiteral, normalizedKeyLiteral: TextUtils.normalizeIdentifier(keyLiteral), - maybeValue: NodeIdMapUtils.maybeNthChild(nodeIdMapCollection, keyValuePairNodeId, 2), + value: NodeIdMapUtils.nthChild(nodeIdMapCollection, keyValuePairNodeId, 2), pairKind: PairKind.SectionMember, }); } @@ -507,25 +499,25 @@ function iterKeyValuePairs< const partial: KVP[] = []; for (const keyValuePair of iterArrayWrapper(nodeIdMapCollection, arrayWrapper)) { - const maybeKey: Key | undefined = NodeIdMapUtils.maybeUnboxNthChildIfAstChecked( + const key: Key | undefined = NodeIdMapUtils.unboxNthChildIfAstChecked( nodeIdMapCollection, keyValuePair.node.id, 0, [Ast.NodeKind.GeneralizedIdentifier, Ast.NodeKind.Identifier], ); - if (maybeKey === undefined) { + if (key === undefined) { break; } - const keyLiteral: string = maybeKey.literal; + const keyLiteral: string = key.literal; partial.push({ source: keyValuePair, - key: maybeKey, + key, keyLiteral, normalizedKeyLiteral: TextUtils.normalizeIdentifier(keyLiteral), - maybeValue: NodeIdMapUtils.maybeNthChild(nodeIdMapCollection, keyValuePair.node.id, 2), + value: NodeIdMapUtils.nthChild(nodeIdMapCollection, keyValuePair.node.id, 2), pairKind, } as KVP); } @@ -537,14 +529,14 @@ function iterArrayWrapperInWrappedContent( nodeIdMapCollection: NodeIdMap.Collection, xorNode: TXorNode, ): ReadonlyArray { - const maybeArrayWrapper: XorNode | undefined = NodeIdMapUtils.maybeUnboxArrayWrapper( + const arrayWrapper: XorNode | undefined = NodeIdMapUtils.unboxArrayWrapper( nodeIdMapCollection, xorNode.node.id, ); - if (maybeArrayWrapper === undefined) { + if (arrayWrapper === undefined) { return []; } - return iterArrayWrapper(nodeIdMapCollection, maybeArrayWrapper); + return iterArrayWrapper(nodeIdMapCollection, arrayWrapper); } diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/childSelectors.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/childSelectors.ts index c835409a..5331b647 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/childSelectors.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/childSelectors.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license. import { Assert, CommonError } from "../../../common"; -import { assertGetXor, maybeXor } from "./commonSelectors"; +import { assertGetXor, xor } from "./commonSelectors"; import { Ast, AstUtils } from "../../../language"; import { ChildIdsById, Collection } from "../nodeIdMap"; import { ParseContext, ParseContextUtils } from "../../context"; @@ -15,7 +15,7 @@ import { XorNodeUtils } from ".."; // * a literal operator constant `+` as the second attribute. // * a literal node `2` as the third attribute. // -// The `INode` interface has the nullable field `maybeAttributeIndex`. +// The `INode` interface has the nullable field `attributeIndex`. // A truthy value indicates it contains a parent and if so what attribute number it is under the parent. export function assertGetChildren(childIdsById: ChildIdsById, parentId: number): ReadonlyArray { @@ -24,7 +24,7 @@ export function assertGetChildren(childIdsById: ChildIdsById, parentId: number): export function assertGetNthChild(nodeIdMapCollection: Collection, parentId: number, attributeIndex: number): TXorNode { return Assert.asDefined( - maybeNthChild(nodeIdMapCollection, parentId, attributeIndex), + nthChild(nodeIdMapCollection, parentId, attributeIndex), `parentId doesn't have a child at the given index`, { parentId, attributeIndex }, ); @@ -43,15 +43,15 @@ export function assertGetNthChildChecked( } export function assertUnboxArrayWrapperAst(nodeIdMapCollection: Collection, nodeId: number): Ast.TArrayWrapper { - const maybeXorNode: XorNode | undefined = Assert.asDefined( - maybeUnboxArrayWrapper(nodeIdMapCollection, nodeId), + const xorNode: XorNode | undefined = Assert.asDefined( + unboxArrayWrapper(nodeIdMapCollection, nodeId), "failure in assertUnboxArrayWrapperAst", { nodeId }, ); - XorNodeUtils.assertIsAstXor(maybeXorNode); + XorNodeUtils.assertIsAstXor(xorNode); - return maybeXorNode.node; + return xorNode.node; } export function assertUnboxNthChildAsAst( @@ -60,7 +60,7 @@ export function assertUnboxNthChildAsAst( attributeIndex: number, ): Ast.TNode { return Assert.asDefined( - maybeUnboxNthChildIfAst(nodeIdMapCollection, parentId, attributeIndex), + unboxNthChildIfAst(nodeIdMapCollection, parentId, attributeIndex), `parentId doesn't have an Ast child at the given index`, { parentId, attributeIndex }, ); @@ -84,7 +84,7 @@ export function assertUnboxNthChildAsContext( attributeIndex: number, ): ParseContext.TNode { return Assert.asDefined( - maybeUnboxNthChildIfContext(nodeIdMapCollection, parentId, attributeIndex), + nthChildIfContext(nodeIdMapCollection, parentId, attributeIndex), `parentId doesn't have a context child at the given index`, { parentId, attributeIndex }, ); @@ -114,25 +114,23 @@ export function assertUnboxNthChildAsContextChecked( return parseContext; } -export function maybeNthChild( +export function nthChild( nodeIdMapCollection: Collection, parentId: number, attributeIndex: number, ): TXorNode | undefined { // Grab the node's childIds. - const maybeChildIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(parentId); + const childIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(parentId); - if (maybeChildIds === undefined) { + if (childIds === undefined) { return undefined; } - const childIds: ReadonlyArray = maybeChildIds; - // Iterate over the children and try to find one which matches attributeIndex. for (const childId of childIds) { const xorNode: TXorNode = assertGetXor(nodeIdMapCollection, childId); - if (xorNode.node.maybeAttributeIndex === attributeIndex) { + if (xorNode.node.attributeIndex === attributeIndex) { return xorNode; } } @@ -140,122 +138,118 @@ export function maybeNthChild( return undefined; } -export function maybeNthChildChecked( +export function nthChildChecked( nodeIdMapCollection: Collection, parentId: number, attributeIndex: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeNthChild(nodeIdMapCollection, parentId, attributeIndex); + const xorNode: TXorNode | undefined = nthChild(nodeIdMapCollection, parentId, attributeIndex); + + return xorNode && XorNodeUtils.isNodeKind(xorNode, expectedNodeKinds) ? xorNode : undefined; +} + +export function nthChildIfContext( + nodeIdMapCollection: Collection, + parentId: number, + attributeIndex: number, +): ParseContext.TNode | undefined { + const xorNode: TXorNode | undefined = nthChild(nodeIdMapCollection, parentId, attributeIndex); - return maybeXorNode && XorNodeUtils.isNodeKind(maybeXorNode, expectedNodeKinds) ? maybeXorNode : undefined; + return xorNode && XorNodeUtils.isContextXor(xorNode) ? xorNode.node : undefined; } -export function maybeUnboxArrayWrapper( +export function unboxArrayWrapper( nodeIdMapCollection: Collection, nodeId: number, ): XorNode | undefined { - return maybeNthChildChecked(nodeIdMapCollection, nodeId, 1, Ast.NodeKind.ArrayWrapper); + return nthChildChecked(nodeIdMapCollection, nodeId, 1, Ast.NodeKind.ArrayWrapper); } -export function maybeUnboxNthChildIfAst( +export function unboxNthChildIfAst( nodeIdMapCollection: Collection, parentId: number, attributeIndex: number, ): Ast.TNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeNthChild(nodeIdMapCollection, parentId, attributeIndex); + const xorNode: TXorNode | undefined = nthChild(nodeIdMapCollection, parentId, attributeIndex); - return maybeXorNode && XorNodeUtils.isAstXor(maybeXorNode) ? maybeXorNode.node : undefined; + return xorNode && XorNodeUtils.isAstXor(xorNode) ? xorNode.node : undefined; } -export function maybeUnboxNthChildIfAstChecked( +export function unboxNthChildIfAstChecked( nodeIdMapCollection: Collection, parentId: number, attributeIndex: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): T | undefined { - const maybeAstNode: Ast.TNode | undefined = maybeUnboxNthChildIfAst(nodeIdMapCollection, parentId, attributeIndex); - - return maybeAstNode && AstUtils.isNodeKind(maybeAstNode, expectedNodeKinds) ? maybeAstNode : undefined; -} - -export function maybeUnboxNthChildIfContext( - nodeIdMapCollection: Collection, - parentId: number, - attributeIndex: number, -): ParseContext.TNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeNthChild(nodeIdMapCollection, parentId, attributeIndex); + const astNode: Ast.TNode | undefined = unboxNthChildIfAst(nodeIdMapCollection, parentId, attributeIndex); - return maybeXorNode && XorNodeUtils.isContextXor(maybeXorNode) ? maybeXorNode.node : undefined; + return astNode && AstUtils.isNodeKind(astNode, expectedNodeKinds) ? astNode : undefined; } -export function maybeUnboxNthChildIfContextChecked( +export function unboxNthChildIfContextChecked( nodeIdMapCollection: Collection, parentId: number, attributeIndex: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): ParseContext.Node | undefined { - const maybeContextNode: ParseContext.TNode | undefined = maybeUnboxNthChildIfContext( + const contextNode: ParseContext.TNode | undefined = nthChildIfContext( nodeIdMapCollection, parentId, attributeIndex, ); - return maybeContextNode && ParseContextUtils.isNodeKind(maybeContextNode, expectedNodeKinds) - ? maybeContextNode - : undefined; + return contextNode && ParseContextUtils.isNodeKind(contextNode, expectedNodeKinds) ? contextNode : undefined; } -export function maybeUnboxIfAst(nodeIdMapCollection: Collection, nodeId: number): Ast.TNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeXor(nodeIdMapCollection, nodeId); +export function unboxIfAst(nodeIdMapCollection: Collection, nodeId: number): Ast.TNode | undefined { + const xorNode: TXorNode | undefined = xor(nodeIdMapCollection, nodeId); - return maybeXorNode && XorNodeUtils.isAstXor(maybeXorNode) ? maybeXorNode.node : undefined; + return xorNode && XorNodeUtils.isAstXor(xorNode) ? xorNode.node : undefined; } -export function maybeUnboxIfAstChecked( +export function unboxIfAstChecked( nodeIdMapCollection: Collection, nodeId: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): T | undefined { - const maybeXorNode: TXorNode | undefined = maybeXor(nodeIdMapCollection, nodeId); + const xorNode: TXorNode | undefined = xor(nodeIdMapCollection, nodeId); - return maybeXorNode && XorNodeUtils.isAstXorChecked(maybeXorNode, expectedNodeKinds) - ? maybeXorNode.node - : undefined; + return xorNode && XorNodeUtils.isAstXorChecked(xorNode, expectedNodeKinds) ? xorNode.node : undefined; } -export function maybeUnboxWrappedContent(nodeIdMapCollection: Collection, nodeId: number): TXorNode | undefined { - const maybeWrapperXorNode: TXorNode | undefined = maybeXor(nodeIdMapCollection, nodeId); +export function unboxWrappedContent(nodeIdMapCollection: Collection, nodeId: number): TXorNode | undefined { + const wrapperXorNode: TXorNode | undefined = xor(nodeIdMapCollection, nodeId); - if (maybeWrapperXorNode === undefined || !XorNodeUtils.isTWrapped(maybeWrapperXorNode)) { + if (wrapperXorNode === undefined || !XorNodeUtils.isTWrapped(wrapperXorNode)) { return undefined; } - return maybeNthChild(nodeIdMapCollection, nodeId, 1); + return nthChild(nodeIdMapCollection, nodeId, 1); } -export function maybeUnboxWrappedContentChecked( +export function unboxWrappedContentChecked( nodeIdMapCollection: Collection, nodeId: number, expectedNodeKinds: ReadonlyArray | C["kind"], ): XorNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeUnboxWrappedContent(nodeIdMapCollection, nodeId); + const xorNode: TXorNode | undefined = unboxWrappedContent(nodeIdMapCollection, nodeId); - return maybeXorNode && XorNodeUtils.isNodeKind(maybeXorNode, expectedNodeKinds) ? maybeXorNode : undefined; + return xorNode && XorNodeUtils.isNodeKind(xorNode, expectedNodeKinds) ? xorNode : undefined; } -export function maybeUnboxWrappedContentIfAst(nodeIdMapCollection: Collection, nodeId: number): Ast.TNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeUnboxWrappedContent(nodeIdMapCollection, nodeId); +export function unboxWrappedContentIfAst(nodeIdMapCollection: Collection, nodeId: number): Ast.TNode | undefined { + const xorNode: TXorNode | undefined = unboxWrappedContent(nodeIdMapCollection, nodeId); - return maybeXorNode && XorNodeUtils.isAstXor(maybeXorNode) ? maybeXorNode.node : undefined; + return xorNode && XorNodeUtils.isAstXor(xorNode) ? xorNode.node : undefined; } -export function maybeUnboxWrappedContentIfAstChecked( +export function unboxWrappedContentIfAstChecked( nodeIdMapCollection: Collection, nodeId: number, expectedNodeKinds: ReadonlyArray | C["kind"], ): C | undefined { - const maybeAstNode: Ast.TNode | undefined = maybeUnboxWrappedContentIfAst(nodeIdMapCollection, nodeId); + const astNode: Ast.TNode | undefined = unboxWrappedContentIfAst(nodeIdMapCollection, nodeId); - return maybeAstNode && AstUtils.isNodeKind(maybeAstNode, expectedNodeKinds) ? maybeAstNode : undefined; + return astNode && AstUtils.isNodeKind(astNode, expectedNodeKinds) ? astNode : undefined; } diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/commonSelectors.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/commonSelectors.ts index 690695cf..d2b2bd02 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/commonSelectors.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/commonSelectors.ts @@ -9,7 +9,7 @@ import { TXorNode, XorNode } from "../xorNode"; import { XorNodeUtils } from ".."; export function assertGetXor(nodeIdMapCollection: Collection, nodeId: number): TXorNode { - return Assert.asDefined(maybeXor(nodeIdMapCollection, nodeId), undefined, { nodeId }); + return Assert.asDefined(xor(nodeIdMapCollection, nodeId), undefined, { nodeId }); } export function assertGetXorChecked( @@ -17,7 +17,7 @@ export function assertGetXorChecked( nodeId: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode { - return Assert.asDefined(maybeXorChecked(nodeIdMapCollection, nodeId, expectedNodeKinds), undefined, { + return Assert.asDefined(xorChecked(nodeIdMapCollection, nodeId, expectedNodeKinds), undefined, { nodeId, expectedNodeKinds, }); @@ -61,28 +61,28 @@ export function assertUnboxContextChecked( return contextNode; } -export function maybeXor(nodeIdMapCollection: Collection, nodeId: number): TXorNode | undefined { - const maybeAstNode: Ast.TNode | undefined = nodeIdMapCollection.astNodeById.get(nodeId); +export function xor(nodeIdMapCollection: Collection, nodeId: number): TXorNode | undefined { + const astNode: Ast.TNode | undefined = nodeIdMapCollection.astNodeById.get(nodeId); - if (maybeAstNode !== undefined) { - return XorNodeUtils.boxAst(maybeAstNode); + if (astNode !== undefined) { + return XorNodeUtils.boxAst(astNode); } - const maybeContextNode: ParseContext.TNode | undefined = nodeIdMapCollection.contextNodeById.get(nodeId); + const contextNode: ParseContext.TNode | undefined = nodeIdMapCollection.contextNodeById.get(nodeId); - if (maybeContextNode !== undefined) { - return XorNodeUtils.boxContext(maybeContextNode); + if (contextNode !== undefined) { + return XorNodeUtils.boxContext(contextNode); } return undefined; } -export function maybeXorChecked( +export function xorChecked( nodeIdMapCollection: Collection, nodeId: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeXor(nodeIdMapCollection, nodeId); + const xorNode: TXorNode | undefined = xor(nodeIdMapCollection, nodeId); - return maybeXorNode && XorNodeUtils.isNodeKind(maybeXorNode, expectedNodeKinds) ? maybeXorNode : undefined; + return xorNode && XorNodeUtils.isNodeKind(xorNode, expectedNodeKinds) ? xorNode : undefined; } diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/idUtils.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/idUtils.ts index fa5bacbb..3843ec25 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/idUtils.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/idUtils.ts @@ -18,9 +18,9 @@ export function recalculateIds( nodeIdMapCollection: NodeIdMap.Collection, nodeStart: TXorNode, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Map { - const trace: Trace = traceManager.entry(IdUtilsTraceConstant.IdUtils, recalculateIds.name, maybeCorrelationId); + const trace: Trace = traceManager.entry(IdUtilsTraceConstant.IdUtils, recalculateIds.name, correlationId); const visitedXorNodes: TXorNode[] = []; const nodeIds: number[] = []; @@ -60,9 +60,9 @@ export function updateNodeIds( nodeIdMapCollection: Collection, newIdByOldId: Map, traceManager: TraceManager, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): void { - const trace: Trace = traceManager.entry(IdUtilsTraceConstant.IdUtils, updateNodeIds.name, maybeCorrelationId, { + const trace: Trace = traceManager.entry(IdUtilsTraceConstant.IdUtils, updateNodeIds.name, correlationId, { [IdUtilsTraceConstant.MapSize]: newIdByOldId.size, }); @@ -95,7 +95,7 @@ const enum IdUtilsTraceConstant { MapSize = "MapSize", } -type CollectionDelta = Omit; +type CollectionDelta = Omit; function createDelta( nodeIdMapCollection: Collection, @@ -129,10 +129,10 @@ function createDelta( // If the node has children and the change delta hasn't been calculated, // then calculate the children for the change delta. - const maybeChildIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(oldId); + const childIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(oldId); - if (maybeChildIds !== undefined && !partialCollection.childIdsById.has(newId)) { - const newChildIds: ReadonlyArray = maybeChildIds.map( + if (childIds !== undefined && !partialCollection.childIdsById.has(newId)) { + const newChildIds: ReadonlyArray = childIds.map( (childId: number) => newIdByOldId.get(childId) ?? childId, ); @@ -141,10 +141,10 @@ function createDelta( // If the node has a parent, // then calculate the updated parent for the change delta. - const maybeOldParentId: number | undefined = nodeIdMapCollection.parentIdById.get(oldId); + const oldParentId: number | undefined = nodeIdMapCollection.parentIdById.get(oldId); - if (maybeOldParentId !== undefined) { - const newParentId: number = newIdByOldId.get(maybeOldParentId) ?? maybeOldParentId; + if (oldParentId !== undefined) { + const newParentId: number = newIdByOldId.get(oldParentId) ?? oldParentId; partialCollection.parentIdById.set(newId, newParentId); // If the parent has children and the change delta hasn't been calculated for the parent's children, @@ -152,7 +152,7 @@ function createDelta( if (!partialCollection.childIdsById.has(newParentId)) { const oldChildIdsOfParent: ReadonlyArray = MapUtils.assertGet( nodeIdMapCollection.childIdsById, - maybeOldParentId, + oldParentId, ); const newChildIdsOfParent: ReadonlyArray = oldChildIdsOfParent.map( @@ -207,10 +207,10 @@ function applyDelta( } // If the nodeId had any children then update the links. - const maybeChildIds: ReadonlyArray | undefined = delta.childIdsById.get(newId); + const childIds: ReadonlyArray | undefined = delta.childIdsById.get(newId); - if (maybeChildIds !== undefined) { - nodeIdMapCollection.childIdsById.set(newId, maybeChildIds); + if (childIds !== undefined) { + nodeIdMapCollection.childIdsById.set(newId, childIds); if (!delta.parentIdById.has(oldId)) { MapUtils.assertDelete(nodeIdMapCollection.childIdsById, oldId); @@ -251,10 +251,10 @@ function applyDelta( idsForSpecificNodeKind.delete(oldId); } - const maybeParentId: number | undefined = delta.parentIdById.get(newId); + const parentId: number | undefined = delta.parentIdById.get(newId); - if (maybeParentId !== undefined) { - nodeIdMapCollection.parentIdById.set(newId, maybeParentId); + if (parentId !== undefined) { + nodeIdMapCollection.parentIdById.set(newId, parentId); if (!delta.parentIdById.has(oldId)) { MapUtils.assertDelete(nodeIdMapCollection.parentIdById, oldId); diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/leafSelectors.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/leafSelectors.ts index d4081827..60771a3a 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/leafSelectors.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/leafSelectors.ts @@ -5,77 +5,71 @@ import { AstNodeById, Collection } from "../nodeIdMap"; import { NodeIdMap, XorNodeUtils } from ".."; import { Assert } from "../../../common"; import { Ast } from "../../../language"; -import { maybeXor } from "./commonSelectors"; import { TXorNode } from "../xorNode"; +import { xor } from "./commonSelectors"; export function assertUnboxLeftMostLeaf(nodeIdMapCollection: Collection, nodeId: number): Ast.TNode { return XorNodeUtils.assertUnboxAst( - Assert.asDefined( - maybeLeftMostXor(nodeIdMapCollection, nodeId), - `nodeId does not exist in nodeIdMapCollection`, - { nodeId }, - ), + Assert.asDefined(leftMostXor(nodeIdMapCollection, nodeId), `nodeId does not exist in nodeIdMapCollection`, { + nodeId, + }), ); } export function assertGetLeftMostXor(nodeIdMapCollection: Collection, nodeId: number): TXorNode { - return Assert.asDefined( - maybeLeftMostXor(nodeIdMapCollection, nodeId), - `nodeId does not exist in nodeIdMapCollection`, - { nodeId }, - ); + return Assert.asDefined(leftMostXor(nodeIdMapCollection, nodeId), `nodeId does not exist in nodeIdMapCollection`, { + nodeId, + }); } // Travels down the left most node under the given nodeId by way of the children collection. -export function maybeLeftMostXor(nodeIdMapCollection: Collection, nodeId: number): TXorNode | undefined { - const currentNode: TXorNode | undefined = maybeXor(nodeIdMapCollection, nodeId); +export function leftMostXor(nodeIdMapCollection: Collection, nodeId: number): TXorNode | undefined { + const currentNode: TXorNode | undefined = xor(nodeIdMapCollection, nodeId); if (currentNode === undefined) { return undefined; } let currentNodeId: number = currentNode.node.id; - let maybeChildIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(currentNodeId); + let childIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(currentNodeId); - while (maybeChildIds?.length) { - currentNodeId = maybeChildIds[0]; - maybeChildIds = nodeIdMapCollection.childIdsById.get(currentNodeId); + while (childIds?.length) { + currentNodeId = childIds[0]; + childIds = nodeIdMapCollection.childIdsById.get(currentNodeId); } - return maybeXor(nodeIdMapCollection, currentNodeId); + return xor(nodeIdMapCollection, currentNodeId); } -// Same as maybeLeftMostXor but also checks if it's an Ast node. -export function maybeLeftMostLeaf(nodeIdMapCollection: NodeIdMap.Collection, nodeId: number): Ast.TNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeLeftMostXor(nodeIdMapCollection, nodeId); +// Same as leftMostXor but also checks if it's an Ast node. +export function leftMostLeaf(nodeIdMapCollection: NodeIdMap.Collection, nodeId: number): Ast.TNode | undefined { + const xorNode: TXorNode | undefined = leftMostXor(nodeIdMapCollection, nodeId); - return maybeXorNode && XorNodeUtils.isAstXor(maybeXorNode) ? maybeXorNode.node : undefined; + return xorNode && XorNodeUtils.isAstXor(xorNode) ? xorNode.node : undefined; } // There are a few assumed invariants about children: // * Children were read left to right. // * Children were placed in childIdsById in the order they were read. // * Therefore the right-most child is the most recently read which also appears last in the document. -export function maybeRightMostLeaf( +export function rightMostLeaf( nodeIdMapCollection: Collection, nodeId: number, - maybeCondition: ((node: Ast.TNode) => boolean) | undefined = undefined, + predicate: ((node: Ast.TNode) => boolean) | undefined = undefined, ): Promise { const astNodeById: AstNodeById = nodeIdMapCollection.astNodeById; let nodeIdsToExplore: number[] = [nodeId]; - let maybeRightMost: Ast.TNode | undefined; + let rightMost: Ast.TNode | undefined; while (nodeIdsToExplore.length) { const nodeId: number = Assert.asDefined(nodeIdsToExplore.pop()); - const maybeAstNode: Ast.TNode | undefined = astNodeById.get(nodeId); + const astNode: Ast.TNode | undefined = astNodeById.get(nodeId); let addChildren: boolean = false; // Check if Ast.TNode or ParserContext.Node - if (maybeAstNode !== undefined) { - const astNode: Ast.TNode = maybeAstNode; - - if (maybeCondition && !maybeCondition(astNode)) { + if (astNode !== undefined) { + if (predicate && !predicate(astNode)) { continue; } @@ -83,22 +77,22 @@ export function maybeRightMostLeaf( // As it's a leaf there are no children to add. if (astNode.isLeaf) { // Is the first leaf encountered. - if (maybeRightMost === undefined) { - maybeRightMost = astNode; + if (rightMost === undefined) { + rightMost = astNode; } // Compare current leaf node to the existing record. - else if (astNode.tokenRange.tokenIndexStart > maybeRightMost.tokenRange.tokenIndexStart) { - maybeRightMost = astNode; + else if (astNode.tokenRange.tokenIndexStart > rightMost.tokenRange.tokenIndexStart) { + rightMost = astNode; } } // Is not a leaf, no previous record exists. // Add all children to the queue. - else if (maybeRightMost === undefined) { + else if (rightMost === undefined) { addChildren = true; } // Is not a leaf, previous record exists. // Check if we can cull the branch, otherwise add all children to the queue. - else if (astNode.tokenRange.tokenIndexEnd > maybeRightMost.tokenRange.tokenIndexStart) { + else if (astNode.tokenRange.tokenIndexEnd > rightMost.tokenRange.tokenIndexStart) { addChildren = true; } } @@ -109,11 +103,10 @@ export function maybeRightMostLeaf( } if (addChildren) { - const maybeChildIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(nodeId); + const childIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(nodeId); - if (maybeChildIds !== undefined) { + if (childIds !== undefined) { // Add the child ids in reversed order to prioritize visiting the right most nodes first. - const childIds: ReadonlyArray = maybeChildIds; const reversedChildIds: number[] = [...childIds]; reversedChildIds.reverse(); nodeIdsToExplore = [...reversedChildIds, ...nodeIdsToExplore]; @@ -121,13 +114,13 @@ export function maybeRightMostLeaf( } } - return Promise.resolve(maybeRightMost); + return Promise.resolve(rightMost); } -export function maybeRightMostLeafWhere( +export function rightMostLeafWhere( nodeIdMapCollection: Collection, nodeId: number, - maybeCondition: ((node: Ast.TNode) => boolean) | undefined, + predicateFn: ((node: Ast.TNode) => boolean) | undefined, ): Promise { - return maybeRightMostLeaf(nodeIdMapCollection, nodeId, maybeCondition); + return rightMostLeaf(nodeIdMapCollection, nodeId, predicateFn); } diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/nodeIdMapUtils.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/nodeIdMapUtils.ts index ed872d9e..205048ce 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/nodeIdMapUtils.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/nodeIdMapUtils.ts @@ -5,8 +5,8 @@ import { Ast, Token } from "../../../language"; import { Collection, IdsByNodeKind } from "../nodeIdMap"; import { TXorNode, XorNodeKind, XorNodeTokenRange } from "../xorNode"; import { Assert } from "../../../common"; -import { maybeRightMostLeaf } from "./leafSelectors"; import { ParseContext } from "../../context"; +import { rightMostLeaf } from "./leafSelectors"; export function copy(nodeIdMapCollection: Collection): Collection { const contextNodeById: Map = new Map( @@ -28,17 +28,17 @@ export function copy(nodeIdMapCollection: Collection): Collection { contextNodeById, leafIds: new Set(nodeIdMapCollection.leafIds), idsByNodeKind, - maybeRightMostLeaf: nodeIdMapCollection.maybeRightMostLeaf, + rightMostLeaf: nodeIdMapCollection.rightMostLeaf, parentIdById: new Map(nodeIdMapCollection.parentIdById), }; } // Checks if the given nodeId contains at least one parsed token. export function hasParsedToken(nodeIdMapCollection: Collection, nodeId: number): boolean { - let maybeChildIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(nodeId); + let childIds: ReadonlyArray | undefined = nodeIdMapCollection.childIdsById.get(nodeId); - while (maybeChildIds !== undefined) { - const numChildren: number = maybeChildIds.length; + while (childIds !== undefined) { + const numChildren: number = childIds.length; // No children means no nothing was parsed under this node. if (numChildren === 0) { @@ -46,7 +46,7 @@ export function hasParsedToken(nodeIdMapCollection: Collection, nodeId: number): } // There might be a child under here. else if (numChildren === 1) { - const childId: number = maybeChildIds[0]; + const childId: number = childIds[0]; // We know it's an Ast Node, therefore something was parsed. if (nodeIdMapCollection.astNodeById.has(childId)) { @@ -54,7 +54,7 @@ export function hasParsedToken(nodeIdMapCollection: Collection, nodeId: number): } // There still might be a child under here. Recurse down to the grandchildren. else { - maybeChildIds = nodeIdMapCollection.childIdsById.get(childId); + childIds = nodeIdMapCollection.childIdsById.get(childId); } } // Handles the 'else if (numChildren > 2)' branch. @@ -87,15 +87,11 @@ export async function xorNodeTokenRange( const contextNode: ParseContext.TNode = xorNode.node; let tokenIndexEnd: number; - const maybeRightMostChild: Ast.TNode | undefined = await maybeRightMostLeaf( - nodeIdMapCollection, - xorNode.node.id, - ); + const rightMostChild: Ast.TNode | undefined = await rightMostLeaf(nodeIdMapCollection, xorNode.node.id); - if (maybeRightMostChild === undefined) { + if (rightMostChild === undefined) { tokenIndexEnd = contextNode.tokenIndexStart; } else { - const rightMostChild: Ast.TNode = maybeRightMostChild; tokenIndexEnd = rightMostChild.tokenRange.tokenIndexEnd; } diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/parentSelectors.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/parentSelectors.ts index a42bc241..70bf0e12 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/parentSelectors.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/parentSelectors.ts @@ -11,7 +11,7 @@ import { XorNodeUtils } from ".."; export function assertUnboxParentAst(nodeIdMapCollection: Collection, nodeId: number): Ast.TNode { return Assert.asDefined( - maybeParentAst(nodeIdMapCollection, nodeId), + parentAst(nodeIdMapCollection, nodeId), "couldn't find the expected parent Ast for nodeId", { nodeId }, ); @@ -30,7 +30,7 @@ export function assertUnboxParentAstChecked( export function assertUnboxParentContext(nodeIdMapCollection: Collection, nodeId: number): ParseContext.TNode { return Assert.asDefined( - maybeParentContext(nodeIdMapCollection, nodeId), + parentContext(nodeIdMapCollection, nodeId), "couldn't find the expected parent context for nodeId", { nodeId }, ); @@ -48,9 +48,9 @@ export function assertUnboxParentContextChecked( } export function assertGetParentXor(nodeIdMapCollection: Collection, nodeId: number): TXorNode { - const maybeNode: TXorNode | undefined = maybeParentXor(nodeIdMapCollection, nodeId); + const node: TXorNode | undefined = parentXor(nodeIdMapCollection, nodeId); - return Assert.asDefined(maybeNode, `nodeId doesn't have a parent`, { nodeId, maybeNodeKind: maybeNode?.node.kind }); + return Assert.asDefined(node, `nodeId doesn't have a parent`, { nodeId, nodeKind: node?.node.kind }); } export function assertGetParentXorChecked( @@ -58,68 +58,66 @@ export function assertGetParentXorChecked( nodeId: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode { - const maybeXorNode: TXorNode = assertGetParentXor(nodeIdMapCollection, nodeId); - XorNodeUtils.assertIsNodeKind(maybeXorNode, expectedNodeKinds); + const xorNode: TXorNode = assertGetParentXor(nodeIdMapCollection, nodeId); + XorNodeUtils.assertIsNodeKind(xorNode, expectedNodeKinds); - return maybeXorNode; + return xorNode; } -export function maybeParentAst(nodeIdMapCollection: Collection, childId: number): Ast.TNode | undefined { - const maybeParentId: number | undefined = nodeIdMapCollection.parentIdById.get(childId); +export function parentAst(nodeIdMapCollection: Collection, childId: number): Ast.TNode | undefined { + const parentId: number | undefined = nodeIdMapCollection.parentIdById.get(childId); - return maybeParentId !== undefined ? nodeIdMapCollection.astNodeById.get(maybeParentId) : undefined; + return parentId !== undefined ? nodeIdMapCollection.astNodeById.get(parentId) : undefined; } -export function maybeParentAstChecked( +export function parentAstChecked( nodeIdMapCollection: Collection, childId: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): T | undefined { - const maybeAstNode: Ast.TNode | undefined = maybeParentAst(nodeIdMapCollection, childId); + const astNode: Ast.TNode | undefined = parentAst(nodeIdMapCollection, childId); - return maybeAstNode && AstUtils.isNodeKind(maybeAstNode, expectedNodeKinds) ? maybeAstNode : undefined; + return astNode && AstUtils.isNodeKind(astNode, expectedNodeKinds) ? astNode : undefined; } -export function maybeParentContext(nodeIdMapCollection: Collection, childId: number): ParseContext.TNode | undefined { - const maybeParentId: number | undefined = nodeIdMapCollection.parentIdById.get(childId); +export function parentContext(nodeIdMapCollection: Collection, childId: number): ParseContext.TNode | undefined { + const parentId: number | undefined = nodeIdMapCollection.parentIdById.get(childId); - return maybeParentId !== undefined ? nodeIdMapCollection.contextNodeById.get(maybeParentId) : undefined; + return parentId !== undefined ? nodeIdMapCollection.contextNodeById.get(parentId) : undefined; } -export function maybeParentContextChecked( +export function parentContextChecked( nodeIdMapCollection: Collection, childId: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): ParseContext.Node | undefined { - const maybeContextNode: ParseContext.TNode | undefined = maybeParentContext(nodeIdMapCollection, childId); + const contextNode: ParseContext.TNode | undefined = parentContext(nodeIdMapCollection, childId); - return maybeContextNode && ParseContextUtils.isNodeKind(maybeContextNode, expectedNodeKinds) - ? maybeContextNode - : undefined; + return contextNode && ParseContextUtils.isNodeKind(contextNode, expectedNodeKinds) ? contextNode : undefined; } -export function maybeParentXor(nodeIdMapCollection: Collection, childId: number): TXorNode | undefined { - const maybeAstNode: Ast.TNode | undefined = maybeParentAst(nodeIdMapCollection, childId); +export function parentXor(nodeIdMapCollection: Collection, childId: number): TXorNode | undefined { + const astNode: Ast.TNode | undefined = parentAst(nodeIdMapCollection, childId); - if (maybeAstNode !== undefined) { - return boxAst(maybeAstNode); + if (astNode !== undefined) { + return boxAst(astNode); } - const maybeContext: ParseContext.TNode | undefined = maybeParentContext(nodeIdMapCollection, childId); + const context: ParseContext.TNode | undefined = parentContext(nodeIdMapCollection, childId); - if (maybeContext !== undefined) { - return boxContext(maybeContext); + if (context !== undefined) { + return boxContext(context); } return undefined; } -export function maybeParentXorChecked( +export function parentXorChecked( nodeIdMapCollection: Collection, childId: number, expectedNodeKinds: ReadonlyArray | T["kind"], ): XorNode | undefined { - const maybeXorNode: TXorNode | undefined = maybeParentXor(nodeIdMapCollection, childId); + const xorNode: TXorNode | undefined = parentXor(nodeIdMapCollection, childId); - return maybeXorNode && XorNodeUtils.isNodeKind(maybeXorNode, expectedNodeKinds) ? maybeXorNode : undefined; + return xorNode && XorNodeUtils.isNodeKind(xorNode, expectedNodeKinds) ? xorNode : undefined; } diff --git a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/specializedSelectors.ts b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/specializedSelectors.ts index 0c04b075..722fc12d 100644 --- a/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/specializedSelectors.ts +++ b/src/powerquery-parser/parser/nodeIdMap/nodeIdMapUtils/specializedSelectors.ts @@ -4,8 +4,8 @@ import { assertGetNthChild, assertGetNthChildChecked, - maybeNthChildChecked, - maybeUnboxNthChildIfAstChecked, + nthChildChecked, + unboxNthChildIfAstChecked, } from "./childSelectors"; import { assertGetParentXor, assertGetParentXorChecked } from "./parentSelectors"; import { assertGetXor, assertGetXorChecked } from "./commonSelectors"; @@ -17,17 +17,17 @@ import { CommonError } from "../../../common"; // Returns the previous sibling of the given recursive expression. // Commonly used for things like getting the identifier name used in an InvokeExpression. // Returns undefined if there is no previous sibling. -export function assertGetRecursiveExpressionPreviousSibling( +export function assertRecursiveExpressionPreviousSibling( nodeIdMapCollection: NodeIdMap.Collection, nodeId: number, - maybeExpectedNodeKinds?: ReadonlyArray | T["kind"] | undefined, + expectedNodeKinds?: ReadonlyArray | T["kind"] | undefined, ): TXorNode { const xorNode: TXorNode = assertGetXor(nodeIdMapCollection, nodeId); const arrayWrapper: TXorNode = assertGetParentXorChecked(nodeIdMapCollection, nodeId, Ast.NodeKind.ArrayWrapper); - const maybePrimaryExpressionAttributeId: number | undefined = xorNode.node.maybeAttributeIndex; + const primaryExpressionAttributeId: number | undefined = xorNode.node.attributeIndex; // It's not the first element in the ArrayWrapper. - if (maybePrimaryExpressionAttributeId && maybePrimaryExpressionAttributeId > 0) { + if (primaryExpressionAttributeId && primaryExpressionAttributeId > 0) { const childIds: ReadonlyArray = NodeIdMapIterator.assertIterChildIds( nodeIdMapCollection.childIdsById, arrayWrapper.node.id, @@ -52,12 +52,12 @@ export function assertGetRecursiveExpressionPreviousSibling ); } - return maybeExpectedNodeKinds + return expectedNodeKinds ? assertGetNthChildChecked( nodeIdMapCollection, arrayWrapper.node.id, indexOfPrimaryExpressionId - 1, - maybeExpectedNodeKinds, + expectedNodeKinds, ) : assertGetNthChild(nodeIdMapCollection, arrayWrapper.node.id, indexOfPrimaryExpressionId - 1); } @@ -65,20 +65,15 @@ export function assertGetRecursiveExpressionPreviousSibling else { const recursivePrimaryExpression: TXorNode = assertGetParentXor(nodeIdMapCollection, arrayWrapper.node.id); - return maybeExpectedNodeKinds - ? assertGetNthChildChecked( - nodeIdMapCollection, - recursivePrimaryExpression.node.id, - 0, - maybeExpectedNodeKinds, - ) + return expectedNodeKinds + ? assertGetNthChildChecked(nodeIdMapCollection, recursivePrimaryExpression.node.id, 0, expectedNodeKinds) : assertGetNthChild(nodeIdMapCollection, recursivePrimaryExpression.node.id, 0); } } // Asserts the given node is an InvokeExpression, // then returns the previous sibling on the condition that it's an identifier. -export function maybeInvokeExpressionIdentifier( +export function invokeExpressionIdentifier( nodeIdMapCollection: NodeIdMap.Collection, nodeId: number, ): XorNode | undefined { @@ -86,7 +81,7 @@ export function maybeInvokeExpressionIdentifier( // The only place for an identifier in a RecursivePrimaryExpression is as the head, therefore an InvokeExpression // only has a name if the InvokeExpression is the 0th element in the RecursivePrimaryExpressionArray. - if (invokeExprXorNode.node.maybeAttributeIndex !== 0) { + if (invokeExprXorNode.node.attributeIndex !== 0) { return undefined; } @@ -94,21 +89,18 @@ export function maybeInvokeExpressionIdentifier( const recursiveArrayXorNode: TXorNode = assertGetParentXor(nodeIdMapCollection, invokeExprXorNode.node.id); const recursiveExprXorNode: TXorNode = assertGetParentXor(nodeIdMapCollection, recursiveArrayXorNode.node.id); - const maybeHeadXorNode: XorNode | undefined = - maybeNthChildChecked( - nodeIdMapCollection, - recursiveExprXorNode.node.id, - 0, - Ast.NodeKind.IdentifierExpression, - ); + const headXorNode: XorNode | undefined = nthChildChecked( + nodeIdMapCollection, + recursiveExprXorNode.node.id, + 0, + Ast.NodeKind.IdentifierExpression, + ); // It's not an identifier expression so there's nothing we can do. - if (maybeHeadXorNode === undefined) { + if (headXorNode === undefined) { return undefined; } - const headXorNode: XorNode = maybeHeadXorNode; - // The only place for an identifier in a RecursivePrimaryExpression is as the head, therefore an InvokeExpression // only has a name if the InvokeExpression is the 0th element in the RecursivePrimaryExpressionArray. if (XorNodeUtils.isContextXor(headXorNode)) { @@ -130,11 +122,11 @@ export function maybeInvokeExpressionIdentifier( } // Unboxes the node if it's a identifier -export function maybeUnboxIdentifier( +export function unboxIdentifier( nodeIdMapCollection: NodeIdMap.Collection, functionParameter: TXorNode, ): Ast.Identifier | undefined { - return maybeUnboxNthChildIfAstChecked( + return unboxNthChildIfAstChecked( nodeIdMapCollection, functionParameter.node.id, 1, @@ -143,32 +135,34 @@ export function maybeUnboxIdentifier( } // Unboxes the identifier literal if it exists. -export function maybeUnboxIdentifierLiteral( +export function unboxIdentifierLiteral( nodeIdMapCollection: NodeIdMap.Collection, functionParameter: TXorNode, ): string | undefined { - const maybeIdentifier: Ast.Identifier | undefined = maybeUnboxIdentifier(nodeIdMapCollection, functionParameter); + const identifier: Ast.Identifier | undefined = unboxIdentifier(nodeIdMapCollection, functionParameter); - return maybeIdentifier ? maybeIdentifier.literal : undefined; + return identifier ? identifier.literal : undefined; } // Unboxes the identifier literal for function name if it exists. -export function maybeInvokeExpressionIdentifierLiteral( +export function invokeExpressionIdentifierLiteral( nodeIdMapCollection: NodeIdMap.Collection, nodeId: number, ): string | undefined { assertGetXorChecked(nodeIdMapCollection, nodeId, Ast.NodeKind.InvokeExpression); - const maybeIdentifierExpressionXorNode: XorNode | undefined = - maybeInvokeExpressionIdentifier(nodeIdMapCollection, nodeId); + const identifierExpressionXorNode: XorNode | undefined = invokeExpressionIdentifier( + nodeIdMapCollection, + nodeId, + ); - if (maybeIdentifierExpressionXorNode === undefined || XorNodeUtils.isContextXor(maybeIdentifierExpressionXorNode)) { + if (identifierExpressionXorNode === undefined || XorNodeUtils.isContextXor(identifierExpressionXorNode)) { return undefined; } - const identifierExpression: Ast.IdentifierExpression = maybeIdentifierExpressionXorNode.node; + const identifierExpression: Ast.IdentifierExpression = identifierExpressionXorNode.node; - return identifierExpression.maybeInclusiveConstant === undefined + return identifierExpression.inclusiveConstant === undefined ? identifierExpression.identifier.literal - : identifierExpression.maybeInclusiveConstant.constantKind + identifierExpression.identifier.literal; + : identifierExpression.inclusiveConstant.constantKind + identifierExpression.identifier.literal; } diff --git a/src/powerquery-parser/parser/nodeIdMap/xorNodeUtils.ts b/src/powerquery-parser/parser/nodeIdMap/xorNodeUtils.ts index d3438906..8b8d5587 100644 --- a/src/powerquery-parser/parser/nodeIdMap/xorNodeUtils.ts +++ b/src/powerquery-parser/parser/nodeIdMap/xorNodeUtils.ts @@ -256,32 +256,30 @@ export function isTWrapped(xorNode: TXorNode): xorNode is XorNode ]); } -export function maybeIdentifierExpressionLiteral(xorNode: TXorNode): string | undefined { - const maybeIdentifierExpression: Ast.IdentifierExpression | undefined = maybeUnboxAstChecked( +export function identifierExpressionLiteral(xorNode: TXorNode): string | undefined { + const identifierExpression: Ast.IdentifierExpression | undefined = unboxAstChecked( xorNode, Ast.NodeKind.IdentifierExpression, ); - if (maybeIdentifierExpression === undefined) { + if (identifierExpression === undefined) { return undefined; } - const identifierExpression: Ast.IdentifierExpression = maybeIdentifierExpression; - - return identifierExpression.maybeInclusiveConstant === undefined + return identifierExpression.inclusiveConstant === undefined ? identifierExpression.identifier.literal - : identifierExpression.maybeInclusiveConstant.constantKind + identifierExpression.identifier.literal; + : identifierExpression.inclusiveConstant.constantKind + identifierExpression.identifier.literal; } -export function maybeUnboxAst(xorNode: TXorNode): Ast.TNode | undefined { +export function unboxAst(xorNode: TXorNode): Ast.TNode | undefined { return isAstXor(xorNode) ? xorNode.node : undefined; } -export function maybeUnboxAstChecked( +export function unboxAstChecked( xorNode: TXorNode, expectedNodeKinds: ReadonlyArray | T["kind"], ): T | undefined { - const maybeAstNode: Ast.TNode | undefined = maybeUnboxAst(xorNode); + const astNode: Ast.TNode | undefined = unboxAst(xorNode); - return maybeAstNode && AstUtils.isNodeKind(maybeAstNode, expectedNodeKinds) ? maybeAstNode : undefined; + return astNode && AstUtils.isNodeKind(astNode, expectedNodeKinds) ? astNode : undefined; } diff --git a/src/powerquery-parser/parser/parseState/parseState.ts b/src/powerquery-parser/parser/parseState/parseState.ts index ddb083a6..7edb5b33 100644 --- a/src/powerquery-parser/parser/parseState/parseState.ts +++ b/src/powerquery-parser/parser/parseState/parseState.ts @@ -9,14 +9,14 @@ import { Token } from "../../language"; import { TraceManager } from "../../common/trace"; export interface ParseState { + readonly cancellationToken: ICancellationToken | undefined; readonly disambiguationBehavior: Disambiguation.DismabiguationBehavior; readonly lexerSnapshot: LexerSnapshot; readonly locale: string; - readonly maybeCancellationToken: ICancellationToken | undefined; readonly traceManager: TraceManager; contextState: ParseContext.State; - maybeCurrentToken: Token.Token | undefined; - maybeCurrentContextNode: ParseContext.TNode | undefined; - maybeCurrentTokenKind: Token.TokenKind | undefined; + currentContextNode: ParseContext.TNode | undefined; + currentToken: Token.Token | undefined; + currentTokenKind: Token.TokenKind | undefined; tokenIndex: number; } diff --git a/src/powerquery-parser/parser/parseState/parseStateUtils.ts b/src/powerquery-parser/parser/parseState/parseStateUtils.ts index b119605f..d82cd862 100644 --- a/src/powerquery-parser/parser/parseState/parseStateUtils.ts +++ b/src/powerquery-parser/parser/parseState/parseStateUtils.ts @@ -11,34 +11,33 @@ import { NoOpTraceManagerInstance } from "../../common/trace"; import { ParseState } from "./parseState"; import { SequenceKind } from "../error"; -export function createState(lexerSnapshot: LexerSnapshot, maybeOverrides: Partial | undefined): ParseState { - const tokenIndex: number = maybeOverrides?.tokenIndex ?? 0; - const maybeCurrentToken: Token.Token | undefined = lexerSnapshot.tokens[tokenIndex]; - const maybeCurrentTokenKind: Token.TokenKind | undefined = maybeCurrentToken?.kind; - const contextState: ParseContext.State = maybeOverrides?.contextState ?? ParseContextUtils.createState(); +export function createState(lexerSnapshot: LexerSnapshot, overrides: Partial | undefined): ParseState { + const tokenIndex: number = overrides?.tokenIndex ?? 0; + const currentToken: Token.Token | undefined = lexerSnapshot.tokens[tokenIndex]; + const currentTokenKind: Token.TokenKind | undefined = currentToken?.kind; + const contextState: ParseContext.State = overrides?.contextState ?? ParseContextUtils.createState(); - const maybeCurrentContextNodeId: number | undefined = + const currentContextNodeId: number | undefined = contextState.nodeIdMapCollection.contextNodeById.size > 0 ? Math.max(...contextState.nodeIdMapCollection.contextNodeById.keys()) : undefined; - const maybeCurrentContextNode: ParseContext.TNode | undefined = - maybeCurrentContextNodeId !== undefined - ? MapUtils.assertGet(contextState.nodeIdMapCollection.contextNodeById, maybeCurrentContextNodeId) + const currentContextNode: ParseContext.TNode | undefined = + currentContextNodeId !== undefined + ? MapUtils.assertGet(contextState.nodeIdMapCollection.contextNodeById, currentContextNodeId) : undefined; return { - ...maybeOverrides, - disambiguationBehavior: - maybeOverrides?.disambiguationBehavior ?? Disambiguation.DismabiguationBehavior.Thorough, + ...overrides, + disambiguationBehavior: overrides?.disambiguationBehavior ?? Disambiguation.DismabiguationBehavior.Thorough, lexerSnapshot, - locale: maybeOverrides?.locale ?? DefaultLocale, - maybeCancellationToken: maybeOverrides?.maybeCancellationToken, - traceManager: maybeOverrides?.traceManager ?? NoOpTraceManagerInstance, - contextState: maybeOverrides?.contextState ?? ParseContextUtils.createState(), - maybeCurrentToken, - maybeCurrentContextNode, - maybeCurrentTokenKind, + locale: overrides?.locale ?? DefaultLocale, + cancellationToken: overrides?.cancellationToken, + traceManager: overrides?.traceManager ?? NoOpTraceManagerInstance, + contextState: overrides?.contextState ?? ParseContextUtils.createState(), + currentToken, + currentContextNode, + currentTokenKind, tokenIndex, }; } @@ -47,10 +46,10 @@ export function createState(lexerSnapshot: LexerSnapshot, maybeOverrides: Partia // eslint-disable-next-line require-await export async function applyState(state: ParseState, update: ParseState): Promise { state.tokenIndex = update.tokenIndex; - state.maybeCurrentToken = update.maybeCurrentToken; - state.maybeCurrentTokenKind = update.maybeCurrentTokenKind; + state.currentToken = update.currentToken; + state.currentTokenKind = update.currentTokenKind; state.contextState = update.contextState; - state.maybeCurrentContextNode = update.maybeCurrentContextNode; + state.currentContextNode = update.currentContextNode; } // If you have a custom parser + parser state, then you'll have to create your own copyState/applyState functions. @@ -67,42 +66,38 @@ export function startContext(state: ParseState, nodeKind: T state.contextState, nodeKind, state.tokenIndex, - state.maybeCurrentToken, - state.maybeCurrentContextNode, + state.currentToken, + state.currentContextNode, ); - state.maybeCurrentContextNode = newContextNode; + state.currentContextNode = newContextNode; } export function endContext(state: ParseState, astNode: T): void { const contextNode: ParseContext.TNode = Assert.asDefined( - state.maybeCurrentContextNode, + state.currentContextNode, `can't end a context if one doesn't exist`, ); - const maybeParentOfContextNode: ParseContext.TNode | undefined = ParseContextUtils.endContext( + const parentOfContextNode: ParseContext.TNode | undefined = ParseContextUtils.endContext( state.contextState, contextNode, astNode, ); - state.maybeCurrentContextNode = maybeParentOfContextNode; + state.currentContextNode = parentOfContextNode; } -export function deleteContext(state: ParseState, maybeNodeId: number | undefined): void { - let nodeId: number; - - if (maybeNodeId === undefined) { - nodeId = Assert.asDefined(state.maybeCurrentContextNode, `can't delete a context if one doesn't exist`).id; - } else { - nodeId = maybeNodeId; +export function deleteContext(state: ParseState, nodeId: number | undefined): void { + if (nodeId === undefined) { + nodeId = Assert.asDefined(state.currentContextNode, `can't delete a context if one doesn't exist`).id; } - state.maybeCurrentContextNode = ParseContextUtils.deleteContext(state.contextState, nodeId); + state.currentContextNode = ParseContextUtils.deleteContext(state.contextState, nodeId); } export function incrementAttributeCounter(state: ParseState): void { - Assert.asDefined(state.maybeCurrentContextNode, `state.maybeCurrentContextNode`).attributeCounter += 1; + Assert.asDefined(state.currentContextNode, `state.currentContextNode`).attributeCounter += 1; } // ------------------------- @@ -143,13 +138,13 @@ export function isOnConstantKind(state: ParseState, constantKind: Constant.TCons } export function isOnGeneralizedIdentifierStart(state: ParseState, tokenIndex: number = state.tokenIndex): boolean { - const maybeTokenKind: Token.TokenKind | undefined = state.lexerSnapshot.tokens[tokenIndex]?.kind; + const tokenKind: Token.TokenKind | undefined = state.lexerSnapshot.tokens[tokenIndex]?.kind; - if (maybeTokenKind === undefined) { + if (tokenKind === undefined) { return false; } - switch (maybeTokenKind) { + switch (tokenKind) { case Token.TokenKind.Identifier: case Token.TokenKind.KeywordAnd: case Token.TokenKind.KeywordAs: @@ -211,8 +206,8 @@ export function isRecursivePrimaryExpressionNext( // ----------------------------- export function assertGetContextNodeMetadata(state: ParseState): ContextNodeMetadata { - const currentContextNode: ParseContext.TNode = Assert.asDefined(state.maybeCurrentContextNode); - const tokenStart: Token.Token = Assert.asDefined(currentContextNode.maybeTokenStart); + const currentContextNode: ParseContext.TNode = Assert.asDefined(state.currentContextNode); + const tokenStart: Token.Token = Assert.asDefined(currentContextNode.tokenStart); // inclusive token index const tokenIndexEnd: number = state.tokenIndex - 1; @@ -227,16 +222,16 @@ export function assertGetContextNodeMetadata(state: ParseState): ContextNodeMeta return { id: currentContextNode.id, - maybeAttributeIndex: currentContextNode.maybeAttributeIndex, + attributeIndex: currentContextNode.attributeIndex, tokenRange, }; } export function assertGetTokenAt(state: ParseState, tokenIndex: number): Token.Token { const lexerSnapshot: LexerSnapshot = state.lexerSnapshot; - const maybeToken: Token.Token | undefined = lexerSnapshot.tokens[tokenIndex]; + const token: Token.Token | undefined = lexerSnapshot.tokens[tokenIndex]; - return Assert.asDefined(maybeToken, undefined, { tokenIndex }); + return Assert.asDefined(token, undefined, { tokenIndex }); } // ------------------------------- @@ -249,10 +244,10 @@ export function assertGetTokenAt(state: ParseState, tokenIndex: number): Token.T export function testCsvContinuationLetExpression( state: ParseState, ): ParseError.ExpectedCsvContinuationError | undefined { - if (state.maybeCurrentTokenKind === Token.TokenKind.KeywordIn) { + if (state.currentTokenKind === Token.TokenKind.KeywordIn) { return new ParseError.ExpectedCsvContinuationError( ParseError.CsvContinuationKind.LetExpression, - maybeCurrentTokenWithColumnNumber(state), + currentTokenWithColumnNumber(state), state.locale, ); } @@ -264,10 +259,10 @@ export function testCsvContinuationDanglingComma( state: ParseState, tokenKind: Token.TokenKind, ): ParseError.ExpectedCsvContinuationError | undefined { - if (state.maybeCurrentTokenKind === tokenKind) { + if (state.currentTokenKind === tokenKind) { return new ParseError.ExpectedCsvContinuationError( ParseError.CsvContinuationKind.DanglingComma, - maybeCurrentTokenWithColumnNumber(state), + currentTokenWithColumnNumber(state), state.locale, ); } else { @@ -291,7 +286,7 @@ export function testClosingTokenKind( return new ParseError.ExpectedClosingTokenKind( expectedTokenKind, - maybeCurrentTokenWithColumnNumber(state), + currentTokenWithColumnNumber(state), state.locale, ); } @@ -300,10 +295,10 @@ export function testIsOnTokenKind( state: ParseState, expectedTokenKind: Token.TokenKind, ): ParseError.ExpectedTokenKindError | undefined { - if (expectedTokenKind !== state.maybeCurrentTokenKind) { - const maybeToken: ParseError.TokenWithColumnNumber | undefined = maybeCurrentTokenWithColumnNumber(state); + if (expectedTokenKind !== state.currentTokenKind) { + const token: ParseError.TokenWithColumnNumber | undefined = currentTokenWithColumnNumber(state); - return new ParseError.ExpectedTokenKindError(expectedTokenKind, maybeToken, state.locale); + return new ParseError.ExpectedTokenKindError(expectedTokenKind, token, state.locale); } else { return undefined; } @@ -314,12 +309,12 @@ export function testIsOnAnyTokenKind( expectedAnyTokenKinds: ReadonlyArray, ): ParseError.ExpectedAnyTokenKindError | undefined { const isError: boolean = - state.maybeCurrentTokenKind === undefined || !expectedAnyTokenKinds.includes(state.maybeCurrentTokenKind); + state.currentTokenKind === undefined || !expectedAnyTokenKinds.includes(state.currentTokenKind); if (isError) { - const maybeToken: ParseError.TokenWithColumnNumber | undefined = maybeCurrentTokenWithColumnNumber(state); + const token: ParseError.TokenWithColumnNumber | undefined = currentTokenWithColumnNumber(state); - return new ParseError.ExpectedAnyTokenKindError(expectedAnyTokenKinds, maybeToken, state.locale); + return new ParseError.ExpectedAnyTokenKindError(expectedAnyTokenKinds, token, state.locale); } else { return undefined; } @@ -339,8 +334,8 @@ export function assertNoMoreTokens(state: ParseState): void { } export function assertNoOpenContext(state: ParseState): void { - Assert.isUndefined(state.maybeCurrentContextNode, undefined, { - contextNodeId: state.maybeCurrentContextNode?.id, + Assert.isUndefined(state.currentContextNode, undefined, { + contextNodeId: state.currentContextNode?.id, }); } @@ -376,21 +371,21 @@ function unterminatedSequence(state: ParseState, sequenceKind: SequenceKind): Pa // ---------- Column number factories ---------- // --------------------------------------------- -export function maybeCurrentTokenWithColumnNumber(state: ParseState): ParseError.TokenWithColumnNumber | undefined { - return maybeTokenWithColumnNumber(state, state.tokenIndex); +export function currentTokenWithColumnNumber(state: ParseState): ParseError.TokenWithColumnNumber | undefined { + return tokenWithColumnNumber(state, state.tokenIndex); } -export function maybeTokenWithColumnNumber( +export function tokenWithColumnNumber( state: ParseState, tokenIndex: number, ): ParseError.TokenWithColumnNumber | undefined { - const maybeToken: Token.Token | undefined = state.lexerSnapshot.tokens[tokenIndex]; + const token: Token.Token | undefined = state.lexerSnapshot.tokens[tokenIndex]; - if (maybeToken === undefined) { + if (!token) { return undefined; } - const currentToken: Token.Token = maybeToken; + const currentToken: Token.Token = token; return { token: currentToken, @@ -400,6 +395,6 @@ export function maybeTokenWithColumnNumber( interface ContextNodeMetadata { readonly id: number; - readonly maybeAttributeIndex: number | undefined; + readonly attributeIndex: number | undefined; readonly tokenRange: Token.TokenRange; } diff --git a/src/powerquery-parser/parser/parser/parser.ts b/src/powerquery-parser/parser/parser/parser.ts index 82fdb9d6..91b76104 100644 --- a/src/powerquery-parser/parser/parser/parser.ts +++ b/src/powerquery-parser/parser/parser/parser.ts @@ -10,7 +10,7 @@ export type TriedParse = Result; export interface ParseStateCheckpoint { readonly tokenIndex: number; readonly contextStateIdCounter: number; - readonly maybeContextNodeId: number | undefined; + readonly contextNodeId: number | undefined; } export interface ParseOk { @@ -37,341 +37,333 @@ export interface Parser { state: ParseState, parser: Parser, identifierContextKind: Ast.IdentifierContextKind, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Ast.Identifier; readonly readGeneralizedIdentifier: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readKeyword: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Ast.IdentifierExpression; // 12.2.1 Documents readonly readDocument: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.2 Section Documents readonly readSectionDocument: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readSectionMembers: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise>; readonly readSectionMember: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.1 Expressions readonly readNullCoalescingExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.2 Logical expressions readonly readLogicalExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.3 Is expression readonly readIsExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readNullablePrimitiveType: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.4 As expression readonly readAsExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.5 Equality expression readonly readEqualityExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.6 Relational expression readonly readRelationalExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.7 Arithmetic expressions readonly readArithmeticExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.8 Metadata expression readonly readMetadataExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.9 Unary expression readonly readUnaryExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.10 Primary expression readonly readPrimaryExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readRecursivePrimaryExpression: ( state: ParseState, parser: Parser, head: Ast.TPrimaryExpression, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.11 Literal expression readonly readLiteralExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Ast.LiteralExpression; // 12.2.3.12 Identifier expression readonly readIdentifierExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Ast.IdentifierExpression; // 12.2.3.14 Parenthesized expression readonly readParenthesizedExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.15 Not-implemented expression readonly readNotImplementedExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Ast.NotImplementedExpression; // 12.2.3.16 Invoke expression readonly readInvokeExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.17 List expression readonly readListExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readListItem: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.18 Record expression readonly readRecordExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.19 Item access expression readonly readItemAccessExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.20 Field access expression readonly readFieldSelection: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readFieldProjection: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readFieldSelector: ( state: ParseState, parser: Parser, allowOptional: boolean, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.21 Function expression readonly readFunctionExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readParameterList: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise>; - readonly readAsType: ( - state: ParseState, - parser: Parser, - maybeCorrelationId: number | undefined, - ) => Promise; + readonly readAsType: (state: ParseState, parser: Parser, correlationId: number | undefined) => Promise; // 12.2.3.22 Each expression readonly readEachExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.23 Let expression readonly readLetExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.24 If expression readonly readIfExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.25 Type expression readonly readTypeExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; - readonly readType: ( - state: ParseState, - parser: Parser, - maybeCorrelationId: number | undefined, - ) => Promise; + readonly readType: (state: ParseState, parser: Parser, correlationId: number | undefined) => Promise; readonly readPrimaryType: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readRecordType: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readTableType: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readFieldSpecificationList: ( state: ParseState, parser: Parser, allowOpenMarker: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readListType: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readFunctionType: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readParameterSpecificationList: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise>; readonly readNullableType: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.26 Error raising expression readonly readErrorRaisingExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.3.27 Error handling expression readonly readErrorHandlingExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; // 12.2.4 Literal Attributes readonly readRecordLiteral: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readFieldNamePairedAnyLiterals: ( state: ParseState, parser: Parser, onePairRequired: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise>; readonly readListLiteral: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readAnyLiteral: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readPrimitiveType: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readIdentifierPairedExpressions: ( @@ -379,23 +371,23 @@ export interface Parser { parser: Parser, onePairRequired: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise>; readonly readIdentifierPairedExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; readonly readGeneralizedIdentifierPairedExpressions: ( state: ParseState, parser: Parser, onePairRequired: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise>; readonly readGeneralizedIdentifierPairedExpression: ( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ) => Promise; } diff --git a/src/powerquery-parser/parser/parser/parserUtils.ts b/src/powerquery-parser/parser/parser/parserUtils.ts index 56a70324..39a1ff06 100644 --- a/src/powerquery-parser/parser/parser/parserUtils.ts +++ b/src/powerquery-parser/parser/parser/parserUtils.ts @@ -16,26 +16,26 @@ export async function tryParse(parseSettings: ParseSettings, lexerSnapshot: Lexe const trace: Trace = parseSettings.traceManager.entry( ParserUtilsTraceConstant.ParserUtils, tryParse.name, - parseSettings.maybeInitialCorrelationId, + parseSettings.initialCorrelationId, ); const updatedSettings: ParseSettings = { ...parseSettings, - maybeInitialCorrelationId: trace.id, + initialCorrelationId: trace.id, }; - const maybeParserEntryPointFn: - | ((state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => Promise) - | undefined = updatedSettings?.maybeParserEntryPointFn; + const parserEntryPoint: + | ((state: ParseState, parser: Parser, correlationId: number | undefined) => Promise) + | undefined = updatedSettings?.parserEntryPoint; - if (maybeParserEntryPointFn === undefined) { + if (parserEntryPoint === undefined) { return await tryParseDocument(updatedSettings, lexerSnapshot); } const parseState: ParseState = updatedSettings.createParseState(lexerSnapshot, defaultOverrides(updatedSettings)); try { - const root: Ast.TNode = await maybeParserEntryPointFn(parseState, updatedSettings.parser, trace.id); + const root: Ast.TNode = await parserEntryPoint(parseState, updatedSettings.parser, trace.id); ParseStateUtils.assertIsDoneParsing(parseState); return ResultUtils.boxOk({ @@ -59,7 +59,7 @@ export async function tryParseDocument( const trace: Trace = parseSettings.traceManager.entry( ParserUtilsTraceConstant.ParserUtils, tryParseDocument.name, - parseSettings.maybeInitialCorrelationId, + parseSettings.initialCorrelationId, ); let root: Ast.TNode; @@ -132,7 +132,7 @@ export async function createCheckpoint(state: ParseState): Promise { state.tokenIndex = checkpoint.tokenIndex; - state.maybeCurrentToken = state.lexerSnapshot.tokens[state.tokenIndex]; - state.maybeCurrentTokenKind = state.maybeCurrentToken?.kind; + state.currentToken = state.lexerSnapshot.tokens[state.tokenIndex]; + state.currentTokenKind = state.currentToken?.kind; const contextState: ParseContext.State = state.contextState; const nodeIdMapCollection: NodeIdMap.Collection = state.contextState.nodeIdMapCollection; @@ -168,8 +168,8 @@ export async function restoreCheckpoint(state: ParseState, checkpoint: ParseStat const reverseNumberSort: (left: number, right: number) => number = (left: number, right: number) => right - left; for (const nodeId of newAstNodeIds.sort(reverseNumberSort)) { - const maybeParentId: number | undefined = nodeIdMapCollection.parentIdById.get(nodeId); - const parentWillBeDeleted: boolean = maybeParentId !== undefined && maybeParentId >= backupIdCounter; + const parentId: number | undefined = nodeIdMapCollection.parentIdById.get(nodeId); + const parentWillBeDeleted: boolean = parentId !== undefined && parentId >= backupIdCounter; ParseContextUtils.deleteAst(state.contextState, nodeId, parentWillBeDeleted); } @@ -177,13 +177,13 @@ export async function restoreCheckpoint(state: ParseState, checkpoint: ParseStat ParseContextUtils.deleteContext(state.contextState, nodeId); } - if (checkpoint.maybeContextNodeId) { - state.maybeCurrentContextNode = NodeIdMapUtils.assertUnboxContext( + if (checkpoint.contextNodeId) { + state.currentContextNode = NodeIdMapUtils.assertUnboxContext( state.contextState.nodeIdMapCollection.contextNodeById, - checkpoint.maybeContextNodeId, + checkpoint.contextNodeId, ); } else { - state.maybeCurrentContextNode = undefined; + state.currentContextNode = undefined; } } @@ -204,7 +204,7 @@ function ensureParseError(state: ParseState, error: Error, locale: string): Pars function defaultOverrides(parseSettings: ParseSettings): Partial { return { locale: parseSettings.locale, - maybeCancellationToken: parseSettings.maybeCancellationToken, + cancellationToken: parseSettings.cancellationToken, traceManager: parseSettings.traceManager, }; } diff --git a/src/powerquery-parser/parser/parsers/combinatorialParser.ts b/src/powerquery-parser/parser/parsers/combinatorialParser.ts index 1373a3b2..e8304ee6 100644 --- a/src/powerquery-parser/parser/parsers/combinatorialParser.ts +++ b/src/powerquery-parser/parser/parsers/combinatorialParser.ts @@ -31,56 +31,56 @@ export const CombinatorialParser: Parser = { restoreCheckpoint: ParserUtils.restoreCheckpoint, // 12.2.3.2 Logical expressions - readLogicalExpression: (state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => + readLogicalExpression: (state: ParseState, parser: Parser, correlationId: number | undefined) => readBinOpExpression( state, parser, Ast.NodeKind.LogicalExpression, - maybeCorrelationId, + correlationId, ) as Promise, // 12.2.3.3 Is expression - readIsExpression: (state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => - readBinOpExpression(state, parser, Ast.NodeKind.IsExpression, maybeCorrelationId) as Promise, + readIsExpression: (state: ParseState, parser: Parser, correlationId: number | undefined) => + readBinOpExpression(state, parser, Ast.NodeKind.IsExpression, correlationId) as Promise, // 12.2.3.4 As expression - readAsExpression: (state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => - readBinOpExpression(state, parser, Ast.NodeKind.AsExpression, maybeCorrelationId) as Promise, + readAsExpression: (state: ParseState, parser: Parser, correlationId: number | undefined) => + readBinOpExpression(state, parser, Ast.NodeKind.AsExpression, correlationId) as Promise, // 12.2.3.5 Equality expression - readEqualityExpression: (state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => + readEqualityExpression: (state: ParseState, parser: Parser, correlationId: number | undefined) => readBinOpExpression( state, parser, Ast.NodeKind.EqualityExpression, - maybeCorrelationId, + correlationId, ) as Promise, // 12.2.3.6 Relational expression - readRelationalExpression: (state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => + readRelationalExpression: (state: ParseState, parser: Parser, correlationId: number | undefined) => readBinOpExpression( state, parser, Ast.NodeKind.RelationalExpression, - maybeCorrelationId, + correlationId, ) as Promise, // 12.2.3.7 Arithmetic expressions - readArithmeticExpression: (state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => + readArithmeticExpression: (state: ParseState, parser: Parser, correlationId: number | undefined) => readBinOpExpression( state, parser, Ast.NodeKind.ArithmeticExpression, - maybeCorrelationId, + correlationId, ) as Promise, // 12.2.3.8 Metadata expression - readMetadataExpression: (state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => + readMetadataExpression: (state: ParseState, parser: Parser, correlationId: number | undefined) => readBinOpExpression( state, parser, Ast.NodeKind.MetadataExpression, - maybeCorrelationId, + correlationId, ) as Promise, // 12.2.3.9 Unary expression @@ -95,17 +95,17 @@ async function readBinOpExpression( state: ParseState, parser: Parser, nodeKind: Ast.NodeKind, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( CombinatorialTraceConstant.CombinatorialParse, readBinOpExpression.name, - maybeCorrelationId, + correlationId, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); - const placeholderContextId: number = Assert.asDefined(state.maybeCurrentContextNode).id; + const placeholderContextId: number = Assert.asDefined(state.currentContextNode).id; // operators/operatorConstants are of length N // expressions are of length N + 1 @@ -116,18 +116,18 @@ async function readBinOpExpression( await parser.readUnaryExpression(state, parser, trace.id), ]; - let maybeOperator: Constant.TBinOpExpressionOperator | undefined = - ConstantUtils.maybeBinOpExpressionOperatorKindFrom(state.maybeCurrentTokenKind); + let operator: Constant.TBinOpExpressionOperator | undefined = ConstantUtils.binOpExpressionOperatorKindFrom( + state.currentTokenKind, + ); - while (maybeOperator !== undefined) { - const operator: Constant.TBinOpExpressionOperator = maybeOperator; + while (operator !== undefined) { operators.push(operator); operatorConstants.push( NaiveParseSteps.readTokenKindAsConstant( state, - Assert.asDefined(state.maybeCurrentTokenKind), - maybeOperator, + Assert.asDefined(state.currentTokenKind), + operator, trace.id, ), ); @@ -144,7 +144,7 @@ async function readBinOpExpression( expressions.push(await parser.readUnaryExpression(state, parser, trace.id)); } - maybeOperator = ConstantUtils.maybeBinOpExpressionOperatorKindFrom(state.maybeCurrentTokenKind); + operator = ConstantUtils.binOpExpressionOperatorKindFrom(state.currentTokenKind); } // There was a single TUnaryExpression, not a TBinOpExpression. @@ -193,9 +193,9 @@ async function readBinOpExpression( Ast.TBinOpExpression | Ast.TUnaryExpression | Ast.TNullablePrimitiveType > = expressions[minPrecedenceIndex + 1]; - left.maybeAttributeIndex = 0; - operatorConstant.maybeAttributeIndex = 1; - right.maybeAttributeIndex = 2; + left.attributeIndex = 0; + operatorConstant.attributeIndex = 1; + right.attributeIndex = 2; const leftTokenRange: Token.TokenRange = left.tokenRange; const rightTokenRange: Token.TokenRange = right.tokenRange; @@ -203,8 +203,8 @@ async function readBinOpExpression( const newBinOpExpression: Ast.TBinOpExpression = { kind: binOpExpressionNodeKindFrom(operator), id: newBinOpExpressionId, - // maybeAttributeIndex is fixed after all TBinOpExpressions have been created. - maybeAttributeIndex: 0, + // attributeIndex is fixed after all TBinOpExpressions have been created. + attributeIndex: 0, tokenRange: { tokenIndexStart: leftTokenRange.tokenIndexStart, tokenIndexEnd: rightTokenRange.tokenIndexEnd, @@ -236,12 +236,12 @@ async function readBinOpExpression( nodeIdMapCollection.childIdsById.set(newBinOpExpressionId, [left.id, operatorConstant.id, right.id]); nodeIdMapCollection.astNodeById.set(newBinOpExpressionId, newBinOpExpression); - const maybeIdsForSpecificNodeKind: Set | undefined = nodeIdMapCollection.idsByNodeKind.get( + const idsForSpecificNodeKind: Set | undefined = nodeIdMapCollection.idsByNodeKind.get( newBinOpExpression.kind, ); - if (maybeIdsForSpecificNodeKind) { - maybeIdsForSpecificNodeKind.add(newBinOpExpression.id); + if (idsForSpecificNodeKind) { + idsForSpecificNodeKind.add(newBinOpExpression.id); } else { nodeIdMapCollection.idsByNodeKind.set(newBinOpExpression.kind, new Set([newBinOpExpression.id])); } @@ -320,32 +320,32 @@ function binOpExpressionNodeKindFrom(operator: Constant.TBinOpExpressionOperator async function readUnaryExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( CombinatorialTraceConstant.CombinatorialParse, readUnaryExpression.name, - maybeCorrelationId, + correlationId, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); - let maybePrimaryExpression: Ast.TPrimaryExpression | undefined; + let primaryExpression: Ast.TPrimaryExpression | undefined; // LL(1) - switch (state.maybeCurrentTokenKind) { + switch (state.currentTokenKind) { // PrimaryExpression case Token.TokenKind.AtSign: case Token.TokenKind.Identifier: - maybePrimaryExpression = NaiveParseSteps.readIdentifierExpression(state, parser, trace.id); + primaryExpression = NaiveParseSteps.readIdentifierExpression(state, parser, trace.id); break; case Token.TokenKind.LeftParenthesis: - maybePrimaryExpression = await NaiveParseSteps.readParenthesizedExpression(state, parser, trace.id); + primaryExpression = await NaiveParseSteps.readParenthesizedExpression(state, parser, trace.id); break; case Token.TokenKind.LeftBracket: - maybePrimaryExpression = await DisambiguationUtils.readAmbiguousBracket( + primaryExpression = await DisambiguationUtils.readAmbiguousBracket( state, parser, [ @@ -359,11 +359,11 @@ async function readUnaryExpression( break; case Token.TokenKind.LeftBrace: - maybePrimaryExpression = await NaiveParseSteps.readListExpression(state, parser, trace.id); + primaryExpression = await NaiveParseSteps.readListExpression(state, parser, trace.id); break; case Token.TokenKind.Ellipsis: - maybePrimaryExpression = NaiveParseSteps.readNotImplementedExpression(state, parser, trace.id); + primaryExpression = NaiveParseSteps.readNotImplementedExpression(state, parser, trace.id); break; // LiteralExpression @@ -392,7 +392,7 @@ async function readUnaryExpression( case Token.TokenKind.KeywordHashDuration: case Token.TokenKind.KeywordHashTable: case Token.TokenKind.KeywordHashTime: - maybePrimaryExpression = parser.readKeyword(state, parser, trace.id); + primaryExpression = parser.readKeyword(state, parser, trace.id); break; // Let Naive throw an error. @@ -402,9 +402,6 @@ async function readUnaryExpression( return await NaiveParseSteps.readUnaryExpression(state, parser, trace.id); } - // We should only reach this code block if a primary expression was read. - const primaryExpression: Ast.TPrimaryExpression = maybePrimaryExpression; - if (ParseStateUtils.isRecursivePrimaryExpressionNext(state, state.tokenIndex)) { trace.exit(); diff --git a/src/powerquery-parser/parser/parsers/naive.ts b/src/powerquery-parser/parser/parsers/naive.ts index 42258406..622d0385 100644 --- a/src/powerquery-parser/parser/parsers/naive.ts +++ b/src/powerquery-parser/parser/parsers/naive.ts @@ -35,7 +35,7 @@ interface WrappedRead< Content, Close extends Constant.WrapperConstant, > extends Ast.IWrapped { - readonly maybeOptionalConstant: Ast.IConstant | undefined; + readonly optionalConstant: Ast.IConstant | undefined; } const GeneralizedIdentifierTerminatorTokenKinds: ReadonlyArray = [ @@ -52,11 +52,11 @@ export function readIdentifier( state: ParseState, _parser: Parser, identifierContextKind: Ast.IdentifierContextKind, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Ast.Identifier { const nodeKind: Ast.NodeKind.Identifier = Ast.NodeKind.Identifier; - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readIdentifier.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readIdentifier.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); @@ -83,14 +83,14 @@ export function readIdentifier( export async function readGeneralizedIdentifier( state: ParseState, _parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.GeneralizedIdentifier = Ast.NodeKind.GeneralizedIdentifier; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readGeneralizedIdentifier.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, @@ -101,10 +101,7 @@ export async function readGeneralizedIdentifier( const tokenRangeStartIndex: number = state.tokenIndex; let tokenRangeEndIndex: number = tokenRangeStartIndex; - while ( - state.maybeCurrentTokenKind && - GeneralizedIdentifierTerminatorTokenKinds.indexOf(state.maybeCurrentTokenKind) === -1 - ) { + while (state.currentTokenKind && GeneralizedIdentifierTerminatorTokenKinds.indexOf(state.currentTokenKind) === -1) { readToken(state); tokenRangeEndIndex = state.tokenIndex; } @@ -116,7 +113,7 @@ export async function readGeneralizedIdentifier( }); throw new ParseError.ExpectedGeneralizedIdentifierError( - ParseStateUtils.maybeTokenWithColumnNumber(state, state.tokenIndex + 1), + ParseStateUtils.tokenWithColumnNumber(state, state.tokenIndex + 1), state.locale, ); } @@ -135,7 +132,7 @@ export async function readGeneralizedIdentifier( }); throw new ParseError.ExpectedGeneralizedIdentifierError( - ParseStateUtils.maybeTokenWithColumnNumber(state, state.tokenIndex + 1), + ParseStateUtils.tokenWithColumnNumber(state, state.tokenIndex + 1), state.locale, ); } @@ -160,11 +157,11 @@ export async function readGeneralizedIdentifier( export function readKeyword( state: ParseState, _parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Ast.IdentifierExpression { const nodeKind: Ast.NodeKind.IdentifierExpression = Ast.NodeKind.IdentifierExpression; - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readKeyword.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readKeyword.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); @@ -192,7 +189,7 @@ export function readKeyword( ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: nodeKind, isLeaf: false, - maybeInclusiveConstant: undefined, + inclusiveConstant: undefined, identifier, }; @@ -209,13 +206,13 @@ export function readKeyword( export async function readDocument( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readDocument.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readDocument.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); let document: Ast.TDocument; @@ -236,11 +233,11 @@ export async function readDocument( // Reset the parser's state. state.tokenIndex = 0; state.contextState = ParseContextUtils.createState(); - state.maybeCurrentContextNode = undefined; + state.currentContextNode = undefined; if (state.lexerSnapshot.tokens.length) { - state.maybeCurrentToken = state.lexerSnapshot.tokens[0]; - state.maybeCurrentTokenKind = state.maybeCurrentToken?.kind; + state.currentToken = state.lexerSnapshot.tokens[0]; + state.currentTokenKind = state.currentToken?.kind; } try { @@ -284,27 +281,18 @@ export async function readDocument( export async function readSectionDocument( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.Section = Ast.NodeKind.Section; - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readSectionDocument.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readSectionDocument.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); - const maybeLiteralAttributes: Ast.RecordLiteral | undefined = await maybeReadLiteralAttributes( - state, - parser, - trace.id, - ); + const literalAttributes: Ast.RecordLiteral | undefined = await readLiteralAttributes(state, parser, trace.id); const sectionConstant: Ast.IConstant = readTokenKindAsConstant( state, @@ -313,10 +301,10 @@ export async function readSectionDocument( trace.id, ); - let maybeName: Ast.Identifier | undefined; + let name: Ast.Identifier | undefined; if (ParseStateUtils.isOnTokenKind(state, Token.TokenKind.Identifier)) { - maybeName = parser.readIdentifier(state, parser, Ast.IdentifierContextKind.Key, trace.id); + name = parser.readIdentifier(state, parser, Ast.IdentifierContextKind.Key, trace.id); } else { ParseStateUtils.incrementAttributeCounter(state); } @@ -338,9 +326,9 @@ export async function readSectionDocument( ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: nodeKind, isLeaf: false, - maybeLiteralAttributes, + literalAttributes, sectionConstant, - maybeName, + name, semicolonConstant, sectionMembers, }; @@ -354,20 +342,15 @@ export async function readSectionDocument( export async function readSectionMembers( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const nodeKind: Ast.NodeKind.ArrayWrapper = Ast.NodeKind.ArrayWrapper; - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readSectionMembers.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readSectionMembers.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const totalTokens: number = state.lexerSnapshot.tokens.length; @@ -394,30 +377,21 @@ export async function readSectionMembers( export async function readSectionMember( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.SectionMember = Ast.NodeKind.SectionMember; - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readSectionMember.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readSectionMember.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); - const maybeLiteralAttributes: Ast.RecordLiteral | undefined = await maybeReadLiteralAttributes( - state, - parser, - trace.id, - ); + const literalAttributes: Ast.RecordLiteral | undefined = await readLiteralAttributes(state, parser, trace.id); - const maybeSharedConstant: Ast.IConstant | undefined = - maybeReadTokenKindAsConstant(state, Token.TokenKind.KeywordShared, Constant.KeywordConstant.Shared); + const sharedConstant: Ast.IConstant | undefined = + readTokenKindAsConstantOrUndefined(state, Token.TokenKind.KeywordShared, Constant.KeywordConstant.Shared); const namePairedExpression: Ast.IdentifierPairedExpression = await parser.readIdentifierPairedExpression( state, @@ -436,8 +410,8 @@ export async function readSectionMember( ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: nodeKind, isLeaf: false, - maybeLiteralAttributes, - maybeSharedConstant, + literalAttributes, + sharedConstant, namePairedExpression, semicolonConstant, }; @@ -459,18 +433,18 @@ export async function readSectionMember( export async function readNullCoalescingExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readNullCoalescingExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const expression: Ast.TExpression = await recursiveReadBinOpExpression< Ast.NodeKind.NullCoalescingExpression, @@ -481,8 +455,8 @@ export async function readNullCoalescingExpression( state, Ast.NodeKind.NullCoalescingExpression, () => parser.readLogicalExpression(state, parser, trace.id), - (maybeCurrentTokenKind: Token.TokenKind | undefined) => - maybeCurrentTokenKind === Token.TokenKind.NullCoalescingOperator + (currentTokenKind: Token.TokenKind | undefined) => + currentTokenKind === Token.TokenKind.NullCoalescingOperator ? Constant.MiscConstant.NullCoalescingOperator : undefined, () => parser.readLogicalExpression(state, parser, trace.id), @@ -497,17 +471,17 @@ export async function readNullCoalescingExpression( export async function readExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readExpression.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readExpression.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); let expression: Ast.TExpression; - switch (state.maybeCurrentTokenKind) { + switch (state.currentTokenKind) { case Token.TokenKind.KeywordEach: expression = await parser.readEachExpression(state, parser, trace.id); break; @@ -549,18 +523,13 @@ export async function readExpression( export async function readLogicalExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readLogicalExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readLogicalExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const logicalExpression: Ast.TLogicalExpression = await recursiveReadBinOpExpression< Ast.NodeKind.LogicalExpression, @@ -571,8 +540,7 @@ export async function readLogicalExpression( state, Ast.NodeKind.LogicalExpression, () => parser.readIsExpression(state, parser, trace.id), - (maybeCurrentTokenKind: Token.TokenKind | undefined) => - ConstantUtils.maybeLogicalOperatorKindFrom(maybeCurrentTokenKind), + (currentTokenKind: Token.TokenKind | undefined) => ConstantUtils.logicalOperatorKindFrom(currentTokenKind), () => parser.readIsExpression(state, parser, trace.id), trace.id, ); @@ -589,13 +557,13 @@ export async function readLogicalExpression( export async function readIsExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readIsExpression.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readIsExpression.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const isExpression: Ast.TIsExpression = await recursiveReadBinOpExpression< Ast.NodeKind.IsExpression, @@ -606,8 +574,8 @@ export async function readIsExpression( state, Ast.NodeKind.IsExpression, () => parser.readAsExpression(state, parser, trace.id), - (maybeCurrentTokenKind: Token.TokenKind | undefined) => - maybeCurrentTokenKind === Token.TokenKind.KeywordIs ? Constant.KeywordConstant.Is : undefined, + (currentTokenKind: Token.TokenKind | undefined) => + currentTokenKind === Token.TokenKind.KeywordIs ? Constant.KeywordConstant.Is : undefined, () => parser.readNullablePrimitiveType(state, parser, trace.id), trace.id, ); @@ -621,18 +589,18 @@ export async function readIsExpression( export async function readNullablePrimitiveType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readNullablePrimitiveType.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); let nullablePrimitiveType: Ast.TNullablePrimitiveType; @@ -660,13 +628,13 @@ export async function readNullablePrimitiveType( export async function readAsExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readAsExpression.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readAsExpression.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const asExpression: Ast.TAsExpression = await recursiveReadBinOpExpression< Ast.NodeKind.AsExpression, @@ -677,8 +645,8 @@ export async function readAsExpression( state, Ast.NodeKind.AsExpression, () => parser.readEqualityExpression(state, parser, trace.id), - (maybeCurrentTokenKind: Token.TokenKind | undefined) => - maybeCurrentTokenKind === Token.TokenKind.KeywordAs ? Constant.KeywordConstant.As : undefined, + (currentTokenKind: Token.TokenKind | undefined) => + currentTokenKind === Token.TokenKind.KeywordAs ? Constant.KeywordConstant.As : undefined, () => parser.readNullablePrimitiveType(state, parser, trace.id), trace.id, ); @@ -695,18 +663,18 @@ export async function readAsExpression( export async function readEqualityExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readEqualityExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const equalityExpression: Ast.TEqualityExpression = await recursiveReadBinOpExpression< Ast.NodeKind.EqualityExpression, @@ -717,8 +685,7 @@ export async function readEqualityExpression( state, Ast.NodeKind.EqualityExpression, () => parser.readRelationalExpression(state, parser, trace.id), - (maybeCurrentTokenKind: Token.TokenKind | undefined) => - ConstantUtils.maybeEqualityOperatorKindFrom(maybeCurrentTokenKind), + (currentTokenKind: Token.TokenKind | undefined) => ConstantUtils.equalityOperatorKindFrom(currentTokenKind), () => parser.readRelationalExpression(state, parser, trace.id), trace.id, ); @@ -735,18 +702,18 @@ export async function readEqualityExpression( export async function readRelationalExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readRelationalExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const relationalExpression: Ast.TRelationalExpression = await recursiveReadBinOpExpression< Ast.NodeKind.RelationalExpression, @@ -757,8 +724,7 @@ export async function readRelationalExpression( state, Ast.NodeKind.RelationalExpression, () => parser.readArithmeticExpression(state, parser, trace.id), - (maybeCurrentTokenKind: Token.TokenKind | undefined) => - ConstantUtils.maybeRelationalOperatorKindFrom(maybeCurrentTokenKind), + (currentTokenKind: Token.TokenKind | undefined) => ConstantUtils.relationalOperatorKindFrom(currentTokenKind), () => parser.readArithmeticExpression(state, parser, trace.id), trace.id, ); @@ -775,18 +741,18 @@ export async function readRelationalExpression( export async function readArithmeticExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readArithmeticExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const arithmeticExpression: Ast.TArithmeticExpression = await recursiveReadBinOpExpression< Ast.NodeKind.ArithmeticExpression, @@ -797,8 +763,7 @@ export async function readArithmeticExpression( state, Ast.NodeKind.ArithmeticExpression, () => parser.readMetadataExpression(state, parser, trace.id), - (maybeCurrentTokenKind: Token.TokenKind | undefined) => - ConstantUtils.maybeArithmeticOperatorKindFrom(maybeCurrentTokenKind), + (currentTokenKind: Token.TokenKind | undefined) => ConstantUtils.arithmeticOperatorKindFrom(currentTokenKind), () => parser.readMetadataExpression(state, parser, trace.id), trace.id, ); @@ -815,32 +780,32 @@ export async function readArithmeticExpression( export async function readMetadataExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.MetadataExpression = Ast.NodeKind.MetadataExpression; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readMetadataExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const left: Ast.TUnaryExpression = await parser.readUnaryExpression(state, parser, trace.id); - const maybeMetaConstant: Ast.IConstant | undefined = maybeReadTokenKindAsConstant( + const metaConstant: Ast.IConstant | undefined = readTokenKindAsConstantOrUndefined( state, Token.TokenKind.KeywordMeta, Constant.KeywordConstant.Meta, ); - if (maybeMetaConstant !== undefined) { - const operatorConstant: Ast.IConstant = maybeMetaConstant; + if (metaConstant !== undefined) { + const operatorConstant: Ast.IConstant = metaConstant; const right: Ast.TUnaryExpression = await parser.readUnaryExpression(state, parser, trace.id); const metadataExpression: Ast.MetadataExpression = { @@ -879,24 +844,17 @@ export async function readMetadataExpression( export async function readUnaryExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readUnaryExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readUnaryExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); - let maybeOperator: Constant.UnaryOperator | undefined = ConstantUtils.maybeUnaryOperatorKindFrom( - state.maybeCurrentTokenKind, - ); + let operator: Constant.UnaryOperator | undefined = ConstantUtils.unaryOperatorKindFrom(state.currentTokenKind); - if (maybeOperator === undefined) { + if (operator === undefined) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [NaiveTraceConstant.IsOperatorPresent]: false, @@ -913,12 +871,12 @@ export async function readUnaryExpression( const operatorConstants: Ast.IConstant[] = []; - while (maybeOperator) { + while (operator) { operatorConstants.push( - readTokenKindAsConstant(state, state.maybeCurrentTokenKind as Token.TokenKind, maybeOperator, trace.id), + readTokenKindAsConstant(state, state.currentTokenKind as Token.TokenKind, operator, trace.id), ); - maybeOperator = ConstantUtils.maybeUnaryOperatorKindFrom(state.maybeCurrentTokenKind); + operator = ConstantUtils.unaryOperatorKindFrom(state.currentTokenKind); } const operators: Ast.IArrayWrapper> = { @@ -957,29 +915,24 @@ export async function readUnaryExpression( export async function readPrimaryExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readPrimaryExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readPrimaryExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); let primaryExpression: Ast.TPrimaryExpression | undefined; - const maybeCurrentTokenKind: Token.TokenKind | undefined = state.maybeCurrentTokenKind; + const currentTokenKind: Token.TokenKind | undefined = state.currentTokenKind; const isIdentifierExpressionNext: boolean = - maybeCurrentTokenKind === Token.TokenKind.AtSign || maybeCurrentTokenKind === Token.TokenKind.Identifier; + currentTokenKind === Token.TokenKind.AtSign || currentTokenKind === Token.TokenKind.Identifier; if (isIdentifierExpressionNext) { primaryExpression = parser.readIdentifierExpression(state, parser, trace.id); } else { - switch (maybeCurrentTokenKind) { + switch (currentTokenKind) { case Token.TokenKind.LeftParenthesis: primaryExpression = await parser.readParenthesizedExpression(state, parser, trace.id); break; @@ -1044,27 +997,27 @@ export async function readRecursivePrimaryExpression( state: ParseState, parser: Parser, head: Ast.TPrimaryExpression, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.RecursivePrimaryExpression = Ast.NodeKind.RecursivePrimaryExpression; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readRecursivePrimaryExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const nodeIdMapCollection: NodeIdMap.Collection = state.contextState.nodeIdMapCollection; const currentContextNode: ParseContext.TNode = Assert.asDefined( - state.maybeCurrentContextNode, - "state.maybeCurrentContextNode", + state.currentContextNode, + "state.currentContextNode", ); // Update parent attributes. @@ -1083,12 +1036,12 @@ export async function readRecursivePrimaryExpression( const mutableHead: TypeScriptUtils.StripReadonly = head; // Update token start to match the first parsed node under it, aka the head. - mutableContext.maybeTokenStart = state.lexerSnapshot.tokens[newTokenIndexStart]; + mutableContext.tokenStart = state.lexerSnapshot.tokens[newTokenIndexStart]; mutableContext.tokenIndexStart = newTokenIndexStart; // Update attribute counters. mutableContext.attributeCounter = 1; - mutableHead.maybeAttributeIndex = 0; + mutableHead.attributeIndex = 0; // Recalculate ids after shuffling things around. const newNodeIdByOldNodeId: Map = NodeIdMapUtils.recalculateIds( @@ -1111,15 +1064,15 @@ export async function readRecursivePrimaryExpression( let continueReadingValues: boolean = true; while (continueReadingValues) { - const maybeCurrentTokenKind: Token.TokenKind | undefined = state.maybeCurrentTokenKind; + const currentTokenKind: Token.TokenKind | undefined = state.currentTokenKind; - if (maybeCurrentTokenKind === Token.TokenKind.LeftParenthesis) { + if (currentTokenKind === Token.TokenKind.LeftParenthesis) { // eslint-disable-next-line no-await-in-loop recursiveExpressions.push(await parser.readInvokeExpression(state, parser, trace.id)); - } else if (maybeCurrentTokenKind === Token.TokenKind.LeftBrace) { + } else if (currentTokenKind === Token.TokenKind.LeftBrace) { // eslint-disable-next-line no-await-in-loop recursiveExpressions.push(await parser.readItemAccessExpression(state, parser, trace.id)); - } else if (maybeCurrentTokenKind === Token.TokenKind.LeftBracket) { + } else if (currentTokenKind === Token.TokenKind.LeftBracket) { // eslint-disable-next-line no-await-in-loop const bracketExpression: Ast.TFieldAccessExpression = (await DisambiguationUtils.readAmbiguousBracket( state, @@ -1169,20 +1122,15 @@ export async function readRecursivePrimaryExpression( export function readLiteralExpression( state: ParseState, _parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Ast.LiteralExpression { const nodeKind: Ast.NodeKind.LiteralExpression = Ast.NodeKind.LiteralExpression; - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readLiteralExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readLiteralExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const expectedTokenKinds: ReadonlyArray = [ @@ -1196,24 +1144,24 @@ export function readLiteralExpression( Token.TokenKind.TextLiteral, ]; - const maybeError: ParseError.ExpectedAnyTokenKindError | undefined = ParseStateUtils.testIsOnAnyTokenKind( + const error: ParseError.ExpectedAnyTokenKindError | undefined = ParseStateUtils.testIsOnAnyTokenKind( state, expectedTokenKinds, ); - if (maybeError) { + if (error) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [TraceConstant.IsThrowing]: true, }); - throw maybeError; + throw error; } const literalKind: Ast.LiteralKind = Assert.asDefined( - AstUtils.maybeLiteralKindFrom(state.maybeCurrentTokenKind), + AstUtils.literalKindFrom(state.currentTokenKind), `couldn't convert TokenKind into LiteralKind`, - { maybeCurrentTokenKind: state.maybeCurrentTokenKind }, + { currentTokenKind: state.currentTokenKind }, ); const literal: string = readToken(state); @@ -1243,24 +1191,24 @@ export function readLiteralExpression( export function readIdentifierExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Ast.IdentifierExpression { const nodeKind: Ast.NodeKind.IdentifierExpression = Ast.NodeKind.IdentifierExpression; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readIdentifierExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); - const maybeInclusiveConstant: Ast.IConstant | undefined = - maybeReadTokenKindAsConstant(state, Token.TokenKind.AtSign, Constant.MiscConstant.AtSign); + const inclusiveConstant: Ast.IConstant | undefined = + readTokenKindAsConstantOrUndefined(state, Token.TokenKind.AtSign, Constant.MiscConstant.AtSign); const identifier: Ast.Identifier = parser.readIdentifier(state, parser, Ast.IdentifierContextKind.Value, trace.id); @@ -1268,7 +1216,7 @@ export function readIdentifierExpression( ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: nodeKind, isLeaf: false, - maybeInclusiveConstant, + inclusiveConstant, identifier, }; @@ -1285,18 +1233,18 @@ export function readIdentifierExpression( export async function readParenthesizedExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readParenthesizedExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const parenthesizedExpression: Ast.ParenthesizedExpression = await readWrapped( state, @@ -1332,20 +1280,20 @@ export async function readParenthesizedExpression( export function readNotImplementedExpression( state: ParseState, _parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Ast.NotImplementedExpression { const nodeKind: Ast.NodeKind.NotImplementedExpression = Ast.NodeKind.NotImplementedExpression; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readNotImplementedExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const ellipsisConstant: Ast.IConstant = readTokenKindAsConstant( @@ -1375,18 +1323,13 @@ export function readNotImplementedExpression( export async function readInvokeExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readInvokeExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readInvokeExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const continueReadingValues: boolean = !ParseStateUtils.isNextTokenKind(state, Token.TokenKind.RightParenthesis); @@ -1433,18 +1376,13 @@ export async function readInvokeExpression( export async function readListExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readListExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readListExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const continueReadingValues: boolean = !ParseStateUtils.isNextTokenKind(state, Token.TokenKind.RightBrace); @@ -1479,15 +1417,15 @@ export async function readListExpression( export async function readListItem( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.RangeExpression = Ast.NodeKind.RangeExpression; - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readListItem.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readListItem.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const left: Ast.TExpression = await parser.readExpression(state, parser, trace.id); @@ -1538,18 +1476,13 @@ export async function readListItem( export async function readRecordExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readRecordExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readRecordExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const continueReadingValues: boolean = !ParseStateUtils.isNextTokenKind(state, Token.TokenKind.RightBracket); @@ -1589,18 +1522,18 @@ export async function readRecordExpression( export async function readItemAccessExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readItemAccessExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const itemAccessExpression: Ast.ItemAccessExpression = await readWrapped( state, @@ -1624,18 +1557,13 @@ export async function readItemAccessExpression( export async function readFieldSelection( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readFieldSelection.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readFieldSelection.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const fieldSelector: Ast.FieldSelector = await readFieldSelector(state, parser, true, trace.id); trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex }); @@ -1646,18 +1574,13 @@ export async function readFieldSelection( export async function readFieldProjection( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readFieldProjection.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readFieldProjection.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const fieldProjection: Ast.FieldProjection = await readWrapped( state, @@ -1692,18 +1615,13 @@ export async function readFieldSelector( state: ParseState, parser: Parser, allowOptional: boolean, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readFieldSelector.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readFieldSelector.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const fieldSelector: Ast.FieldSelector = await readWrapped( state, @@ -1734,20 +1652,20 @@ export async function readFieldSelector( export async function readFunctionExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.FunctionExpression = Ast.NodeKind.FunctionExpression; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readFunctionExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const parameters: Ast.IParameterList = await parser.readParameterList( @@ -1756,7 +1674,7 @@ export async function readFunctionExpression( trace.id, ); - const maybeFunctionReturnType: Ast.AsNullablePrimitiveType | undefined = await maybeReadAsNullablePrimitiveType( + const functionReturnType: Ast.AsNullablePrimitiveType | undefined = await readAsNullablePrimitiveType( state, parser, trace.id, @@ -1776,7 +1694,7 @@ export async function readFunctionExpression( kind: nodeKind, isLeaf: false, parameters, - maybeFunctionReturnType, + functionReturnType, fatArrowConstant, expression, }; @@ -1790,23 +1708,18 @@ export async function readFunctionExpression( export async function readParameterList( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readParameterList.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readParameterList.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const parameterList: Ast.IParameterList = await genericReadParameterList( state, parser, - () => maybeReadAsNullablePrimitiveType(state, parser, trace.id), + () => readAsNullablePrimitiveType(state, parser, trace.id), trace.id, ); @@ -1815,23 +1728,23 @@ export async function readParameterList( return parameterList; } -async function maybeReadAsNullablePrimitiveType( +async function readAsNullablePrimitiveType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, - maybeReadAsNullablePrimitiveType.name, - maybeCorrelationId, + readAsNullablePrimitiveType.name, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); - const maybeAsNullablePrimitiveType: Ast.AsNullablePrimitiveType | undefined = await maybeReadPairedConstant( + const asNullablePrimitiveType: Ast.AsNullablePrimitiveType | undefined = await readPairedConstantOrUndefined( state, Ast.NodeKind.AsNullablePrimitiveType, () => ParseStateUtils.isOnTokenKind(state, Token.TokenKind.KeywordAs), @@ -1842,19 +1755,19 @@ async function maybeReadAsNullablePrimitiveType( trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex }); - return maybeAsNullablePrimitiveType; + return asNullablePrimitiveType; } export async function readAsType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readAsType.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readAsType.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const asType: Ast.AsType = await readPairedConstant( state, @@ -1876,18 +1789,13 @@ export async function readAsType( export async function readEachExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readEachExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readEachExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const eachExpression: Ast.EachExpression = await readPairedConstant( state, @@ -1909,20 +1817,15 @@ export async function readEachExpression( export async function readLetExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.LetExpression = Ast.NodeKind.LetExpression; - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readLetExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readLetExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const letConstant: Ast.IConstant = readTokenKindAsConstant( @@ -1973,15 +1876,15 @@ export async function readLetExpression( export async function readIfExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.IfExpression = Ast.NodeKind.IfExpression; - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readIfExpression.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readIfExpression.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const ifConstant: Ast.IConstant = readTokenKindAsConstant( @@ -2036,18 +1939,13 @@ export async function readIfExpression( export async function readTypeExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readTypeExpression.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readTypeExpression.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); let typeExpression: Ast.TTypeExpression; @@ -2071,13 +1969,13 @@ export async function readTypeExpression( export async function readType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readType.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readType.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const triedReadPrimaryType: TriedReadPrimaryType = await tryReadPrimaryType(state, parser, trace.id); @@ -2101,13 +1999,13 @@ export async function readType( export async function readPrimaryType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readPrimaryType.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readPrimaryType.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const triedReadPrimaryType: TriedReadPrimaryType = await tryReadPrimaryType(state, parser, trace.id); @@ -2131,15 +2029,15 @@ export async function readPrimaryType( export async function readRecordType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.RecordType = Ast.NodeKind.RecordType; - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readRecordType.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readRecordType.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const fields: Ast.FieldSpecificationList = await parser.readFieldSpecificationList( @@ -2166,15 +2064,15 @@ export async function readRecordType( export async function readTableType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.TableType = Ast.NodeKind.TableType; - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readTableType.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readTableType.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const tableConstant: Ast.IConstant = readConstantKind( @@ -2182,12 +2080,12 @@ export async function readTableType( Constant.PrimitiveTypeConstant.Table, ); - const maybeCurrentTokenKind: Token.TokenKind | undefined = state.maybeCurrentTokenKind; + const currentTokenKind: Token.TokenKind | undefined = state.currentTokenKind; const isPrimaryExpressionExpected: boolean = - maybeCurrentTokenKind === Token.TokenKind.AtSign || - maybeCurrentTokenKind === Token.TokenKind.Identifier || - maybeCurrentTokenKind === Token.TokenKind.LeftParenthesis; + currentTokenKind === Token.TokenKind.AtSign || + currentTokenKind === Token.TokenKind.Identifier || + currentTokenKind === Token.TokenKind.LeftParenthesis; let rowType: Ast.FieldSpecificationList | Ast.TPrimaryExpression; @@ -2222,20 +2120,20 @@ export async function readFieldSpecificationList( parser: Parser, allowOpenMarker: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.FieldSpecificationList = Ast.NodeKind.FieldSpecificationList; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readFieldSpecificationList.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const leftBracketConstant: Ast.IConstant = readTokenKindAsConstant( @@ -2253,15 +2151,15 @@ export async function readFieldSpecificationList( ParseStateUtils.startContext(state, fieldArrayNodeKind); while (continueReadingValues) { - const maybeError: ParseError.TInnerParseError | undefined = testPostCommaError(state); + const error: ParseError.TInnerParseError | undefined = testPostCommaError(state); - if (maybeError) { + if (error) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [TraceConstant.IsThrowing]: true, }); - throw maybeError; + throw error; } if (ParseStateUtils.isOnTokenKind(state, Token.TokenKind.Ellipsis)) { @@ -2292,38 +2190,38 @@ export async function readFieldSpecificationList( const fieldSpecificationNodeKind: Ast.NodeKind.FieldSpecification = Ast.NodeKind.FieldSpecification; ParseStateUtils.startContext(state, fieldSpecificationNodeKind); - const maybeOptionalConstant: Ast.IConstant | undefined = - maybeReadConstantKind(state, Constant.LanguageConstant.Optional); + const optionalConstant: Ast.IConstant | undefined = + readConstantKindOrUndefined(state, Constant.LanguageConstant.Optional); // eslint-disable-next-line no-await-in-loop const name: Ast.GeneralizedIdentifier = await parser.readGeneralizedIdentifier(state, parser, trace.id); - const maybeFieldTypeSpecification: Ast.FieldTypeSpecification | undefined = + const fieldTypeSpecification: Ast.FieldTypeSpecification | undefined = // eslint-disable-next-line no-await-in-loop - await maybeReadFieldTypeSpecification(state, parser, trace.id); + await readFieldTypeSpecification(state, parser, trace.id); const field: Ast.FieldSpecification = { ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: fieldSpecificationNodeKind, isLeaf: false, - maybeOptionalConstant, + optionalConstant, name, - maybeFieldTypeSpecification, + fieldTypeSpecification, }; ParseStateUtils.endContext(state, field); - const maybeCommaConstant: Ast.IConstant | undefined = - maybeReadTokenKindAsConstant(state, Token.TokenKind.Comma, Constant.MiscConstant.Comma); + const commaConstant: Ast.IConstant | undefined = + readTokenKindAsConstantOrUndefined(state, Token.TokenKind.Comma, Constant.MiscConstant.Comma); - continueReadingValues = maybeCommaConstant !== undefined; + continueReadingValues = commaConstant !== undefined; const csv: Ast.ICsv = { ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: csvNodeKind, isLeaf: false, node: field, - maybeCommaConstant, + commaConstant, }; ParseStateUtils.endContext(state, csv); @@ -2347,16 +2245,9 @@ export async function readFieldSpecificationList( ParseStateUtils.endContext(state, fieldArray); - let maybeOpenRecordMarkerConstant: Ast.IConstant | undefined = undefined; - - if (isOnOpenRecordMarker) { - maybeOpenRecordMarkerConstant = readTokenKindAsConstant( - state, - Token.TokenKind.Ellipsis, - Constant.MiscConstant.Ellipsis, - trace.id, - ); - } + const openRecordMarkerConstant: Ast.IConstant | undefined = isOnOpenRecordMarker + ? readTokenKindAsConstant(state, Token.TokenKind.Ellipsis, Constant.MiscConstant.Ellipsis, trace.id) + : undefined; const rightBracketConstant: Ast.IConstant = readClosingTokenKindAsConstant( state, @@ -2371,7 +2262,7 @@ export async function readFieldSpecificationList( isLeaf: false, openWrapperConstant: leftBracketConstant, content: fieldArray, - maybeOpenRecordMarkerConstant, + openRecordMarkerConstant, closeWrapperConstant: rightBracketConstant, }; @@ -2381,39 +2272,39 @@ export async function readFieldSpecificationList( return fieldSpecificationList; } -async function maybeReadFieldTypeSpecification( +async function readFieldTypeSpecification( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.FieldTypeSpecification = Ast.NodeKind.FieldTypeSpecification; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, - maybeReadFieldTypeSpecification.name, - maybeCorrelationId, + readFieldTypeSpecification.name, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); - const maybeEqualConstant: Ast.IConstant | undefined = maybeReadTokenKindAsConstant( + const equalConstant: Ast.IConstant | undefined = readTokenKindAsConstantOrUndefined( state, Token.TokenKind.Equal, Constant.MiscConstant.Equal, ); - if (maybeEqualConstant) { + if (equalConstant) { const fieldType: Ast.TType = await parser.readType(state, parser, trace.id); const fieldTypeSpecification: Ast.FieldTypeSpecification = { ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: Ast.NodeKind.FieldTypeSpecification, isLeaf: false, - equalConstant: maybeEqualConstant, + equalConstant, fieldType, }; @@ -2454,13 +2345,13 @@ function fieldSpecificationListReadError(state: ParseState, allowOpenMarker: boo export async function readListType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readListType.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readListType.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const listType: Ast.ListType = await readWrapped( state, @@ -2480,15 +2371,15 @@ export async function readListType( export async function readFunctionType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.FunctionType = Ast.NodeKind.FunctionType; - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readFunctionType.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readFunctionType.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const functionConstant: Ast.IConstant = readConstantKind( @@ -2522,16 +2413,11 @@ export async function readFunctionType( async function tryReadPrimaryType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - tryReadPrimaryType.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, tryReadPrimaryType.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); const isTableTypeNext: boolean = ParseStateUtils.isOnConstantKind(state, Constant.PrimitiveTypeConstant.Table) && @@ -2575,18 +2461,18 @@ async function tryReadPrimaryType( export async function readParameterSpecificationList( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readParameterSpecificationList.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const parameterList: Ast.IParameterList = await genericReadParameterList( state, @@ -2603,13 +2489,13 @@ export async function readParameterSpecificationList( export async function readNullableType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readNullableType.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readNullableType.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const nullableType: Ast.NullableType = await readPairedConstant( state, @@ -2631,18 +2517,18 @@ export async function readNullableType( export async function readErrorRaisingExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readErrorRaisingExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const errorRaisingExpression: Ast.ErrorRaisingExpression = await readPairedConstant( state, @@ -2664,20 +2550,20 @@ export async function readErrorRaisingExpression( export async function readErrorHandlingExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.ErrorHandlingExpression = Ast.NodeKind.ErrorHandlingExpression; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readErrorHandlingExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, nodeKind); const tryConstant: Ast.IConstant = readTokenKindAsConstant( @@ -2701,18 +2587,18 @@ export async function readErrorHandlingExpression( trace.id, ); - const maybeError: ParseError.InvalidCatchFunctionError | undefined = testCatchFunction( + const error: ParseError.InvalidCatchFunctionError | undefined = testCatchFunction( state, catchExpression.paired, ); - if (maybeError) { + if (error) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [TraceConstant.IsError]: true, }); - throw maybeError; + throw error; } const errorHandlingCatchExpression: Ast.ErrorHandlingCatchExpression = { @@ -2722,14 +2608,14 @@ export async function readErrorHandlingExpression( isLeaf: false, tryConstant, protectedExpression, - maybeHandler: catchExpression, + handler: catchExpression, }; result = errorHandlingCatchExpression; } // optionally read OtherwiseExpression else { - const maybeOtherwiseExpression: Ast.OtherwiseExpression | undefined = await maybeReadPairedConstant( + const otherwiseExpression: Ast.OtherwiseExpression | undefined = await readPairedConstantOrUndefined( state, Ast.NodeKind.OtherwiseExpression, () => ParseStateUtils.isOnTokenKind(state, Token.TokenKind.KeywordOtherwise), @@ -2751,7 +2637,7 @@ export async function readErrorHandlingExpression( isLeaf: false, tryConstant, protectedExpression, - maybeHandler: maybeOtherwiseExpression, + handler: otherwiseExpression, }; result = errorHandlingOtherwiseExpression; @@ -2770,18 +2656,13 @@ export async function readErrorHandlingExpression( export async function readRecordLiteral( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readRecordLiteral.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readRecordLiteral.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const continueReadingValues: boolean = !ParseStateUtils.isNextTokenKind(state, Token.TokenKind.RightBracket); @@ -2829,18 +2710,18 @@ export async function readFieldNamePairedAnyLiterals( parser: Parser, continueReadingValues: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readFieldNamePairedAnyLiterals.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const csvArray: Ast.ICsvArray = await readCsvArray( state, @@ -2865,13 +2746,13 @@ export async function readFieldNamePairedAnyLiterals( export async function readListLiteral( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readListLiteral.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readListLiteral.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const continueReadingValues: boolean = !ParseStateUtils.isNextTokenKind(state, Token.TokenKind.RightBrace); @@ -2910,13 +2791,13 @@ export async function readListLiteral( export async function readAnyLiteral( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readAnyLiteral.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readAnyLiteral.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); let anyLiteral: Ast.TAnyLiteral; @@ -2936,18 +2817,13 @@ export async function readAnyLiteral( export async function readPrimitiveType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - readPrimitiveType.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readPrimitiveType.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const triedReadPrimitiveType: TriedReadPrimitiveType = await tryReadPrimitiveType(state, parser, trace.id); @@ -2971,18 +2847,13 @@ export async function readPrimitiveType( async function tryReadPrimitiveType( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const nodeKind: Ast.NodeKind.PrimitiveType = Ast.NodeKind.PrimitiveType; - const trace: Trace = state.traceManager.entry( - NaiveTraceConstant.Parse, - tryReadPrimitiveType.name, - maybeCorrelationId, - { - [NaiveTraceConstant.TokenIndex]: state.tokenIndex, - }, - ); + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, tryReadPrimitiveType.name, correlationId, { + [NaiveTraceConstant.TokenIndex]: state.tokenIndex, + }); ParseStateUtils.startContext(state, nodeKind); @@ -2994,14 +2865,12 @@ async function tryReadPrimitiveType( Token.TokenKind.NullLiteral, ]; - const maybeError: ParseError.ExpectedAnyTokenKindError | undefined = ParseStateUtils.testIsOnAnyTokenKind( + const error: ParseError.ExpectedAnyTokenKindError | undefined = ParseStateUtils.testIsOnAnyTokenKind( state, expectedTokenKinds, ); - if (maybeError) { - const error: ParseError.ExpectedAnyTokenKindError = maybeError; - + if (error) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [TraceConstant.IsError]: true, @@ -3057,7 +2926,7 @@ async function tryReadPrimitiveType( primitiveTypeKind = Constant.PrimitiveTypeConstant.Null; readToken(state); } else { - const details: { tokenKind: Token.TokenKind | undefined } = { tokenKind: state.maybeCurrentTokenKind }; + const details: { tokenKind: Token.TokenKind | undefined } = { tokenKind: state.currentTokenKind }; await parser.restoreCheckpoint(state, checkpoint); trace.exit({ @@ -3096,18 +2965,18 @@ export async function readIdentifierPairedExpressions( parser: Parser, continueReadingValues: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readIdentifierPairedExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const csvArray: Ast.ICsvArray = await readCsvArray( state, @@ -3127,15 +2996,15 @@ export async function readGeneralizedIdentifierPairedExpressions( parser: Parser, continueReadingValues: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readGeneralizedIdentifierPairedExpressions.name, - maybeCorrelationId, + correlationId, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const csvArray: Ast.ICsvArray = await readCsvArray( state, @@ -3153,18 +3022,18 @@ export async function readGeneralizedIdentifierPairedExpressions( export async function readGeneralizedIdentifierPairedExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readGeneralizedIdentifierPairedExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const generalizedIdentifierPairedExpression: Ast.GeneralizedIdentifierPairedExpression = await readKeyValuePair( @@ -3183,18 +3052,18 @@ export async function readGeneralizedIdentifierPairedExpression( export async function readIdentifierPairedExpression( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readIdentifierPairedExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const identifierPairedExpression: Ast.IdentifierPairedExpression = await readKeyValuePair( @@ -3229,14 +3098,14 @@ async function recursiveReadBinOpExpression< state: ParseState, nodeKind: Kind, leftReader: () => Promise, - maybeOperatorFrom: (tokenKind: Token.TokenKind | undefined) => Op | undefined, + operatorFrom: (tokenKind: Token.TokenKind | undefined) => Op | undefined, rightReader: () => Promise, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, recursiveReadBinOpExpression.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, @@ -3246,9 +3115,9 @@ async function recursiveReadBinOpExpression< const left: Left = await leftReader(); // If no operator, return Left - const maybeOperator: Op | undefined = maybeOperatorFrom(state.maybeCurrentTokenKind); + const operator: Op | undefined = operatorFrom(state.currentTokenKind); - if (maybeOperator === undefined) { + if (operator === undefined) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [NaiveTraceConstant.IsOperatorPresent]: false, @@ -3261,8 +3130,8 @@ async function recursiveReadBinOpExpression< const operatorConstant: Ast.TConstant & Ast.IConstant = readTokenKindAsConstant( state, - Assert.asDefined(state.maybeCurrentTokenKind), - maybeOperator, + Assert.asDefined(state.currentTokenKind), + operator, trace.id, ); @@ -3270,7 +3139,7 @@ async function recursiveReadBinOpExpression< Kind, Op, Right - >(state, nodeKind, maybeOperatorFrom, rightReader, trace.id); + >(state, nodeKind, operatorFrom, rightReader, trace.id); const binOpExpression: Ast.IBinOpExpression = { ...ParseStateUtils.assertGetContextNodeMetadata(state), @@ -3301,14 +3170,14 @@ async function recursiveReadBinOpExpressionHelper< >( state: ParseState, nodeKind: Kind, - maybeOperatorFrom: (tokenKind: Token.TokenKind | undefined) => OperatorKind | undefined, + operatorFrom: (tokenKind: Token.TokenKind | undefined) => OperatorKind | undefined, rightReader: () => Promise, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, recursiveReadBinOpExpressionHelper.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, @@ -3317,9 +3186,9 @@ async function recursiveReadBinOpExpressionHelper< ParseStateUtils.startContext(state, nodeKind); const rightAsLeft: Right = await rightReader(); - const maybeOperator: OperatorKind | undefined = maybeOperatorFrom(state.maybeCurrentTokenKind); + const operator: OperatorKind | undefined = operatorFrom(state.currentTokenKind); - if (maybeOperator === undefined) { + if (operator === undefined) { ParseStateUtils.deleteContext(state, undefined); trace.exit({ @@ -3332,8 +3201,8 @@ async function recursiveReadBinOpExpressionHelper< const operatorConstant: Ast.TConstant & Ast.IConstant = readTokenKindAsConstant( state, - Assert.asDefined(state.maybeCurrentTokenKind), - maybeOperator, + Assert.asDefined(state.currentTokenKind), + operator, trace.id, ); @@ -3341,7 +3210,7 @@ async function recursiveReadBinOpExpressionHelper< await recursiveReadBinOpExpressionHelper( state, nodeKind, - maybeOperatorFrom, + operatorFrom, rightReader, trace.id, ); @@ -3370,11 +3239,11 @@ async function readCsvArray( valueReader: () => Promise, continueReadingValues: boolean, testPostCommaError: (state: ParseState) => ParseError.TInnerParseError | undefined, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const nodeKind: Ast.NodeKind.ArrayWrapper = Ast.NodeKind.ArrayWrapper; - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readCsvArray.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readCsvArray.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); @@ -3386,38 +3255,35 @@ async function readCsvArray( const csvNodeKind: Ast.NodeKind.Csv = Ast.NodeKind.Csv; ParseStateUtils.startContext(state, csvNodeKind); - const maybeError: ParseError.TInnerParseError | undefined = testPostCommaError(state); + const error: ParseError.TInnerParseError | undefined = testPostCommaError(state); - if (maybeError) { + if (error) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [TraceConstant.IsThrowing]: true, }); - throw maybeError; + throw error; } // eslint-disable-next-line no-await-in-loop const node: T = await valueReader(); - const maybeCommaConstant: Ast.IConstant | undefined = maybeReadTokenKindAsConstant( - state, - Token.TokenKind.Comma, - Constant.MiscConstant.Comma, - ); + const commaConstant: Ast.IConstant | undefined = + readTokenKindAsConstantOrUndefined(state, Token.TokenKind.Comma, Constant.MiscConstant.Comma); const element: Ast.TCsv & Ast.ICsv = { ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: csvNodeKind, isLeaf: false, node, - maybeCommaConstant, + commaConstant, }; ParseStateUtils.endContext(state, element); elements.push(element); - continueReadingValues = maybeCommaConstant !== undefined; + continueReadingValues = commaConstant !== undefined; } const csvArray: Ast.ICsvArray = { @@ -3442,11 +3308,11 @@ async function readKeyValuePair( nodeKind: KVP["kind"], keyReader: () => Promise, valueReader: () => Promise, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { ParseStateUtils.startContext(state, nodeKind); - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readKeyValuePair.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readKeyValuePair.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); @@ -3510,7 +3376,7 @@ async function readPairedConstant< return pairedConstant; } -async function maybeReadPairedConstant< +async function readPairedConstantOrUndefined< Kind extends Ast.TPairedConstantNodeKind, ConstantKind extends Constant.TConstant, Paired, @@ -3520,12 +3386,12 @@ async function maybeReadPairedConstant< condition: () => boolean, constantReader: () => Ast.TConstant & Ast.IConstant, pairedReader: () => Promise, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise | undefined> { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, - maybeReadPairedConstant.name, - maybeCorrelationId, + readPairedConstantOrUndefined.name, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, @@ -3558,14 +3424,14 @@ async function genericReadParameterList( state: ParseState, parser: Parser, typeReader: () => Promise, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { const nodeKind: Ast.NodeKind.ParameterList = Ast.NodeKind.ParameterList; const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, genericReadParameterList.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, @@ -3592,22 +3458,21 @@ async function genericReadParameterList( ParseStateUtils.startContext(state, Ast.NodeKind.Csv); ParseStateUtils.startContext(state, Ast.NodeKind.Parameter); - const maybeError: ParseError.TInnerParseError | undefined = - testCsvContinuationDanglingCommaForParenthesis(state); + const error: ParseError.TInnerParseError | undefined = testCsvContinuationDanglingCommaForParenthesis(state); - if (maybeError) { + if (error) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [TraceConstant.IsThrowing]: true, }); - throw maybeError; + throw error; } - const maybeOptionalConstant: Ast.IConstant | undefined = - maybeReadConstantKind(state, Constant.LanguageConstant.Optional); + const optionalConstant: Ast.IConstant | undefined = + readConstantKindOrUndefined(state, Constant.LanguageConstant.Optional); - if (reachedOptionalParameter && !maybeOptionalConstant) { + if (reachedOptionalParameter && !optionalConstant) { const token: Token.Token = ParseStateUtils.assertGetTokenAt(state, state.tokenIndex); trace.exit({ @@ -3620,7 +3485,7 @@ async function genericReadParameterList( state.lexerSnapshot.graphemePositionStartFrom(token), state.locale, ); - } else if (maybeOptionalConstant) { + } else if (optionalConstant) { reachedOptionalParameter = true; } @@ -3633,33 +3498,30 @@ async function genericReadParameterList( ); // eslint-disable-next-line no-await-in-loop - const maybeParameterType: T = await typeReader(); + const parameterType: T = await typeReader(); const parameter: Ast.IParameter = { ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: Ast.NodeKind.Parameter, isLeaf: false, - maybeOptionalConstant, + optionalConstant, name, - maybeParameterType, + parameterType, }; ParseStateUtils.endContext(state, parameter); - const maybeCommaConstant: Ast.IConstant | undefined = maybeReadTokenKindAsConstant( - state, - Token.TokenKind.Comma, - Constant.MiscConstant.Comma, - ); + const commaConstant: Ast.IConstant | undefined = + readTokenKindAsConstantOrUndefined(state, Token.TokenKind.Comma, Constant.MiscConstant.Comma); - continueReadingValues = maybeCommaConstant !== undefined; + continueReadingValues = commaConstant !== undefined; const csv: Ast.ICsv> = { ...ParseStateUtils.assertGetContextNodeMetadata(state), kind: Ast.NodeKind.Csv, isLeaf: false, node: parameter, - maybeCommaConstant, + commaConstant, }; ParseStateUtils.endContext(state, csv); @@ -3714,9 +3576,9 @@ async function readWrapped< contentReader: () => Promise, closeConstantReader: () => Ast.IConstant, allowOptionalConstant: boolean, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise> { - const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readWrapped.name, maybeCorrelationId, { + const trace: Trace = state.traceManager.entry(NaiveTraceConstant.Parse, readWrapped.name, correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }); @@ -3726,10 +3588,10 @@ async function readWrapped< const content: Content = await contentReader(); const closeWrapperConstant: Ast.IConstant = closeConstantReader(); - let maybeOptionalConstant: Ast.IConstant | undefined; + let optionalConstant: Ast.IConstant | undefined; if (allowOptionalConstant) { - maybeOptionalConstant = maybeReadTokenKindAsConstant( + optionalConstant = readTokenKindAsConstantOrUndefined( state, Token.TokenKind.QuestionMark, Constant.MiscConstant.QuestionMark, @@ -3743,7 +3605,7 @@ async function readWrapped< openWrapperConstant, content, closeWrapperConstant, - maybeOptionalConstant, + optionalConstant, }; ParseStateUtils.endContext(state, wrapped as unknown as Ast.TWrapped); @@ -3757,7 +3619,7 @@ async function readWrapped< // --------------------------------------------- export function readToken(state: ParseState): string { - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); const tokens: ReadonlyArray = state.lexerSnapshot.tokens; @@ -3776,11 +3638,11 @@ export function readToken(state: ParseState): string { // That means a correct implementation would have some sort of TokenRange | Eof union type, // but there's no clean way to introduce that. // - // So, for now when a IParseState is Eof when maybeCurrentTokenKind === undefined. - state.maybeCurrentTokenKind = undefined; + // So, for now when a IParseState is Eof when currentTokenKind === undefined. + state.currentTokenKind = undefined; } else { - state.maybeCurrentToken = tokens[state.tokenIndex]; - state.maybeCurrentTokenKind = state.maybeCurrentToken.kind; + state.currentToken = tokens[state.tokenIndex]; + state.currentTokenKind = state.currentToken.kind; } return data; @@ -3790,32 +3652,32 @@ export function readClosingTokenKindAsConstant( state: ParseState, tokenKind: Token.TokenKind, constantKind: C, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Ast.TConstant & Ast.IConstant { - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, Ast.NodeKind.Constant); const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readTokenKindAsConstant.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - const maybeError: ParseError.ExpectedClosingTokenKind | undefined = ParseStateUtils.testClosingTokenKind( + const error: ParseError.ExpectedClosingTokenKind | undefined = ParseStateUtils.testClosingTokenKind( state, tokenKind, ); - if (maybeError !== undefined) { + if (error !== undefined) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [TraceConstant.IsThrowing]: true, }); - throw maybeError; + throw error; } const result: Ast.TConstant & Ast.IConstant = readTokenKindAsConstantInternal( @@ -3834,18 +3696,18 @@ export function readTokenKindAsConstant( state: ParseState, tokenKind: Token.TokenKind, constantKind: C, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Ast.TConstant & Ast.IConstant { const trace: Trace = state.traceManager.entry( NaiveTraceConstant.Parse, readTokenKindAsConstant.name, - maybeCorrelationId, + correlationId, { [NaiveTraceConstant.TokenIndex]: state.tokenIndex, }, ); - state.maybeCancellationToken?.throwIfCancelled(); + state.cancellationToken?.throwIfCancelled(); ParseStateUtils.startContext(state, Ast.NodeKind.Constant); const result: Ast.TConstant & Ast.IConstant = readTokenKindAsConstantInternal( @@ -3877,18 +3739,15 @@ function readTokenKindAsConstantInternal( }, ); - const maybeError: ParseError.ExpectedTokenKindError | undefined = ParseStateUtils.testIsOnTokenKind( - state, - tokenKind, - ); + const error: ParseError.ExpectedTokenKindError | undefined = ParseStateUtils.testIsOnTokenKind(state, tokenKind); - if (maybeError !== undefined) { + if (error !== undefined) { trace.exit({ [NaiveTraceConstant.TokenIndex]: state.tokenIndex, [TraceConstant.IsError]: true, }); - throw maybeError; + throw error; } const tokenData: string = readToken(state); @@ -3911,14 +3770,12 @@ function readTokenKindAsConstantInternal( return constant; } -export function maybeReadTokenKindAsConstant( +export function readTokenKindAsConstantOrUndefined( state: ParseState, tokenKind: Token.TokenKind, constantKind: ConstantKind, ): (Ast.TConstant & Ast.IConstant) | undefined { - state.maybeCancellationToken?.throwIfCancelled(); - - let maybeConstant: (Ast.TConstant & Ast.IConstant) | undefined; + state.cancellationToken?.throwIfCancelled(); if (ParseStateUtils.isOnTokenKind(state, tokenKind)) { const nodeKind: Ast.NodeKind.Constant = Ast.NodeKind.Constant; @@ -3940,23 +3797,19 @@ export function maybeReadTokenKindAsConstant( state: ParseState, constantKind: ConstantKind, ): Ast.TConstant & Ast.IConstant { - return Assert.asDefined(maybeReadConstantKind(state, constantKind), `couldn't conver constantKind`, { + return Assert.asDefined(readConstantKindOrUndefined(state, constantKind), `couldn't conver constantKind`, { constantKind, }); } -function maybeReadConstantKind( +function readConstantKindOrUndefined( state: ParseState, constantKind: ConstantKind, ): (Ast.TConstant & Ast.IConstant) | undefined { @@ -3998,13 +3851,13 @@ function maybeReadConstantKind( } } -async function maybeReadLiteralAttributes( +async function readLiteralAttributes( state: ParseState, parser: Parser, - maybeCorrelationId: number | undefined, + correlationId: number | undefined, ): Promise { if (ParseStateUtils.isOnTokenKind(state, Token.TokenKind.LeftBracket)) { - return await parser.readRecordLiteral(state, parser, maybeCorrelationId); + return await parser.readRecordLiteral(state, parser, correlationId); } else { ParseStateUtils.incrementAttributeCounter(state); @@ -4046,8 +3899,8 @@ function testCatchFunction( if ( parameters.length > 1 || - (parameters.length === 1 && parameters[0].node.maybeParameterType) || - catchFunction.maybeFunctionReturnType + (parameters.length === 1 && parameters[0].node.parameterType) || + catchFunction.functionReturnType ) { const tokenStart: Token.Token = Assert.asDefined( state.lexerSnapshot.tokens[catchFunction.tokenRange.tokenIndexStart], diff --git a/src/powerquery-parser/settings/settings.ts b/src/powerquery-parser/settings/settings.ts index 85075f13..6c395eb9 100644 --- a/src/powerquery-parser/settings/settings.ts +++ b/src/powerquery-parser/settings/settings.ts @@ -9,9 +9,9 @@ import { ICancellationToken } from "../common"; import { LexerSnapshot } from "../lexer"; export interface CommonSettings { + readonly cancellationToken: ICancellationToken | undefined; + readonly initialCorrelationId: number | undefined; readonly locale: string; - readonly maybeCancellationToken: ICancellationToken | undefined; - readonly maybeInitialCorrelationId: number | undefined; readonly traceManager: TraceManager; } @@ -19,24 +19,21 @@ export type LexSettings = CommonSettings; export interface ParseSettings extends CommonSettings { readonly parser: Parser; - readonly createParseState: ( - lexerSnapshot: LexerSnapshot, - maybeOverrides: Partial | undefined, - ) => ParseState; - readonly maybeParserEntryPointFn: - | ((state: ParseState, parser: Parser, maybeCorrelationId: number | undefined) => Promise) + readonly createParseState: (lexerSnapshot: LexerSnapshot, overrides: Partial | undefined) => ParseState; + readonly parserEntryPoint: + | ((state: ParseState, parser: Parser, correlationId: number | undefined) => Promise) | undefined; } export type Settings = LexSettings & ParseSettings; export const DefaultSettings: Settings = { - createParseState: (lexerSnapshot: LexerSnapshot, maybeOverrides: Partial | undefined) => - ParseStateUtils.createState(lexerSnapshot, maybeOverrides), + createParseState: (lexerSnapshot: LexerSnapshot, overrides: Partial | undefined) => + ParseStateUtils.createState(lexerSnapshot, overrides), locale: DefaultLocale, - maybeCancellationToken: undefined, - maybeInitialCorrelationId: undefined, - maybeParserEntryPointFn: undefined, + cancellationToken: undefined, + initialCorrelationId: undefined, + parserEntryPoint: undefined, parser: CombinatorialParser, traceManager: NoOpTraceManagerInstance, }; diff --git a/src/powerquery-parser/settings/settingsUtils.ts b/src/powerquery-parser/settings/settingsUtils.ts index fb13296c..c1463b05 100644 --- a/src/powerquery-parser/settings/settingsUtils.ts +++ b/src/powerquery-parser/settings/settingsUtils.ts @@ -4,9 +4,9 @@ import { DefaultSettings, Settings } from "./settings"; import { ICancellationToken } from "../common"; -export function createDefaultSettings(maybeCancellationToken: ICancellationToken | undefined): Settings { +export function createDefaultSettings(cancellationToken: ICancellationToken | undefined): Settings { return { ...DefaultSettings, - maybeCancellationToken, + cancellationToken, }; } diff --git a/src/powerquery-parser/task/taskUtils.ts b/src/powerquery-parser/task/taskUtils.ts index 8f8a4dcc..9d65cffd 100644 --- a/src/powerquery-parser/task/taskUtils.ts +++ b/src/powerquery-parser/task/taskUtils.ts @@ -174,11 +174,11 @@ export function tryLex(settings: LexSettings, text: string): TriedLexTask { } const state: Lexer.State = triedLex.value; - const maybeErrorLineMap: Lexer.ErrorLineMap | undefined = Lexer.maybeErrorLineMap(state); + const errorLineMap: Lexer.ErrorLineMap | undefined = Lexer.errorLineMap(state); - if (maybeErrorLineMap) { + if (errorLineMap) { return createLexTaskError( - new Lexer.LexError.LexError(new Lexer.LexError.ErrorLineMapError(maybeErrorLineMap, settings.locale)), + new Lexer.LexError.LexError(new Lexer.LexError.ErrorLineMapError(errorLineMap, settings.locale)), ); } @@ -207,12 +207,12 @@ export async function tryLexParse(settings: LexSettings & ParseSettings, text: s const trace: Trace = settings.traceManager.entry( TaskUtilsTraceConstant.LexParse, tryLexParse.name, - settings.maybeInitialCorrelationId, + settings.initialCorrelationId, ); const updatedSettings: LexSettings & ParseSettings = { ...settings, - maybeInitialCorrelationId: trace.id, + initialCorrelationId: trace.id, }; const triedLexTask: TriedLexTask = tryLex(updatedSettings, text); diff --git a/src/test/libraryTest/common/cancellationToken.ts b/src/test/libraryTest/common/cancellationToken.ts index 47758cf2..d6627dac 100644 --- a/src/test/libraryTest/common/cancellationToken.ts +++ b/src/test/libraryTest/common/cancellationToken.ts @@ -35,7 +35,7 @@ function assertGetLexerStateWithCancellationToken(): Lexer.State { const triedLex: Lexer.TriedLex = Lexer.tryLex(DefaultSettings, "foo"); Assert.isOk(triedLex); const state: TypeScriptUtils.StripReadonly = triedLex.value; - state.maybeCancellationToken = new TimedCancellationToken(0); + state.cancellationToken = new TimedCancellationToken(0); return state; } diff --git a/src/test/libraryTest/common/stringUtils.ts b/src/test/libraryTest/common/stringUtils.ts index 9d208e02..d364de41 100644 --- a/src/test/libraryTest/common/stringUtils.ts +++ b/src/test/libraryTest/common/stringUtils.ts @@ -15,11 +15,11 @@ describe("StringUtils", () => { it(`"a"`, () => expect(StringUtils.ensureQuoted(`"a"`)).to.equal(`"a"`)); }); - describe(`maybeFindQuote`, () => { + describe(`findQuote`, () => { it(`""`, () => { - const actual: StringUtils.FoundQuote | undefined = StringUtils.maybefindQuote(`""`, 0); + const actual: StringUtils.FoundQuotes | undefined = StringUtils.findQuotes(`""`, 0); - const expected: StringUtils.FoundQuote = { + const expected: StringUtils.FoundQuotes = { indexStart: 0, indexEnd: 2, quoteLength: 2, @@ -29,9 +29,9 @@ describe("StringUtils", () => { }); it(`""""`, () => { - const actual: StringUtils.FoundQuote | undefined = StringUtils.maybefindQuote(`""""`, 0); + const actual: StringUtils.FoundQuotes | undefined = StringUtils.findQuotes(`""""`, 0); - const expected: StringUtils.FoundQuote = { + const expected: StringUtils.FoundQuotes = { indexStart: 0, indexEnd: 4, quoteLength: 4, @@ -41,9 +41,9 @@ describe("StringUtils", () => { }); it(`"""a"""`, () => { - const actual: StringUtils.FoundQuote | undefined = StringUtils.maybefindQuote(`"""a"""`, 0); + const actual: StringUtils.FoundQuotes | undefined = StringUtils.findQuotes(`"""a"""`, 0); - const expected: StringUtils.FoundQuote = { + const expected: StringUtils.FoundQuotes = { indexStart: 0, indexEnd: 7, quoteLength: 7, @@ -53,9 +53,9 @@ describe("StringUtils", () => { }); it(`"""abc"""`, () => { - const actual: StringUtils.FoundQuote | undefined = StringUtils.maybefindQuote(`"""abc"""`, 0); + const actual: StringUtils.FoundQuotes | undefined = StringUtils.findQuotes(`"""abc"""`, 0); - const expected: StringUtils.FoundQuote = { + const expected: StringUtils.FoundQuotes = { indexStart: 0, indexEnd: 9, quoteLength: 9, @@ -64,13 +64,13 @@ describe("StringUtils", () => { expect(actual).to.deep.equal(expected); }); - it(`"`, () => expect(StringUtils.maybefindQuote(`"`, 0)).to.be.undefined); - it(`"abc`, () => expect(StringUtils.maybefindQuote(`"abc`, 0)).to.be.undefined); + it(`"`, () => expect(StringUtils.findQuotes(`"`, 0)).to.be.undefined); + it(`"abc`, () => expect(StringUtils.findQuotes(`"abc`, 0)).to.be.undefined); it(`_""`, () => { - const actual: StringUtils.FoundQuote | undefined = StringUtils.maybefindQuote(`_""`, 1); + const actual: StringUtils.FoundQuotes | undefined = StringUtils.findQuotes(`_""`, 1); - const expected: StringUtils.FoundQuote = { + const expected: StringUtils.FoundQuotes = { indexStart: 1, indexEnd: 3, quoteLength: 2, @@ -80,9 +80,9 @@ describe("StringUtils", () => { }); it(`_"a"`, () => { - const actual: StringUtils.FoundQuote | undefined = StringUtils.maybefindQuote(`_"a"`, 1); + const actual: StringUtils.FoundQuotes | undefined = StringUtils.findQuotes(`_"a"`, 1); - const expected: StringUtils.FoundQuote = { + const expected: StringUtils.FoundQuotes = { indexStart: 1, indexEnd: 4, quoteLength: 3, @@ -92,19 +92,19 @@ describe("StringUtils", () => { }); }); - describe(`maybeNormalizeNumber`, () => { + describe(`normalizeNumber`, () => { // tslint:disable-next-line: chai-vague-errors - it(`foo`, () => expect(StringUtils.maybeNormalizeNumber(`foo`)).to.be.undefined); - it(`1`, () => expect(StringUtils.maybeNormalizeNumber(`1`)).to.equal("1")); - it(`-1`, () => expect(StringUtils.maybeNormalizeNumber(`-1`)).to.equal("-1")); - it(`--1`, () => expect(StringUtils.maybeNormalizeNumber(`--1`)).to.equal("1")); - it(`+1`, () => expect(StringUtils.maybeNormalizeNumber(`+1`)).to.equal("1")); - it(`-+1`, () => expect(StringUtils.maybeNormalizeNumber(`-+1`)).to.equal("-1")); - it(`+-1`, () => expect(StringUtils.maybeNormalizeNumber(`+-1`)).to.equal("-1")); - it(`--1E1`, () => expect(StringUtils.maybeNormalizeNumber(`--1E1`)).to.equal("1E1")); - it(`0x1`, () => expect(StringUtils.maybeNormalizeNumber(`0x1`)).to.equal("0x1")); - it(`-0x1`, () => expect(StringUtils.maybeNormalizeNumber(`-0x1`)).to.equal("-0x1")); - it(`0X1`, () => expect(StringUtils.maybeNormalizeNumber(`0X1`)).to.equal("0x1")); - it(`-0X1`, () => expect(StringUtils.maybeNormalizeNumber(`-0X1`)).to.equal("-0x1")); + it(`foo`, () => expect(StringUtils.normalizeNumber(`foo`)).to.be.undefined); + it(`1`, () => expect(StringUtils.normalizeNumber(`1`)).to.equal("1")); + it(`-1`, () => expect(StringUtils.normalizeNumber(`-1`)).to.equal("-1")); + it(`--1`, () => expect(StringUtils.normalizeNumber(`--1`)).to.equal("1")); + it(`+1`, () => expect(StringUtils.normalizeNumber(`+1`)).to.equal("1")); + it(`-+1`, () => expect(StringUtils.normalizeNumber(`-+1`)).to.equal("-1")); + it(`+-1`, () => expect(StringUtils.normalizeNumber(`+-1`)).to.equal("-1")); + it(`--1E1`, () => expect(StringUtils.normalizeNumber(`--1E1`)).to.equal("1E1")); + it(`0x1`, () => expect(StringUtils.normalizeNumber(`0x1`)).to.equal("0x1")); + it(`-0x1`, () => expect(StringUtils.normalizeNumber(`-0x1`)).to.equal("-0x1")); + it(`0X1`, () => expect(StringUtils.normalizeNumber(`0X1`)).to.equal("0x1")); + it(`-0X1`, () => expect(StringUtils.normalizeNumber(`-0X1`)).to.equal("-0x1")); }); }); diff --git a/src/test/libraryTest/lexer/common.ts b/src/test/libraryTest/lexer/common.ts index ba786ab9..a8e8fd3d 100644 --- a/src/test/libraryTest/lexer/common.ts +++ b/src/test/libraryTest/lexer/common.ts @@ -126,7 +126,7 @@ export function assertGetLexOk(text: string): Lexer.State { const lexerState: Lexer.State = triedLex.value; if (Lexer.isErrorState(lexerState)) { - const errorLineMap: Lexer.ErrorLineMap = Assert.asDefined(Lexer.maybeErrorLineMap(lexerState)); + const errorLineMap: Lexer.ErrorLineMap = Assert.asDefined(Lexer.errorLineMap(lexerState)); const errorLines: ReadonlyArray = [...errorLineMap.keys()]; const details: { errorLines: ReadonlyArray } = { errorLines }; diff --git a/src/test/libraryTest/parser/columnNumber.ts b/src/test/libraryTest/parser/columnNumber.ts index ad5ea1da..e58bc4be 100644 --- a/src/test/libraryTest/parser/columnNumber.ts +++ b/src/test/libraryTest/parser/columnNumber.ts @@ -22,7 +22,7 @@ async function assertGetExpectedTokenKindError(text: string): Promise { const error: ParseError.ExpectedTokenKindError = await assertGetExpectedTokenKindError(text); - const foundToken: ParseError.TokenWithColumnNumber = Assert.asDefined(error.maybeFoundToken); + const foundToken: ParseError.TokenWithColumnNumber = Assert.asDefined(error.foundToken); expect(foundToken.token.positionStart.codeUnit).to.equal(codeUnit, "codeUnit"); expect(foundToken.token.positionStart.lineNumber).to.equal(lineNumber, "lineNumber"); diff --git a/src/test/libraryTest/parser/error.ts b/src/test/libraryTest/parser/error.ts index dd5ec3cc..94139e2f 100644 --- a/src/test/libraryTest/parser/error.ts +++ b/src/test/libraryTest/parser/error.ts @@ -18,13 +18,12 @@ import { TestAssertUtils } from "../../testUtils"; const DefaultSettingsWithStrict: Settings = { ...DefaultSettings, - createParseState: (lexerSnapshot: Lexer.LexerSnapshot, maybeOverrides: Partial | undefined) => { - maybeOverrides = maybeOverrides ?? {}; + createParseState: (lexerSnapshot: Lexer.LexerSnapshot, overrides: Partial | undefined) => { + overrides = overrides ?? {}; return ParseStateUtils.createState(lexerSnapshot, { - ...maybeOverrides, - disambiguationBehavior: - maybeOverrides.disambiguationBehavior ?? Disambiguation.DismabiguationBehavior.Strict, + ...overrides, + disambiguationBehavior: overrides.disambiguationBehavior ?? Disambiguation.DismabiguationBehavior.Strict, }); }, }; @@ -102,7 +101,7 @@ describe("Parser.Error", () => { ...DefaultSettings, parser: RecursiveDescentParser, // eslint-disable-next-line require-await - maybeParserEntryPointFn: async (state: ParseState, parser: Parser): Promise => + parserEntryPoint: async (state: ParseState, parser: Parser): Promise => parser.readIdentifier(state, parser, Ast.IdentifierContextKind.Value, undefined), }; diff --git a/src/test/libraryTest/parser/idUtils.ts b/src/test/libraryTest/parser/idUtils.ts index 51fecaf7..82a597ba 100644 --- a/src/test/libraryTest/parser/idUtils.ts +++ b/src/test/libraryTest/parser/idUtils.ts @@ -61,7 +61,7 @@ async function expectLinksMatch( xorNode = XorNodeUtils.boxAst(triedLexParse.ast); } else if (TaskUtils.isParseStageParseError(triedLexParse)) { nodeIdMapCollection = triedLexParse.nodeIdMapCollection; - xorNode = XorNodeUtils.boxContext(Assert.asDefined(triedLexParse.error.state.contextState.maybeRoot)); + xorNode = XorNodeUtils.boxContext(Assert.asDefined(triedLexParse.error.state.contextState.root)); } else { throw new Error(`expected TriedLexParse to be Ok`); } @@ -82,8 +82,8 @@ async function expectLinksMatch( contextIds: [], leafIds: new Set(), idsByNodeKind: new Map(), - maybeCancellationToken: undefined, - maybeInitialCorrelationId: undefined, + cancellationToken: undefined, + initialCorrelationId: undefined, traceManager: NoOpTraceManagerInstance, }; @@ -204,10 +204,10 @@ async function traverseVisitNode(state: TraverseState, xorNode: TXorNode): Promi state.contextIds.push(xorNode.node.id); } - const maybeNodeIdsByNodeKind: Set | undefined = state.idsByNodeKind.get(xorNode.node.kind); + const nodeIdsByNodeKind: Set | undefined = state.idsByNodeKind.get(xorNode.node.kind); - if (maybeNodeIdsByNodeKind !== undefined) { - maybeNodeIdsByNodeKind.add(xorNode.node.id); + if (nodeIdsByNodeKind !== undefined) { + nodeIdsByNodeKind.add(xorNode.node.id); } else { state.idsByNodeKind.set(xorNode.node.kind, new Set([xorNode.node.id])); } diff --git a/src/test/libraryTest/parser/nodeIdMapUtils.ts b/src/test/libraryTest/parser/nodeIdMapUtils.ts index b9d83855..0eac76eb 100644 --- a/src/test/libraryTest/parser/nodeIdMapUtils.ts +++ b/src/test/libraryTest/parser/nodeIdMapUtils.ts @@ -47,11 +47,11 @@ describe("nodeIdMapIterator", () => { expect(fieldSpecificationKeyValuePairs.length).to.equal(2); const firstKeyValuePair: FieldSpecificationKeyValuePair = fieldSpecificationKeyValuePairs[0]; - expect(firstKeyValuePair.maybeOptional).to.equal(undefined); + expect(firstKeyValuePair.optional).to.equal(undefined); expect(firstKeyValuePair.normalizedKeyLiteral).to.equal("foo"); const secondKeyValuePair: FieldSpecificationKeyValuePair = fieldSpecificationKeyValuePairs[1]; - expect(Boolean(secondKeyValuePair.maybeOptional)).to.equal(true); + expect(Boolean(secondKeyValuePair.optional)).to.equal(true); expect(secondKeyValuePair.normalizedKeyLiteral).to.equal("bar"); }); @@ -232,17 +232,17 @@ describe("nodeIdMapIterator", () => { expect(fieldSpecificationKeyValuePairs.length).to.equal(2); const firstKeyValuePair: FieldSpecificationKeyValuePair = fieldSpecificationKeyValuePairs[0]; - expect(firstKeyValuePair.maybeOptional).to.equal(undefined); + expect(firstKeyValuePair.optional).to.equal(undefined); expect(firstKeyValuePair.normalizedKeyLiteral).to.equal("foo"); const secondKeyValuePair: FieldSpecificationKeyValuePair = fieldSpecificationKeyValuePairs[1]; - expect(Boolean(secondKeyValuePair.maybeOptional)).to.equal(true); + expect(Boolean(secondKeyValuePair.optional)).to.equal(true); expect(secondKeyValuePair.normalizedKeyLiteral).to.equal("bar"); }); }); describe(`nodeIdMapUtils`, () => { - describe(`maybeInvokeExpressionIdentifier`, () => { + describe(`invokeExpressionIdentifier`, () => { it(`Ast`, async () => { const text: string = `Foo(1)`; const parseOk: Task.ParseTaskOk = await TestAssertUtils.assertGetLexParseOk(DefaultSettings, text); @@ -256,7 +256,7 @@ describe(`nodeIdMapUtils`, () => { const invokeExpressionNodeId: number = invokeExpressionNodeIds.values().next().value; const invokeExpressionIdentifier: XorNode = Assert.asDefined( - NodeIdMapUtils.maybeInvokeExpressionIdentifier(nodeIdMapCollection, invokeExpressionNodeId), + NodeIdMapUtils.invokeExpressionIdentifier(nodeIdMapCollection, invokeExpressionNodeId), ); XorNodeUtils.assertIsAstXor(invokeExpressionIdentifier); @@ -281,7 +281,7 @@ describe(`nodeIdMapUtils`, () => { const invokeExpressionNodeId: number = invokeExpressionNodeIds.values().next().value; const invokeExpressionIdentifier: XorNode = Assert.asDefined( - NodeIdMapUtils.maybeInvokeExpressionIdentifier(nodeIdMapCollection, invokeExpressionNodeId), + NodeIdMapUtils.invokeExpressionIdentifier(nodeIdMapCollection, invokeExpressionNodeId), ); XorNodeUtils.assertIsAstXor(invokeExpressionIdentifier); @@ -289,7 +289,7 @@ describe(`nodeIdMapUtils`, () => { }); }); - describe("maybeUnboxWrappedContent", () => { + describe("unboxWrappedContent", () => { it("Ast", async () => { const text: string = `[a = 1]`; const parseOk: Task.ParseTaskOk = await TestAssertUtils.assertGetLexParseOk(DefaultSettings, text); @@ -303,7 +303,7 @@ describe(`nodeIdMapUtils`, () => { const recordExpressionNodeId: number = recordExpressionNodeIds.values().next().value; XorNodeUtils.assertUnboxAstChecked( - Assert.asDefined(NodeIdMapUtils.maybeUnboxWrappedContent(nodeIdMapCollection, recordExpressionNodeId)), + Assert.asDefined(NodeIdMapUtils.unboxWrappedContent(nodeIdMapCollection, recordExpressionNodeId)), Ast.NodeKind.ArrayWrapper, ); }); @@ -326,7 +326,7 @@ describe(`nodeIdMapUtils`, () => { const recordExpressionNodeId: number = recordExpressionNodeIds.values().next().value; XorNodeUtils.assertUnboxAstChecked( - Assert.asDefined(NodeIdMapUtils.maybeUnboxWrappedContent(nodeIdMapCollection, recordExpressionNodeId)), + Assert.asDefined(NodeIdMapUtils.unboxWrappedContent(nodeIdMapCollection, recordExpressionNodeId)), Ast.NodeKind.ArrayWrapper, ); }); diff --git a/src/test/libraryTest/parser/simple.ts b/src/test/libraryTest/parser/simple.ts index 900532f8..8b42ddc8 100644 --- a/src/test/libraryTest/parser/simple.ts +++ b/src/test/libraryTest/parser/simple.ts @@ -35,8 +35,8 @@ async function collectAbridgeNodeFromAst(text: string): Promise( state, parseError.nodeIdMapCollection, - XorNodeUtils.boxContext(Assert.asDefined(parseError.parseState.contextState.maybeRoot)), + XorNodeUtils.boxContext(Assert.asDefined(parseError.parseState.contextState.root)), Traverse.VisitNodeStrategy.BreadthFirst, collectAbridgeXorNodeVisit, Traverse.assertGetAllXorChildren, @@ -100,8 +100,8 @@ async function assertGetNthNodeOfKind( nodeKind, nthCounter: 0, nthRequired, - maybeCancellationToken: undefined, - maybeInitialCorrelationId: undefined, + cancellationToken: undefined, + initialCorrelationId: undefined, traceManager: NoOpTraceManagerInstance, }; @@ -125,12 +125,12 @@ async function assertGetNthNodeOfKind( // eslint-disable-next-line require-await async function collectAbridgeAstNodeVisit(state: CollectAbridgeNodeState, node: Language.Ast.TNode): Promise { - state.result.push([node.kind, node.maybeAttributeIndex]); + state.result.push([node.kind, node.attributeIndex]); } // eslint-disable-next-line require-await async function collectAbridgeXorNodeVisit(state: CollectAbridgeNodeState, xorNode: TXorNode): Promise { - state.result.push([xorNode.node.kind, xorNode.node.maybeAttributeIndex]); + state.result.push([xorNode.node.kind, xorNode.node.attributeIndex]); } // eslint-disable-next-line require-await @@ -165,7 +165,7 @@ describe("Parser.AbridgedNode", () => { const customSettings: Settings = { ...DefaultSettings, parser: Parser.RecursiveDescentParser, - maybeParserEntryPointFn: Parser.RecursiveDescentParser.readParameterSpecificationList, + parserEntryPoint: Parser.RecursiveDescentParser.readParameterSpecificationList, }; const triedLexParseTask: Task.TriedLexParseTask = await TaskUtils.tryLexParse( diff --git a/src/test/libraryTest/tokenizer/common.ts b/src/test/libraryTest/tokenizer/common.ts index e3d15144..44fe19f7 100644 --- a/src/test/libraryTest/tokenizer/common.ts +++ b/src/test/libraryTest/tokenizer/common.ts @@ -29,7 +29,7 @@ export class Tokenizer implements TokensProvider { const lexerState: Lexer.State = { lines: [], locale: DefaultLocale, - maybeCancellationToken: undefined, + cancellationToken: undefined, }; return new TokenizerState(lexerState); diff --git a/src/test/libraryTest/type/typeUtils/nameOf.ts b/src/test/libraryTest/type/typeUtils/nameOf.ts index 9a806fe9..32dadf68 100644 --- a/src/test/libraryTest/type/typeUtils/nameOf.ts +++ b/src/test/libraryTest/type/typeUtils/nameOf.ts @@ -272,13 +272,13 @@ describe(`TypeUtils.nameOf`, () => { { isNullable: false, isOptional: false, - maybeType: undefined, + type: undefined, nameLiteral: "x", }, { isNullable: false, isOptional: true, - maybeType: undefined, + type: undefined, nameLiteral: "y", }, ], @@ -297,25 +297,25 @@ describe(`TypeUtils.nameOf`, () => { { isNullable: false, isOptional: false, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param1", }, { isNullable: true, isOptional: false, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param2", }, { isNullable: false, isOptional: true, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param3", }, { isNullable: true, isOptional: true, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param4", }, ], @@ -500,25 +500,25 @@ describe(`TypeUtils.nameOf`, () => { { isNullable: false, isOptional: false, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param1", }, { isNullable: true, isOptional: false, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param2", }, { isNullable: false, isOptional: true, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param3", }, { isNullable: true, isOptional: true, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param4", }, ], diff --git a/src/test/libraryTest/type/typeUtils/typeCheck.ts b/src/test/libraryTest/type/typeUtils/typeCheck.ts index 652ed6e6..e66c00e7 100644 --- a/src/test/libraryTest/type/typeUtils/typeCheck.ts +++ b/src/test/libraryTest/type/typeUtils/typeCheck.ts @@ -79,7 +79,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, ], @@ -107,7 +107,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: true, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, ], @@ -126,7 +126,7 @@ describe(`TypeUtils.typeCheck`, () => { expect(actual).to.deep.equal(expected); }); - it(`maybeType === null translates to any`, () => { + it(`type === null translates to any`, () => { const args: ReadonlyArray = [Language.Type.NumberInstance]; const definedFunction: Language.Type.DefinedFunction = TypeUtils.createDefinedFunction( @@ -135,7 +135,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: true, isOptional: false, - maybeType: undefined, + type: undefined, nameLiteral: "foo", }, ], @@ -154,7 +154,7 @@ describe(`TypeUtils.typeCheck`, () => { expect(actual).to.deep.equal(expected); }); - it(`paramter.maybeType === any allows any type`, () => { + it(`paramter.type === any allows any type`, () => { const args: ReadonlyArray = [Language.Type.NumberInstance]; const definedFunction: Language.Type.DefinedFunction = TypeUtils.createDefinedFunction( @@ -163,7 +163,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Any, + type: Language.Type.TypeKind.Any, nameLiteral: "foo", }, ], @@ -191,7 +191,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Text, + type: Language.Type.TypeKind.Text, nameLiteral: "foo", }, ], @@ -219,7 +219,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, ], @@ -250,13 +250,13 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Text, + type: Language.Type.TypeKind.Text, nameLiteral: "bar", }, ], @@ -284,7 +284,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, ], @@ -320,7 +320,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: true, isOptional: false, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, ], @@ -348,7 +348,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, ], @@ -376,7 +376,7 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, ], @@ -407,13 +407,13 @@ describe(`TypeUtils.typeCheck`, () => { { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Number, + type: Language.Type.TypeKind.Number, nameLiteral: "foo", }, { isNullable: false, isOptional: false, - maybeType: Language.Type.TypeKind.Text, + type: Language.Type.TypeKind.Text, nameLiteral: "bar", }, ], diff --git a/src/test/libraryTest/type/typeUtils/typeUtils.ts b/src/test/libraryTest/type/typeUtils/typeUtils.ts index 549f5942..5a9c477c 100644 --- a/src/test/libraryTest/type/typeUtils/typeUtils.ts +++ b/src/test/libraryTest/type/typeUtils/typeUtils.ts @@ -10,14 +10,14 @@ import { OrderedMap } from "../../../../powerquery-parser"; interface AbridgedType { readonly kind: Type.TypeKind; - readonly maybeExtendedKind: Type.ExtendedTypeKind | undefined; + readonly extendedKind: Type.ExtendedTypeKind | undefined; readonly isNullable: boolean; } function abridgedPrimitiveType(kind: Type.TypeKind, isNullable: boolean): AbridgedType { return { kind, - maybeExtendedKind: undefined, + extendedKind: undefined, isNullable, }; } @@ -25,7 +25,7 @@ function abridgedPrimitiveType(kind: Type.TypeKind, isNullable: boolean): Abridg function typeToAbridged(type: Type.TPowerQueryType): AbridgedType { return { kind: type.kind, - maybeExtendedKind: type.maybeExtendedKind, + extendedKind: type.extendedKind, isNullable: type.isNullable, }; } @@ -459,25 +459,25 @@ describe(`TypeUtils`, () => { { isNullable: false, isOptional: false, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param1", }, { isNullable: true, isOptional: false, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param2", }, { isNullable: false, isOptional: true, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param3", }, { isNullable: true, isOptional: true, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param4", }, ], @@ -647,25 +647,25 @@ describe(`TypeUtils`, () => { { isNullable: false, isOptional: false, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param1", }, { isNullable: true, isOptional: false, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param2", }, { isNullable: false, isOptional: true, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param3", }, { isNullable: true, isOptional: true, - maybeType: Type.TypeKind.Number, + type: Type.TypeKind.Number, nameLiteral: "param4", }, ], diff --git a/src/test/testUtils/assertUtils.ts b/src/test/testUtils/assertUtils.ts index c7769738..3d5d61df 100644 --- a/src/test/testUtils/assertUtils.ts +++ b/src/test/testUtils/assertUtils.ts @@ -53,7 +53,7 @@ async function assertGetTriedParse(settings: LexSettings & ParseSettings, text: const triedLex: Lexer.TriedLex = Lexer.tryLex(settings, text); Assert.isOk(triedLex); const lexerState: Lexer.State = triedLex.value; - Assert.isUndefined(Lexer.maybeErrorLineMap(lexerState)); + Assert.isUndefined(Lexer.errorLineMap(lexerState)); const triedSnapshot: Lexer.TriedLexerSnapshot = Lexer.trySnapshot(lexerState); Assert.isOk(triedSnapshot); diff --git a/src/test/testUtils/fileUtils.ts b/src/test/testUtils/fileUtils.ts index bfd4b91a..c5e145b5 100644 --- a/src/test/testUtils/fileUtils.ts +++ b/src/test/testUtils/fileUtils.ts @@ -58,9 +58,9 @@ export async function tryLexParse( return await TaskUtils.tryLexParse(settings, contents); } -function isDirectory(maybePath: string): boolean { +function isDirectory(path: string): boolean { // tslint:disable-next-line: non-literal-fs-path - return fs.statSync(maybePath).isDirectory(); + return fs.statSync(path).isDirectory(); } function isFile(filePath: string): boolean { diff --git a/style.md b/style.md index e376e49c..4e258d4e 100644 --- a/style.md +++ b/style.md @@ -1,12 +1,5 @@ # Style Notes -## Naming conventions - -- A function that can return undefined should have its name start with `maybe`, eg. `const maybeUser = maybeGetCurrentUser()` -- A variable that can be undefined should have its name start with `maybe`, eg. `const maybeUser = maybeGetCurrentUser()` -- A function that can return a result should have its name start with `try`, eg. `const triedUpdateUserPhoto = tryUpdateUserPhoto(user, photo)` -- A variable that is a Result should have its name start with `tried`, eg. `const triedUpdateUserPhoto = tryUpdateUserPhoto(user, photo)` - ## Exports - naive.ts, ast.ts, and naive.ts are excluded from the following rules