Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Method.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ interface EtsMethod : Base, CommonMethod {
val signature: EtsMethodSignature
val typeParameters: List<EtsType>

val isObjectLiteralMethod: Boolean
get() = hasModifier(EtsModifier.OBJECT_LITERAL_METHOD)

/** Null preserves unknown strictness for legacy or synthetic methods. */
val isStrictMode: Boolean?
get() = null
Expand Down
3 changes: 2 additions & 1 deletion jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Modifiers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ enum class EtsModifier(val value: Int, val string: String) {
READONLY(value = 1 shl 11, string = "readonly"),
OUT(value = 1 shl 12, string = "out"),
OVERRIDE(value = 1 shl 13, string = "override"),
DECLARE(value = 1 shl 14, string = "declare");
DECLARE(value = 1 shl 14, string = "declare"),
OBJECT_LITERAL_METHOD(value = 1 shl 15, string = "object-literal-method"),
}

interface WithModifiers {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -592,17 +592,24 @@ class EtsTsFrontendTest {
}

@Test
fun `named object method is unsupported before allocation through JSON conversion`() {
fun `named object method retains its callable own property through JSON conversion`() {
val dto = runFrontend("export function value() { return { x: 1, method() { return this.x; } }; }")
val serialized = Json { serializersModule = dtoModule }.encodeToString(dto)
val roundTripped = EtsFileDto.loadFromJson(serialized)
val stmts = roundTripped.classes.single { it.signature.name == DEFAULT_ARK_CLASS_NAME }
.methods.single { it.signature.name == "value" }.body!!.cfg.blocks.flatMap { it.stmts }

assertTrue(stmts.filterIsInstance<AssignStmtDto>().any { it.right is RawValueDto })
assertTrue(stmts.filterIsInstance<AssignStmtDto>().none { it.right is NewExprDto })
assertTrue(stmts.none { it is DefineDataPropertyStmtDto })
assertTrue(roundTripped.classes.none { it.signature.name.startsWith("%AC") })
assertTrue(stmts.filterIsInstance<AssignStmtDto>().none { it.right is RawValueDto })
assertTrue(stmts.filterIsInstance<AssignStmtDto>().any { it.right is NewExprDto })
val property = stmts.filterIsInstance<DefineDataPropertyStmtDto>()
.single { (it.key as? ConstantDto)?.value == "method" }
val storedMethod = assertIs<LocalDto>(property.value)
val storedType = assertIs<FunctionTypeDto>(storedMethod.type)
val owner = roundTripped.toEtsFile().classes.single { it.name == DEFAULT_ARK_CLASS_NAME }
val lifted = owner.methods.single { it.name == storedType.signature.name }

assertTrue(lifted.isObjectLiteralMethod)
assertTrue(lifted.parameters.single().type is EtsLexicalEnvType)
}

@Test
Expand Down
1 change: 1 addition & 0 deletions jacodb-ets/ts-frontend/src/dto/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export const Modifier = {
OUT: 1 << 12,
OVERRIDE: 1 << 13,
DECLARE: 1 << 14,
OBJECT_LITERAL_METHOD: 1 << 15,
} as const;

export type ModifierName = keyof typeof Modifier;
Expand Down
13 changes: 13 additions & 0 deletions jacodb-ets/ts-frontend/src/lowering/astUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,3 +503,16 @@ export function scopeFunctionType(ctx: LoweringContext, decl: ts.FunctionDeclara
}
return type;
}

export function unwrapTransparentExpression(node: ts.Expression): ts.Expression {
while (
ts.isParenthesizedExpression(node)
|| ts.isAsExpression(node)
|| ts.isTypeAssertionExpression(node)
|| ts.isNonNullExpression(node)
|| ts.isSatisfiesExpression(node)
) {
node = node.expression;
}
return node;
}
3 changes: 3 additions & 0 deletions jacodb-ets/ts-frontend/src/lowering/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ export function syntaxKindName(kind: ts.SyntaxKind): string {
return SYNTAX_KIND_NAMES[kind] ?? ts.SyntaxKind[kind] ?? String(kind);
}

/** Signals that a source construct must fall back to an unsupported IR node. */
export class LoweringError extends Error {}

function snippet(node: ts.Node): string {
try {
return node.getText().slice(0, 200);
Expand Down
126 changes: 87 additions & 39 deletions jacodb-ets/ts-frontend/src/lowering/exprLowering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ import {
ANONYMOUS_METHOD_PREFIX,
ClassCategory,
CONSTRUCTOR_NAME,
Modifier,
PATTERN_PARAMETER_PREFIX,
} from "../dto/constants";
import { FieldDto } from "../dto/model";
import { bindingIdentifier, buildParameters, BuiltParameters, classLikeDeclarationOf, memberName, modifiersOf, returnTypeOf, unsupportedClassDeclarationReason } from "./astUtils";
import { bindingIdentifier, buildParameters, BuiltParameters, classLikeDeclarationOf, memberName, modifiersOf, returnTypeOf, unsupportedClassDeclarationReason, unwrapTransparentExpression } from "./astUtils";
import { BinaryOp, RelationOp, UnaryOp } from "../dto/ops";
import {
ClassSignatureDto,
Expand Down Expand Up @@ -67,7 +68,7 @@ import {
StaticFieldRefDto,
ValueDto,
} from "../dto/values";
import { syntaxKindName, unsupportedValue } from "./diagnostics";
import { LoweringError, syntaxKindName, unsupportedStmt, unsupportedValue } from "./diagnostics";
import { MethodContext } from "./methodBuilder";
import { IteratorLowerer, throwRuntimeError } from "./iteratorLowering";

Expand Down Expand Up @@ -120,8 +121,10 @@ const COMPOUND_ASSIGN_BY_SYNTAX: Partial<Record<ts.SyntaxKind, BinaryOp>> = {
[ts.SyntaxKind.QuestionQuestionEqualsToken]: "??",
};

/** Thrown internally for constructs the current milestone cannot lower; callers degrade to Raw*. */
export class LoweringError extends Error {}
export { LoweringError } from "./diagnostics";

type LiftedFunction = ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration
| ts.GetAccessorDeclaration | ts.MethodDeclaration;

/** Lowers the body of a nested function (closure / object-literal method) into a fresh MethodContext. */
export type FunctionBodyLowerer = (
Expand Down Expand Up @@ -1752,7 +1755,7 @@ export class ExprLowerer {
return this.lowerClosure(node);
}

private lowerClosure(node: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | ts.GetAccessorDeclaration): LocalDto {
private lowerClosure(node: LiftedFunction): LocalDto {
if (this.lowerFunctionBody === undefined) {
throw new LoweringError("closure in a context without a body lowerer");
}
Expand All @@ -1773,7 +1776,9 @@ export class ExprLowerer {
const { parameters, prologueParams } = buildParameters(this.m.ctx, node);
const returnType = returnTypeOf(this.m.ctx, node);
const baseSignature: MethodSignatureDto = { declaringClass, name, parameters, returnType };
const capturedIdentifiers = collectCapturedIdentifiers(node, this.m.checker);
const objectMethod = ts.isMethodDeclaration(node);
const unsupportedBody = objectMethod ? unsupportedObjectMethodBody(node, this.m.checker) : undefined;
const capturedIdentifiers = unsupportedBody === undefined ? collectCapturedIdentifiers(node, this.m.checker) : [];
const capturesUninitializedParameter = capturedIdentifiers.some((identifier) =>
this.m.isUninitializedParameter(identifier),
);
Expand All @@ -1793,7 +1798,9 @@ export class ExprLowerer {
let environment:
| { name: string; type: Extract<TypeDto, { _: "LexicalEnvType" }> }
| undefined;
if (captures.length > 0 || lexicalThis !== undefined) {
// Every evaluation of a method definition creates a function, even
// when there are no captured values to put in its environment.
if (objectMethod || captures.length > 0 || lexicalThis !== undefined) {
const capturedLocals = captures.map((capture) => ({
name: capture.outerLocal.name,
type: capture.outerLocal.type,
Expand Down Expand Up @@ -1825,18 +1832,24 @@ export class ExprLowerer {
name,
ts.isArrowFunction(node) && this.m.isStaticMethod,
);
this.lowerFunctionBody(closureContext, node.body, (afterParameter) => {
if (environment === undefined) {
closureContext.emitPrologue(prologueParams, afterParameter);
} else {
closureContext.emitClosurePrologue(
environment.name, environment.type, captures, prologueParams, afterParameter, lexicalThis,
);
}
});
if (unsupportedBody !== undefined) {
this.m.diagnostics.warn(node, unsupportedBody);
closureContext.withOrigin(node, () => closureContext.cfg.emit(unsupportedStmt(node)));
} else {
this.lowerFunctionBody(closureContext, node.body, (afterParameter) => {
if (environment === undefined) {
closureContext.emitPrologue(prologueParams, afterParameter);
} else {
closureContext.emitClosurePrologue(
environment.name, environment.type, captures, prologueParams, afterParameter, lexicalThis,
);
}
});
}
const modifiers = modifiersOf(node) | (objectMethod ? Modifier.OBJECT_LITERAL_METHOD : 0);
registry.methods.push({
signature,
modifiers: modifiersOf(node),
modifiers,
decorators: [],
isStrictMode: isStrictMode(node),
body: closureContext.build(),
Expand All @@ -1853,11 +1866,6 @@ export class ExprLowerer {
if (this.lowerFunctionBody === undefined) {
throw new LoweringError("object literal in a context without a body lowerer");
}
const hasUnmaterializedMethod = node.properties.some(ts.isMethodDeclaration);
if (hasUnmaterializedMethod) {
throw new LoweringError("object literal method needs a per-evaluation callable own property");
}

const registry = this.m.ctx.anonymous;
const name = `${ANONYMOUS_CLASS_PREFIX}${registry.nextClassId++}$${this.m.methodName}`;
const signature: ClassSignatureDto = {
Expand Down Expand Up @@ -1905,12 +1913,16 @@ export class ExprLowerer {
excludedKeys: [],
throwOnNullishSource: false,
});
} else if (ts.isGetAccessorDeclaration(property)) {
} else if (ts.isGetAccessorDeclaration(property) || ts.isMethodDeclaration(property)) {
const key = ts.isComputedPropertyName(property.name)
? this.lowerPropertyKey(property.name.expression)
: constant(memberName(property.name), STRING_TYPE);
const getter = this.lowerClosure(property);
this.m.cfg.emit({ _: "DefineAccessorStmt", target: temp, key, getter });
const callable = this.lowerClosure(property);
if (ts.isMethodDeclaration(property)) {
this.m.cfg.emit({ _: "DefineDataPropertyStmt", target: temp, key, value: callable });
} else {
this.m.cfg.emit({ _: "DefineAccessorStmt", target: temp, key, getter: callable });
}
} else {
// Setters remain separately unsupported.
throw new LoweringError(`object literal member: ${syntaxKindName(property.kind)}`);
Expand Down Expand Up @@ -2257,6 +2269,55 @@ function numericConstantText(node: ts.NumericLiteral): string {
return Number.isFinite(Number(node.text)) ? node.text : node.getText();
}

function unsupportedObjectMethodBody(
method: ts.MethodDeclaration,
checker: ts.TypeChecker,
): string | undefined {
if (method.asteriskToken !== undefined) return "object literal generator method calls are not represented in EtsIR";

const pending: ts.Node[] = [...method.parameters];
if (method.body !== undefined) pending.push(method.body);
while (pending.length > 0) {
const node = pending.pop()!;
if (ts.isTypeNode(node)) continue;
if (node.kind === ts.SyntaxKind.SuperKeyword) {
return "object literal method requires [[HomeObject]] for super";
}
if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.NewKeyword) {
return "object literal method new.target is not represented in EtsIR";
}
if (ts.isIdentifier(node) && node.text === "arguments") {
const parent = node.parent;
const propertyName = (ts.isPropertyAccessExpression(parent) || ts.isPropertyAssignment(parent))
&& parent.name === node;
if (!propertyName && checker.getSymbolAtLocation(node)?.declarations === undefined) {
return "object literal method arguments object is not represented in EtsIR";
}
}

// Arrows inherit these bindings from the method. Other functions have
// independent bodies, but their computed keys run in this lexical scope.
if (ts.isFunctionLike(node) && !ts.isArrowFunction(node)) {
const name = node.name;
if (name !== undefined && ts.isComputedPropertyName(name)) pending.push(name.expression);
continue;
}
if (ts.isClassLike(node)) {
for (const clause of node.heritageClauses ?? []) {
for (const type of clause.types) pending.push(type.expression);
}
for (const member of node.members) {
const name = member.name;
if (name !== undefined && ts.isComputedPropertyName(name)) pending.push(name.expression);
}
continue;
}

ts.forEachChild(node, (child) => { pending.push(child); });
}
return undefined;
}

/** Nested arrows share the receiver; ordinary functions and class members introduce their own. */
function usesLexicalThis(arrow: ts.ArrowFunction): boolean {
let found = false;
Expand Down Expand Up @@ -2400,19 +2461,6 @@ function containsPossibleSideEffect(node: ts.Node): boolean {


/** Erase syntax that leaves an expression's runtime value unchanged. */
function unwrapTransparentExpression(node: ts.Expression): ts.Expression {
while (
ts.isParenthesizedExpression(node)
|| ts.isAsExpression(node)
|| ts.isTypeAssertionExpression(node)
|| ts.isNonNullExpression(node)
|| ts.isSatisfiesExpression(node)
) {
node = node.expression;
}
return node;
}

/** Identifier binding written by an assignment or an increment/decrement, if any. */
function assignmentTarget(node: ts.Node): ts.Identifier | undefined {
if (ts.isBinaryExpression(node) && (
Expand Down Expand Up @@ -2446,7 +2494,7 @@ function sameBinding(
* are excluded.
*/
function collectCapturedIdentifiers(
closure: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | ts.GetAccessorDeclaration,
closure: LiftedFunction,
checker: ts.TypeChecker,
): ts.Identifier[] {
if (closure.body === undefined) return [];
Expand Down
Loading
Loading