Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix incorrect function.name for aliased imports #1484

Draft
wants to merge 12 commits into
base: master
Choose a base branch
from
4 changes: 3 additions & 1 deletion src/ec-evaluator/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,9 @@
}

declareIdentifier(context, spec.local.name, node, environment)
defineVariable(context, spec.local.name, functions[spec.imported.name], true, node)
const importedObj = functions[spec.imported.name]
Object.defineProperty(importedObj, 'name', { value: spec.local.name })
defineVariable(context, spec.local.name, importedObj, true, node)
}
}
})
Expand All @@ -211,7 +213,7 @@
* @returns The corresponding promise.
*/
export function ECEResultPromise(context: Context, value: Value): Promise<Result> {
return new Promise((resolve, reject) => {

Check warning on line 216 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'reject' is defined but never used. Allowed unused args must match /^_/u
if (value instanceof ECEBreak) {
resolve({ status: 'suspended-ec-eval', context })
} else if (value instanceof ECError) {
Expand Down Expand Up @@ -363,7 +365,7 @@
command: es.WhileStatement,
context: Context,
agenda: Agenda,
stash: Stash

Check warning on line 368 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
) {
if (hasBreakStatement(command.body as es.BlockStatement)) {
agenda.push(instr.breakMarkerInstr(command))
Expand Down Expand Up @@ -442,7 +444,7 @@
}
},

IfStatement: function (command: es.IfStatement, context: Context, agenda: Agenda, stash: Stash) {

Check warning on line 447 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
agenda.push(...reduceConditional(command))
},

Expand Down Expand Up @@ -514,7 +516,7 @@
command: es.ContinueStatement,
context: Context,
agenda: Agenda,
stash: Stash

Check warning on line 519 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
) {
agenda.push(instr.contInstr(command))
},
Expand All @@ -523,7 +525,7 @@
command: es.BreakStatement,
context: Context,
agenda: Agenda,
stash: Stash

Check warning on line 528 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
) {
agenda.push(instr.breakInstr(command))
},
Expand Down Expand Up @@ -569,7 +571,7 @@
command: es.MemberExpression,
context: Context,
agenda: Agenda,
stash: Stash

Check warning on line 574 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
) {
agenda.push(instr.arrAccInstr(command))
agenda.push(command.property)
Expand All @@ -580,7 +582,7 @@
command: es.ConditionalExpression,
context: Context,
agenda: Agenda,
stash: Stash

Check warning on line 585 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
) {
agenda.push(...reduceConditional(command))
},
Expand Down Expand Up @@ -651,7 +653,7 @@
* Instructions
*/

[InstrType.RESET]: function (command: Instr, context: Context, agenda: Agenda, stash: Stash) {

Check warning on line 656 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
// Keep pushing reset instructions until marker is found.
const cmdNext: AgendaItem | undefined = agenda.pop()
if (cmdNext && (isNode(cmdNext) || cmdNext.instrType !== InstrType.MARKER)) {
Expand Down Expand Up @@ -936,7 +938,7 @@
stash.push(value)
},

[InstrType.CONTINUE]: function (command: Instr, context: Context, agenda: Agenda, stash: Stash) {

Check warning on line 941 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
const next = agenda.pop() as AgendaItem
if (isInstr(next) && next.instrType == InstrType.CONTINUE_MARKER) {
// Encountered continue mark, stop popping
Expand All @@ -951,7 +953,7 @@

[InstrType.CONTINUE_MARKER]: function () {},

[InstrType.BREAK]: function (command: Instr, context: Context, agenda: Agenda, stash: Stash) {

Check warning on line 956 in src/ec-evaluator/interpreter.ts

View workflow job for this annotation

GitHub Actions / build

'stash' is defined but never used. Allowed unused args must match /^_/u
const next = agenda.pop() as AgendaItem
if (isInstr(next) && next.instrType == InstrType.BREAK_MARKER) {
// Encountered break mark, stop popping
Expand Down
4 changes: 3 additions & 1 deletion src/infiniteLoops/instrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,9 @@ async function handleImports(programs: es.Program[]): Promise<[string, string[]]
}
)
program.body = (importsToAdd as es.Program['body']).concat(otherNodes)
const importedNames = importsToAdd.flatMap(node =>
const importedNames = (
importsToAdd.filter(node => node.type === 'VariableDeclaration') as es.VariableDeclaration[]
).flatMap(node =>
Comment on lines +590 to +592
Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure if there's a less hacky way to handle this...

node.declarations.map(
decl => ((decl.init as es.MemberExpression).object as es.Identifier).name
)
Expand Down
1 change: 1 addition & 0 deletions src/infiniteLoops/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ function prepareBuiltins(oldBuiltins: Map<string, any>) {
}
}
newBuiltins.set('undefined', undefined)
newBuiltins.set('Object', Object)
Copy link
Member Author

Choose a reason for hiding this comment

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

Not sure if this is the right move; what are the implications of this? Perhaps someone could verify/advise.

Copy link
Member

Choose a reason for hiding this comment

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

I see that you are updating the name property in the function object. But here, are you trying to add the name "Object" to the names of builtins that are visible from Source programs?

return newBuiltins
}

Expand Down
2 changes: 1 addition & 1 deletion src/runner/sourceRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ export async function sourceRunner(
return runNative(program, context, theOptions)
}

return runInterpreter(program!, context, theOptions)
return runInterpreter(program, context, theOptions)
}

export async function sourceFilesRunner(
Expand Down
60 changes: 53 additions & 7 deletions src/transpiler/__tests__/modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,30 @@ import { transformImportDeclarations, transpile } from '../transpiler'
jest.mock('../../modules/moduleLoaderAsync')
jest.mock('../../modules/moduleLoader')

// One import declaration is transformed into two AST nodes
const IMPORT_DECLARATION_NODE_COUNT = 2

test('Transform import declarations to correct number of nodes', async () => {
const code = stripIndent`
import { foo } from "one_module";
`
const context = mockContext(Chapter.SOURCE_4)
const program = parse(code, context)!
const [, importNodes] = await transformImportDeclarations(program, new Set<string>(), {
wrapSourceModules: true,
loadTabs: false,
checkImports: true
})
expect(importNodes.length).toEqual(IMPORT_DECLARATION_NODE_COUNT)
})

test('Transform import declarations into variable declarations', async () => {
const code = stripIndent`
import { foo } from "one_module";
import { bar } from "another_module";
foo(bar);
`
const identifiers = ['foo', 'bar'] as const
const context = mockContext(Chapter.SOURCE_4)
const program = parse(code, context)!
const [, importNodes] = await transformImportDeclarations(program, new Set<string>(), {
Expand All @@ -25,11 +43,33 @@ test('Transform import declarations into variable declarations', async () => {
checkImports: true
})

expect(importNodes[0].type).toBe('VariableDeclaration')
expect((importNodes[0].declarations[0].id as Identifier).name).toEqual('foo')
identifiers.forEach((ident, index) => {
const idx = IMPORT_DECLARATION_NODE_COUNT * index
expect(importNodes[idx].type).toBe('VariableDeclaration')
const node = importNodes[idx] as VariableDeclaration
expect((node.declarations[0].id as Identifier).name).toEqual(ident)
})
})

test('Transform import declarations with correctly aliased names (expression statements)', async () => {
const code = stripIndent`
import { foo } from "one_module";
import { bar as alias } from "another_module";
foo(bar);
`
const aliases = ['foo', 'alias'] as const
const context = mockContext(Chapter.SOURCE_4)
const program = parse(code, context)!
const [, importNodes] = await transformImportDeclarations(program, new Set<string>(), {
wrapSourceModules: true,
loadTabs: false,
checkImports: true
})

expect(importNodes[1].type).toBe('VariableDeclaration')
expect((importNodes[1].declarations[0].id as Identifier).name).toEqual('bar')
aliases.forEach((_, index) => {
const idx = IMPORT_DECLARATION_NODE_COUNT * index + 1
expect(importNodes[idx].type).toBe('ExpressionStatement')
})
})

test('Transpiler accounts for user variable names when transforming import statements', async () => {
Expand All @@ -54,7 +94,10 @@ test('Transpiler accounts for user variable names when transforming import state

expect(importNodes[0].type).toBe('VariableDeclaration')
expect(
((importNodes[0].declarations[0].init as MemberExpression).object as Identifier).name
(
((importNodes[0] as VariableDeclaration).declarations[0].init as MemberExpression)
.object as Identifier
).name
).toEqual('__MODULE__1')

expect(varDecl0.type).toBe('VariableDeclaration')
Expand All @@ -63,9 +106,12 @@ test('Transpiler accounts for user variable names when transforming import state
expect(varDecl1.type).toBe('VariableDeclaration')
expect(((varDecl1 as VariableDeclaration).declarations[0].init as Literal).value).toEqual('test1')

expect(importNodes[1].type).toBe('VariableDeclaration')
expect(importNodes[2].type).toBe('VariableDeclaration')
expect(
((importNodes[1].declarations[0].init as MemberExpression).object as Identifier).name
(
((importNodes[2] as VariableDeclaration).declarations[0].init as MemberExpression)
.object as Identifier
).name
).toEqual('__MODULE__3')
})

Expand Down
40 changes: 30 additions & 10 deletions src/transpiler/transpiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export async function transformImportDeclarations(
context?: Context,
nativeId?: es.Identifier,
useThis: boolean = false
): Promise<[string, es.VariableDeclaration[], es.Program['body']]> {
): Promise<[string, (es.VariableDeclaration | es.ExpressionStatement)[], es.Program['body']]> {
const [importNodes, otherNodes] = partition(program.body, isImportDeclaration)

if (importNodes.length === 0) return ['', [], otherNodes]
Expand Down Expand Up @@ -109,29 +109,49 @@ export async function transformImportDeclarations(
}

const declNodes = nodes.flatMap(({ specifiers }) =>
specifiers.map(spec => {
specifiers.flatMap(spec => {
assert(spec.type === 'ImportSpecifier', `Expected ImportSpecifier, got ${spec.type}`)

if (checkImports && !(spec.imported.name in docs!)) {
throw new UndefinedImportError(spec.imported.name, moduleName, spec)
}

// Convert each import specifier to its corresponding local variable declaration
return create.constantDeclaration(
spec.local.name,
create.memberExpression(
create.identifier(`${useThis ? 'this.' : ''}${namespaced}`),
spec.imported.name
return [
// Convert each import specifier to its corresponding local variable declaration
create.constantDeclaration(
spec.local.name,
create.memberExpression(
create.identifier(`${useThis ? 'this.' : ''}${namespaced}`),
spec.imported.name
)
),
// Update the specifier's name property with the new name. This is so that calling
// `function.name` will return the aliased name. Equivalent to:
// Object.defineProperty(spec.imported.name, 'name', { value: spec.local.name });
create.expressionStatement(
create.callExpression(
create.memberExpression(create.identifier('Object'), 'defineProperty'),
[
create.memberExpression(
create.identifier(`${useThis ? 'this.' : ''}${namespaced}`),
spec.imported.name
),
create.literal('name'),
create.objectExpression([
create.property('value', create.literal(spec.local.name))
])
]
)
)
)
]
})
)

return [moduleName, { text, nodes: declNodes, namespaced }] as [
string,
{
text: string
nodes: es.VariableDeclaration[]
nodes: (es.VariableDeclaration | es.ExpressionStatement)[]
namespaced: string
}
]
Expand Down