Skip to content

Commit

Permalink
[lang1] 支持 (import)
Browse files Browse the repository at this point in the history
  • Loading branch information
xieyuheng committed Mar 31, 2024
1 parent 4375a31 commit ed51ebc
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 2 deletions.
1 change: 0 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
[lang1] 支持 `(import)`
[lang1] test `(import)`

> [lang0] 支持直接递归函数与相互递归函数,不能判断等价的地方就不判断。
Expand Down
1 change: 1 addition & 0 deletions src/lang1/mod/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from "./Mod.js"
export * from "./modResolve.js"
export * from "./createMod.js"
export * from "./modDefine.js"
export * from "./modFind.js"
5 changes: 5 additions & 0 deletions src/lang1/mod/modResolve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type Mod } from "./index.js"

export function modResolve(mod: Mod, href: string): URL {
return new URL(href, mod.url)
}
7 changes: 6 additions & 1 deletion src/lang1/run/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { formatExp } from "../format/formatExp.js"
import { modDefine, type Mod } from "../mod/index.js"
import { reduce } from "../reduce/reduce.js"
import { type Stmt } from "../stmt/Stmt.js"
import { importOne } from "./importOne.js"

export function execute(mod: Mod, stmt: Stmt): null | string {
switch (stmt["@kind"]) {
Expand All @@ -20,7 +21,11 @@ export function execute(mod: Mod, stmt: Stmt): null | string {
}

case "Import": {
throw new Error("TODO")
for (const entry of stmt.entries) {
importOne(mod, stmt.path, entry)
}

return null
}
}
}
29 changes: 29 additions & 0 deletions src/lang1/run/importOne.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { modDefine, modFind, modResolve } from "../mod/index.js"
import type { Mod } from "../mod/Mod.js"
import type { ImportEntry } from "../stmt/Stmt.js"
import { executeMod } from "./executeMod.js"

export function importOne(mod: Mod, path: string, entry: ImportEntry): void {
const url = modResolve(mod, path)
if (url.href === mod.url.href) {
throw new Error(`I can not circular import: ${path}`)
}

const found = mod.loadedMods.get(url.href)
if (found === undefined) {
throw new Error(`Mod is not loaded: ${path}`)
}

executeMod(found.mod)

const { name, rename } = entry

const def = modFind(found.mod, name)
if (def === undefined) {
throw new Error(
`I can not import undefined name: ${name}, from path: ${path}`,
)
}

modDefine(mod, rename || name, def)
}

0 comments on commit ed51ebc

Please sign in to comment.