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 @@ -195,7 +195,9 @@ function evaluateImports(
}

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 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
42 changes: 31 additions & 11 deletions src/transpiler/transpiler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* eslint-disable @typescript-eslint/no-unused-vars */

Check failure on line 1 in src/transpiler/transpiler.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

';' expected.

Check failure on line 1 in src/transpiler/transpiler.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

',' expected.

Check failure on line 1 in src/transpiler/transpiler.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

An element access expression should take an argument.

Check failure on line 1 in src/transpiler/transpiler.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

',' expected.
import { generate } from 'astring'
import * as es from 'estree'
import { partition } from 'lodash'
Expand Down Expand Up @@ -63,7 +63,7 @@
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 @@
}

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 [
return [moduleName, { text, nodes: declNodes, namespaced }] satisfies [
string,
{
text: string
nodes: es.VariableDeclaration[]
nodes: (es.VariableDeclaration | es.ExpressionStatement)[]
namespaced: string
}
]
Expand Down
Loading