Skip to content

Add support for Source modules/functions to Full TypeScript chapter #1400

Open
@zhaojj2209

Description

@zhaojj2209

Currently, the Full TypeScript chapter uses the below workaround for pre-declared functions and prelude functions:

// Add builtins to code
// Each declaration is replaced with a single constant declaration with type `any`
// to reduce evaluation time
for (const builtin of context.nativeStorage.builtins) {
code += `const ${builtin[0]}: any = 1\n`
}
// Add prelude functions to code
// Each declaration is replaced with a single constant declaration with type `any`
// to reduce evaluation time
if (context.prelude) {
const preludeFns = context.prelude.split('\nfunction ').slice(1)
preludeFns.forEach(fnString => {
const fnName = fnString.split('(')[0]
// Functions in prelude that start with $ are not added
if (fnName.startsWith('$')) {
return
}
code += `const ${fnName}: any = 1\n`
})
}

Any errors related to modules are also ignored:

diagnostics.forEach(diagnostic => {
const message = diagnostic.messageText.toString()
// Ignore errors regarding imports
// as TS does not have information about Source modules
if (message === IMPORT_TOP_LEVEL_ERROR || message.startsWith(START_OF_MODULE_ERROR)) {
return
}
const lineNumRegExpArr = lineNumRegex.exec(formattedString.split(message)[1])
const lineNum = (lineNumRegExpArr === null ? 0 : parseInt(lineNumRegExpArr[0])) - lineOffset
// Ignore any errors that occur in builtins/prelude (line number <= 0)
if (lineNum <= 0) {
return
}
const position = { line: lineNum, column: 0, offset: 0 }
context.errors.push(new FatalSyntaxError(positionToSourceLocation(position), message))
})

This means that modules and pre-declared functions are not properly typed in the Full TypeScript chapter, and it would be good to add support for them down the line.

To add support for pre-declared functions (without exposing the implementation of the functions to the user), one possible way is to create a lightweight file containing the types of each function, then replace the any type in the constant declaration with the correct type for the function.

In terms of module support, we can perhaps wait until #1399 is solved, and see if the same approach can be used here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementNew feature or requestProposalProposing a feature, please discuss

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions