source-academy/js-slang

Add support for module types in Source Typed

zhaojj2209 opened this issue · 0 comments

Currently, all names imported from modules default to the any type (see below code snippet, specifically line 563):

function handleImportDeclarations(node: tsEs.Program) {
const importStmts: tsEs.ImportDeclaration[] = node.body.filter(
(stmt): stmt is tsEs.ImportDeclaration => stmt.type === 'ImportDeclaration'
)
if (importStmts.length === 0) {
return
}
const modules = memoizedGetModuleManifest()
const moduleList = Object.keys(modules)
importStmts.forEach(stmt => {
// Source only uses strings for import source value
const moduleName = stmt.source.value as string
if (!moduleList.includes(moduleName)) {
context.errors.push(new ModuleNotFoundError(moduleName, stmt))
}
stmt.specifiers.map(spec => {
if (spec.type !== 'ImportSpecifier') {
throw new TypecheckError(stmt, 'Unknown specifier type')
}
setType(spec.local.name, tAny, env)
})
})
}

In order to support typing of modules, we would need to design a system that allows for the importing of module types.

Possible implementation: every module should include a type declaration file containing a mapping of names to types. When encountering import statements, the type error checker can then retrieve the types from the type declaration file and conduct type checking using those types. If the type declaration file does not exist/any errors are encountered, the type error checker can default back to using the any type for all names in the module.