-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Transform numeric unions to types like string unions
- Loading branch information
Showing
8 changed files
with
264 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
import ts, {LiteralTypeNode, Node, NumericLiteral, PrefixUnaryExpression, SyntaxKind, UnionTypeNode} from "typescript"; | ||
import {escapeIdentifier} from "../../utils/strings.js"; | ||
import {CheckCoverageService, checkCoverageServiceKey} from "./CheckCoveragePlugin.js"; | ||
import {ConfigurationService, configurationServiceKey} from "./ConfigurationPlugin.js"; | ||
import {ConverterContext} from "../context.js"; | ||
import {createAnonymousDeclarationPlugin} from "./AnonymousDeclarationPlugin.js"; | ||
import {flatUnionTypes, isNullableType} from "./NullableUnionTypePlugin.js"; | ||
import {ifPresent, Render} from "../render.js"; | ||
import {InjectionService, injectionServiceKey} from "./InjectionPlugin.js"; | ||
import {InjectionType} from "../injection.js"; | ||
import {TypeScriptService, typeScriptServiceKey} from "./TypeScriptPlugin.js"; | ||
import {NamespaceInfoService, namespaceInfoServiceKey} from "./NamespaceInfoPlugin.js"; | ||
|
||
export function isNumericUnionType(node: ts.Node, context: ConverterContext): node is UnionTypeNode { | ||
return ( | ||
ts.isUnionTypeNode(node) | ||
&& flatUnionTypes(node, context).every(type => ( | ||
ts.isLiteralTypeNode(type) | ||
&& (ts.isNumericLiteral(type.literal) | ||
|| (ts.isPrefixUnaryExpression(type.literal) | ||
&& ts.isNumericLiteral(type.literal.operand))) | ||
)) | ||
) | ||
} | ||
|
||
export function isNullableNumericUnionType(node: ts.Node, context: ConverterContext): node is UnionTypeNode { | ||
if (!ts.isUnionTypeNode(node)) return false | ||
|
||
const types = flatUnionTypes(node, context) | ||
const nonNullableTypes = types.filter(type => !isNullableType(type)) | ||
|
||
return ( | ||
types.every(type => ( | ||
isNullableType(type) | ||
|| ( | ||
ts.isLiteralTypeNode(type) | ||
&& (ts.isNumericLiteral(type.literal) | ||
|| (ts.isPrefixUnaryExpression(type.literal) | ||
&& ts.isNumericLiteral(type.literal.operand))) | ||
) | ||
)) | ||
&& nonNullableTypes.length > 1 | ||
) | ||
} | ||
|
||
export function convertNumericUnionType( | ||
node: UnionTypeNode, | ||
name: string, | ||
isInlined: boolean, | ||
context: ConverterContext, | ||
render: Render, | ||
) { | ||
const checkCoverageService = context.lookupService<CheckCoverageService>(checkCoverageServiceKey) | ||
checkCoverageService?.cover(node) | ||
|
||
const configurationService = context.lookupService<ConfigurationService>(configurationServiceKey) | ||
if (configurationService === undefined) throw new Error("ConfigurationService required") | ||
const typeScriptService = context.lookupService<TypeScriptService>(typeScriptServiceKey) | ||
if (typeScriptService === undefined) throw new Error("TypeScriptService required") | ||
const namespaceInfoService = context.lookupService<NamespaceInfoService>(namespaceInfoServiceKey) | ||
const injectionService = context.lookupService<InjectionService>(injectionServiceKey) | ||
|
||
const types = flatUnionTypes(node, context) | ||
|
||
const nonNullableTypes = types.filter(type => !isNullableType(type)) | ||
const nullableTypes = types.filter(type => isNullableType(type)) | ||
|
||
const {unionNameMapper} = configurationService.configuration | ||
|
||
const entries = nonNullableTypes | ||
.filter((type): type is LiteralTypeNode => ts.isLiteralTypeNode(type)) | ||
.map(type => { | ||
checkCoverageService?.cover(type) | ||
|
||
return type.literal | ||
}) | ||
.filter((literal): literal is NumericLiteral | PrefixUnaryExpression => | ||
ts.isNumericLiteral(literal) | ||
|| (ts.isPrefixUnaryExpression(literal) | ||
&& ts.isNumericLiteral(literal.operand)) | ||
) | ||
.map(literal => { | ||
checkCoverageService?.cover(literal) | ||
|
||
const value = typeScriptService.printNode(literal) | ||
|
||
for (const [namePattern, valueMapping] of Object.entries(unionNameMapper)) { | ||
const nameRegexp = new RegExp(namePattern) | ||
if (nameRegexp.test(name)) { | ||
for (const [valuePattern, key] of Object.entries(valueMapping)) { | ||
const valueRegexp = new RegExp(valuePattern) | ||
if (valueRegexp.test(value)) { | ||
if (!key) { | ||
throw new Error("Configured key in unionNameMapper must not be empty") | ||
} | ||
return [key, value] as const | ||
} | ||
} | ||
} | ||
} | ||
|
||
if (ts.isNumericLiteral(literal)) { | ||
return [`VALUE_${toIdentifierPart(typeScriptService, literal)}`, value] as const | ||
} else { | ||
return [`VALUE_MINUS_${toIdentifierPart(typeScriptService, literal.operand)}`, value] as const | ||
} | ||
}) | ||
|
||
const keyDisambiguators: Map<string, number> = new Map() | ||
const disambiguatedEntries = entries.map(([key, value]) => { | ||
const keyDisambiguator = (keyDisambiguators.get(key) ?? 0) + 1 | ||
keyDisambiguators.set(key, keyDisambiguator) | ||
if (keyDisambiguator > 1) { | ||
return [escapeIdentifier(`${key}_${keyDisambiguator}`), value] as const; | ||
} else { | ||
return [escapeIdentifier(key), value] as const; | ||
} | ||
}); | ||
|
||
const body = disambiguatedEntries | ||
.map(([key, value]) => ( | ||
` | ||
@seskar.js.JsValue("${value}") | ||
val ${key}: ${name} | ||
`.trim() | ||
)) | ||
.join("\n") | ||
|
||
const heritageInjections = injectionService?.resolveInjections(node, InjectionType.HERITAGE_CLAUSE, context, render) | ||
|
||
const namespace = typeScriptService.findClosest(node, ts.isModuleDeclaration) | ||
|
||
let externalModifier = "external " | ||
|
||
if (isInlined && namespace !== undefined && namespaceInfoService?.resolveNamespaceStrategy(namespace) === "object") { | ||
externalModifier = "" | ||
} | ||
|
||
const injectedHeritageClauses = heritageInjections | ||
?.filter(Boolean) | ||
?.join(", ") | ||
|
||
const declaration = ` | ||
sealed ${externalModifier}interface ${name}${ifPresent(injectedHeritageClauses, it => ` : ${it}`)} { | ||
companion object { | ||
${body} | ||
} | ||
} | ||
`.trim() | ||
|
||
const nullable = nullableTypes.length > 0 | ||
|
||
return { | ||
declaration, | ||
nullable, | ||
} | ||
} | ||
|
||
function toIdentifierPart(typeScriptService: TypeScriptService, node: Node): string { | ||
return typeScriptService.printNode(node).replaceAll(".", "_") | ||
} | ||
|
||
export const numericUnionTypePlugin = createAnonymousDeclarationPlugin( | ||
(node, context, render) => { | ||
if (!isNullableNumericUnionType(node, context)) return null | ||
|
||
const name = context.resolveName(node) | ||
|
||
const {declaration, nullable} = convertNumericUnionType(node, name, false, context, render) | ||
|
||
const reference = nullable ? `${name}?` : name | ||
|
||
return {name, declaration, reference}; | ||
} | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
// Generated by Karakum - do not modify it manually! | ||
|
||
@file:JsModule("sandbox-base/union/numericEnum") | ||
@file:Suppress( | ||
"NON_EXTERNAL_DECLARATION_IN_INAPPROPRIATE_FILE", | ||
) | ||
|
||
package sandbox.base.union | ||
|
||
external fun compare(): CompareResult | ||
|
||
sealed external interface AnotherCompareResult { | ||
companion object { | ||
@seskar.js.JsValue("-1") | ||
val VALUE_MINUS_1: AnotherCompareResult | ||
@seskar.js.JsValue("0") | ||
val VALUE_0: AnotherCompareResult | ||
@seskar.js.JsValue("1") | ||
val VALUE_1: AnotherCompareResult | ||
} | ||
} | ||
|
||
external fun foo(param: FooParam) | ||
|
||
sealed external interface AnotherCompareResult2 { | ||
companion object { | ||
@seskar.js.JsValue("-1") | ||
val RESULT: AnotherCompareResult2 | ||
@seskar.js.JsValue("0") | ||
val RESULT_2: AnotherCompareResult2 | ||
@seskar.js.JsValue("1") | ||
val RESULT_3: AnotherCompareResult2 | ||
} | ||
} | ||
|
||
sealed external interface AnotherCompareResult3 { | ||
companion object { | ||
@seskar.js.JsValue("-1.0") | ||
val VALUE_MINUS_1_0: AnotherCompareResult3 | ||
@seskar.js.JsValue("0") | ||
val VALUE_0: AnotherCompareResult3 | ||
@seskar.js.JsValue("1.") | ||
val VALUE_1_: AnotherCompareResult3 | ||
} | ||
} | ||
sealed external interface CompareResult { | ||
companion object { | ||
@seskar.js.JsValue("-1") | ||
val VALUE_MINUS_1: CompareResult | ||
@seskar.js.JsValue("0") | ||
val VALUE_0: CompareResult | ||
@seskar.js.JsValue("1") | ||
val VALUE_1: CompareResult | ||
} | ||
} | ||
|
||
sealed external interface FooParam { | ||
companion object { | ||
@seskar.js.JsValue("-1") | ||
val VALUE_MINUS_1: FooParam | ||
@seskar.js.JsValue("0") | ||
val VALUE_0: FooParam | ||
@seskar.js.JsValue("1") | ||
val VALUE_1: FooParam | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
export declare function compare(): -1 | 0 | 1 | ||
|
||
export declare type AnotherCompareResult = -1 | 0 | 1 | ||
|
||
export function foo(param: -1 | 0 | 1); | ||
|
||
export declare type AnotherCompareResult2 = -1 | 0 | 1 | ||
|
||
export declare type AnotherCompareResult3 = -1.0 | 0 | 1. |