Skip to content

Commit c689a90

Browse files
committed
Update tests
1 parent 9cdec12 commit c689a90

File tree

7 files changed

+46
-77
lines changed

7 files changed

+46
-77
lines changed

scripts/build_sicp_package.mjs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import createContext from '../dist/createContext.js'
77
import { ACORN_PARSE_OPTIONS } from '../dist/constants.js'
88
import { Chapter } from '../dist/types.js'
99

10+
const SICP_DIR = 'sicp_publish/dist'
11+
1012
async function recursiveDirCopy(srcPath, dstPath) {
1113
// Copy and keep only necessary files
1214
const files = await fsPromises.readdir(srcPath)
@@ -29,26 +31,26 @@ async function recursiveDirCopy(srcPath, dstPath) {
2931
}
3032

3133
async function prepare() {
32-
await fsPromises.rm('sicp_publish/dist', { recursive: true, force: true })
33-
await fsPromises.mkdir('sicp_publish/dist', { recursive: true })
34-
await recursiveDirCopy('dist', 'sicp_publish/dist')
34+
await fsPromises.rm(SICP_DIR, { recursive: true, force: true })
35+
await fsPromises.mkdir(SICP_DIR, { recursive: true })
36+
await recursiveDirCopy('dist', SICP_DIR)
3537

3638
// Remove unnecessary dependencies
3739
await Promise.all([
3840
'finder.js', 'index.js', 'scope-refactoring.js'
39-
].map(fileName => fsPromises.rm(`sicp_publish/dist/${fileName}`)))
41+
].map(fileName => fsPromises.rm(`${SICP_DIR}/${fileName}`)))
4042
}
4143

4244
function main() {
43-
const writeStream = createWriteStream('sicp_publish/dist/sicp.js', {
45+
const writeStream = createWriteStream(`${SICP_DIR}/sicp.js`, {
4446
encoding: 'utf-8',
4547
flags: 'w'
4648
})
4749
writeStream.write('"use strict";\n')
4850
writeStream.write('Object.defineProperty(exports, "__esModule", { value: true });\n')
4951
writeStream.write('const createContext_1 = require("./createContext");\n')
50-
writeStream.write('const dict = createContext_1.default(4).nativeStorage.builtins;')
51-
writeStream.write('\n// Declare functions for prelude\n')
52+
writeStream.write('const dict = createContext_1.default(4).nativeStorage.builtins;\n')
53+
writeStream.write('\n// Declare builtins for prelude\n')
5254

5355
// @ts-expect-error Something to do with weird stuff going on between cjs and esm
5456
const context = createContext.default(Chapter.SOURCE_4)
@@ -66,7 +68,7 @@ function main() {
6668

6769
const prelude = parse(context.prelude, ACORN_PARSE_OPTIONS)
6870

69-
writeStream.write('\n // Export prelude functions\n')
71+
writeStream.write('\n// Export prelude functions\n')
7072
for (const func of prelude.body) {
7173
if (func.type !== 'FunctionDeclaration') {
7274
throw new Error(`Expected FunctionDeclarations, got '${func.type}' instead`)

src/__tests__/environment.ts

Lines changed: 0 additions & 31 deletions
This file was deleted.

src/index.ts

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { SourceLocation } from 'estree'
2-
import * as es from 'estree'
1+
import type es from 'estree'
32
import { SourceMapConsumer } from 'source-map'
43

54
import createContext from './createContext'
@@ -10,16 +9,16 @@ import { getAllOccurrencesInScopeHelper, getScopeHelper } from './scope-refactor
109
import { setBreakpointAtLine } from './stdlib/inspector'
1110
import {
1211
Chapter,
13-
Context,
14-
Error as ResultError,
15-
ExecutionMethod,
16-
Finished,
17-
ModuleContext,
18-
RecursivePartial,
19-
Result,
20-
SourceError,
21-
SVMProgram,
22-
Variant
12+
type Context,
13+
type Error as ResultError,
14+
type ExecutionMethod,
15+
type Finished,
16+
type ModuleContext,
17+
type RecursivePartial,
18+
type Result,
19+
type SourceError,
20+
type SVMProgram,
21+
type Variant
2322
} from './types'
2423
import { assemble } from './vm/svml-assembler'
2524
import { compileToIns } from './vm/svml-compiler'
@@ -30,7 +29,7 @@ import { ModuleNotFoundError } from './modules/errors'
3029
import type { ImportOptions } from './modules/moduleTypes'
3130
import preprocessFileImports from './modules/preprocessor'
3231
import { validateFilePath } from './modules/preprocessor/filePaths'
33-
import { getKeywords, getProgramNames, NameDeclaration } from './name-extractor'
32+
import { getKeywords, getProgramNames, type NameDeclaration } from './name-extractor'
3433
import { htmlRunner, resolvedErrorPromise, sourceFilesRunner } from './runner'
3534

3635
export interface IOptions {
@@ -57,7 +56,7 @@ export interface IOptions {
5756

5857
// needed to work on browsers
5958
if (typeof window !== 'undefined') {
60-
// @ts-ignore
59+
// @ts-expect-error Initialize doesn't exist on SourceMapConsumer
6160
SourceMapConsumer.initialize({
6261
'lib/mappings.wasm': 'https://unpkg.com/[email protected]/lib/mappings.wasm'
6362
})
@@ -77,11 +76,13 @@ export function parseError(errors: SourceError[], verbose: boolean = verboseErro
7776
// TODO currently elaboration is just tagged on to a new line after the error message itself. find a better
7877
// way to display it.
7978
const elaboration = error.elaborate()
80-
return line < 1
79+
return typeof line === 'number' && line < 1
8180
? `${filePath}${explanation}\n${elaboration}\n`
8281
: `${filePath}Line ${line}, Column ${column}: ${explanation}\n${elaboration}\n`
8382
} else {
84-
return line < 1 ? explanation : `${filePath}Line ${line}: ${explanation}`
83+
return typeof line === 'number' && line < 1
84+
? explanation
85+
: `${filePath}Line ${line}: ${explanation}`
8586
}
8687
})
8788
return errorMessagesArr.join('\n')
@@ -91,7 +92,7 @@ export function findDeclaration(
9192
code: string,
9293
context: Context,
9394
loc: { line: number; column: number }
94-
): SourceLocation | null | undefined {
95+
): es.SourceLocation | null | undefined {
9596
const program = looseParse(code, context)
9697
if (!program) {
9798
return null
@@ -111,7 +112,7 @@ export function getScope(
111112
code: string,
112113
context: Context,
113114
loc: { line: number; column: number }
114-
): SourceLocation[] {
115+
): es.SourceLocation[] {
115116
const program = looseParse(code, context)
116117
if (!program) {
117118
return []
@@ -132,7 +133,7 @@ export function getAllOccurrencesInScope(
132133
code: string,
133134
context: Context,
134135
loc: { line: number; column: number }
135-
): SourceLocation[] {
136+
): es.SourceLocation[] {
136137
const program = looseParse(code, context)
137138
if (!program) {
138139
return []

src/modules/preprocessor/__tests__/analyzer.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import type { Program } from 'estree'
2-
import createContext from '../../../createContext'
32
import {
43
DuplicateImportNameError,
54
UndefinedDefaultImportError,
@@ -53,7 +52,7 @@ describe('Test throwing import validation errors', () => {
5352
allowUndefinedImports: boolean,
5453
throwOnDuplicateNames: boolean
5554
) {
56-
const context = createContext(Chapter.FULL_JS)
55+
const context = mockContext(Chapter.FULL_JS)
5756
const importGraphResult = await parseProgramsAndConstructImportGraph(
5857
p => Promise.resolve(files[p]),
5958
entrypointFilePath as string,
@@ -712,7 +711,7 @@ describe('Test throwing DuplicateImportNameErrors', () => {
712711
shouldThrow,
713712
errMsg
714713
) => {
715-
const context = createContext(Chapter.FULL_JS)
714+
const context = mockContext(Chapter.FULL_JS)
716715
const [entrypointFilePath, ...topoOrder] = objectKeys(programs)
717716

718717
await loadSourceModules(new Set(['one_module', 'another_module']), context, false)

src/modules/preprocessor/__tests__/preprocessor.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import type { Program } from 'estree'
2-
import type { MockedFunction } from 'jest-mock'
32

43
import { parseError, type IOptions } from '../../..'
54
import { mockContext } from '../../../utils/testing/mocks'
@@ -14,6 +13,7 @@ import {
1413
} from '../../../stdlib/localImport.prelude'
1514
import type { SourceFiles } from '../../moduleTypes'
1615
import { UndefinedImportError } from '../../errors'
16+
import { asMockedFunc } from '../../../utils/testing/misc'
1717

1818
jest.mock('../../loader/loaders')
1919

@@ -49,7 +49,7 @@ describe('preprocessFileImports', () => {
4949
const assertASTsAreEquivalent = (
5050
actualProgram: Program | undefined,
5151
expectedCode: string,
52-
log: boolean = false
52+
_log: boolean = false
5353
): void => {
5454
if (!actualProgram) {
5555
throw new Error('Actual program should not be undefined!')
@@ -140,9 +140,7 @@ describe('preprocessFileImports', () => {
140140
})
141141

142142
it('ignores Source module imports & removes all non-Source module import-related AST nodes in the preprocessed program', async () => {
143-
const docsMocked = memoizedGetModuleDocsAsync as MockedFunction<
144-
typeof memoizedGetModuleDocsAsync
145-
>
143+
const docsMocked = asMockedFunc(memoizedGetModuleDocsAsync)
146144
docsMocked.mockResolvedValueOnce({
147145
default: {} as any,
148146
a: {} as any,
@@ -195,9 +193,8 @@ describe('preprocessFileImports', () => {
195193
})
196194

197195
it('collates Source module imports at the start of the top-level environment of the preprocessed program', async () => {
198-
const docsMocked = memoizedGetModuleDocsAsync as MockedFunction<
199-
typeof memoizedGetModuleDocsAsync
200-
>
196+
const docsMocked = asMockedFunc(memoizedGetModuleDocsAsync)
197+
201198
docsMocked.mockResolvedValue({
202199
f: {} as any,
203200
g: {} as any,

src/runner/fullJSRunner.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import * as create from '../utils/ast/astCreator'
1717
import { getFunctionDeclarationNamesInProgram } from '../utils/uniqueIds'
1818
import { toSourceError } from './errors'
1919
import { resolvedErrorPromise } from './utils'
20-
import { Runner } from './types'
20+
import type { Runner } from './types'
2121

2222
function fullJSEval(code: string, nativeStorage: NativeStorage): any {
2323
if (nativeStorage.evaller) {
@@ -68,7 +68,7 @@ const fullJSRunner: Runner = async (program, context) => {
6868
context.nativeStorage.previousProgramsIdentifiers.add(id)
6969
)
7070
const preEvalCode: string = generate(preEvalProgram)
71-
await fullJSEval(preEvalCode, context.nativeStorage)
71+
fullJSEval(preEvalCode, context.nativeStorage)
7272

7373
let transpiled
7474
let sourceMapJson: RawSourceMap | undefined
@@ -77,7 +77,7 @@ const fullJSRunner: Runner = async (program, context) => {
7777
return {
7878
status: 'finished',
7979
context,
80-
value: await fullJSEval(transpiled, context.nativeStorage)
80+
value: fullJSEval(transpiled, context.nativeStorage)
8181
}
8282
} catch (error) {
8383
context.errors.push(

src/runner/sourceRunner.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,18 @@ const runners = {
3535
if (context.errors.length > 0) {
3636
return resolvedErrorPromise
3737
}
38-
const redexedSteps: IStepperPropContents[] = []
39-
for (const step of steps) {
38+
39+
const redexedSteps = steps.map((step): IStepperPropContents => {
4040
const redex = getRedex(step[0], step[1])
4141
const redexed = redexify(step[0], step[1])
42-
redexedSteps.push({
42+
return {
4343
code: redexed[0],
4444
redex: redexed[1],
4545
explanation: step[2],
4646
function: callee(redex, context)
47-
})
48-
}
47+
}
48+
})
49+
4950
return Promise.resolve({
5051
status: 'finished',
5152
context,

0 commit comments

Comments
 (0)