forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.ts
More file actions
398 lines (362 loc) · 11.3 KB
/
Copy pathbuild.ts
File metadata and controls
398 lines (362 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import { basename, dirname, join, resolve } from "node:path"
import { readFileSync, writeFileSync, existsSync, readdirSync } from "node:fs"
import { ensureDirSync, readJSONSync, mkdirp } from "fs-extra"
import {
compileWithHost,
jacdacDefaultSpecifications,
DevsDiagnostic,
formatDiagnostics,
DEVS_DBG_FILE,
prettySize,
DebugInfo,
CompileFlags,
SrcMapResolver,
preludeFiles,
Host,
LocalBuildConfig,
ResolvedBuildConfig,
resolveBuildConfig,
DeviceConfig,
RepoInfo,
pinsInfo,
CompilationResult,
} from "@devicescript/compiler"
import {
BINDIR,
CmdOptions,
consoleColors,
debug,
error,
GENDIR,
LIBDIR,
log,
verboseLog,
} from "./command"
import type { DevsModule } from "@devicescript/vm"
import { readFile, writeFile } from "node:fs/promises"
import { printDmesg } from "./vmworker"
import { EXIT_CODE_COMPILATION_ERROR } from "./exitcodes"
import { converters, parseServiceSpecificationMarkdownToJSON } from "jacdac-ts"
export function readDebugInfo() {
let dbg: DebugInfo
try {
dbg = readJSONSync(join(BINDIR, DEVS_DBG_FILE))
} catch {}
return dbg
}
let devsInst: DevsModule
export function setDevsDmesg() {
if (devsInst) {
const dbg = readDebugInfo()
devsInst.dmesg = (s: string) => {
printDmesg(dbg, "WASM", s)
}
}
}
export function devsFactory() {
// emscripten doesn't like multiple instances
if (devsInst) return Promise.resolve(devsInst)
const d = require("@devicescript/vm")
try {
require("websocket-polyfill")
// @ts-ignore
global.Blob = require("buffer").Blob
} catch {
log("can't load websocket-polyfill")
}
return (d() as Promise<DevsModule>).then(m => {
devsInst = m
setDevsDmesg()
m.devsInit()
return m
})
}
export async function devsStartWithNetwork(options: {
tcp?: boolean
test?: boolean
deviceId?: string
gcStress?: boolean
}) {
const inst = await devsFactory()
if (options.deviceId) inst.devsSetDeviceId(options.deviceId)
inst.devsGcStress(!!options.gcStress)
if (options.tcp)
await inst.setupNodeTcpSocketTransport(require, "127.0.0.1", 8082)
else await inst.setupWebsocketTransport("ws://127.0.0.1:8081")
inst.devsStart()
return inst
}
export async function getHost(
buildConfig: ResolvedBuildConfig,
options: BuildOptions & CmdOptions,
folder: string
) {
const inst = options.noVerify ? undefined : await devsFactory()
const outdir = resolve(options.cwd ?? ".", options.outDir || BINDIR)
ensureDirSync(outdir)
const devsHost: Host = {
write: (fn: string, cont: string) => {
const p = join(outdir, fn)
verboseLog(`write ${p}`)
writeFileSync(p, cont)
if (
fn.endsWith(".jasm") &&
typeof cont == "string" &&
cont.indexOf("???oops") >= 0
)
throw new Error("bad disassembly")
},
read: (fn: string) => {
return readFileSync(resolve(folder, fn), "utf-8")
},
log: verboseLog,
isBasicOutput: () => !consoleColors,
error: (err: DevsDiagnostic) => {
if (!options.quiet)
console.error(formatDiagnostics([err], !consoleColors))
},
getFlags: () => options.flag ?? {},
getConfig: () => buildConfig,
verifyBytecode: (buf: Uint8Array) => {
if (!inst) return
const res = inst.devsVerify(buf)
if (res != 0) throw new Error("verification error: " + res)
},
}
return devsHost
}
function toDevsDiag(d: jdspec.Diagnostic): DevsDiagnostic {
return {
category: 1,
code: 9998,
file: undefined,
filename: d.file,
start: 0,
length: 1,
messageText: d.message,
line: d.line,
column: 1,
endLine: d.line,
endColumn: 100,
formatted: "",
}
}
function compileServiceSpecs(
tsdir: string,
lcfg: LocalBuildConfig,
errors: DevsDiagnostic[]
) {
const dir = join(tsdir, "services")
lcfg.addServices = []
if (existsSync(dir)) {
const includes: Record<string, jdspec.ServiceSpec> = {}
jacdacDefaultSpecifications.forEach(
spec => (includes[spec.shortId] = spec)
)
const markdowns = readdirSync(dir, { encoding: "utf-8" }).filter(
fn => /\.md$/i.test(fn) && !/README\.md$/i.test(fn)
)
for (const mdf of markdowns) {
const fn = join(dir, mdf)
const content = readFileSync(fn, { encoding: "utf-8" })
const json = parseServiceSpecificationMarkdownToJSON(
content,
includes,
fn
)
json.catalog = false
if (json?.errors?.length)
errors.push(...json.errors.map(toDevsDiag))
else {
includes[json.shortId] = json
verboseLog(`custom service: ${json.shortName}`)
lcfg.addServices.push(json)
}
}
}
}
export function validateBoard(board: DeviceConfig, baseCfg: RepoInfo) {
const bid = board.id
if (!/^\w+$/.test(bid)) throw new Error(`invalid identifier: ${bid}`)
board.id = bid
const arch = baseCfg.archs[board.archId]
if (!arch) throw new Error(`board.archId ${board.archId} is invalid`)
if (baseCfg.boards[bid]) throw new Error(`board ${bid} already defined`)
if ((+board.productId & 0xf000_0000) != 0x3000_0000)
throw new Error(`invalid productId ${board.productId}`)
const { desc, errors } = pinsInfo(arch, board)
verboseLog(desc)
if (errors.length) throw new Error(errors.join("\n"))
}
function compileBoards(
tsdir: string,
lcfg: LocalBuildConfig,
errors: DevsDiagnostic[]
) {
const dir = join(tsdir, "boards")
lcfg.addBoards = []
const baseCfg = resolveBuildConfig()
if (existsSync(dir)) {
const boards = readdirSync(dir, { encoding: "utf-8" }).filter(fn =>
fn.endsWith(".board.json")
)
for (const boardFn of boards) {
const fullName = join(dir, boardFn)
try {
const board: DeviceConfig = JSON.parse(
readFileSync(fullName, "utf-8")
)
const bid = basename(boardFn, ".board.json")
if (board.id && board.id != bid)
throw new Error("ignoring id: field in favor of filename")
board.id = bid
validateBoard(board, baseCfg)
verboseLog(`custom board: ${board.id}`)
lcfg.addBoards.push(board)
} catch (e) {
errors.push(
toDevsDiag({
file: fullName,
line: 1,
message: e.message,
})
)
}
}
}
}
export class CompilationError extends Error {
static NAME = "CompilationError"
constructor(message: string) {
super(message)
this.name = CompilationError.NAME
}
}
export function buildConfigFromDir(dir: string, options: BuildOptions = {}) {
const lcfg: LocalBuildConfig = {}
const errors: DevsDiagnostic[] = []
if (dir) {
compileServiceSpecs(dir, lcfg, errors)
compileBoards(dir, lcfg, errors)
if (!options.quiet)
for (const e of errors)
console.error(`${e.filename}(${e.line}): ${e.messageText}`)
}
return {
buildConfig: resolveBuildConfig(lcfg),
errors,
}
}
export async function compileFile(
fn: string,
options: BuildOptions = {}
): Promise<CompilationResult> {
const exists = existsSync(fn)
if (!exists) throw new Error(`source file "${fn}" not found`)
const folder = dirname(resolve(fn))
const { errors, buildConfig } = buildConfigFromDir(folder)
const host = await getHost(buildConfig, options, folder)
const res = compileWithHost(basename(fn), host)
await saveLibFiles(buildConfig, options)
setDevsDmesg() // set again after we have re-created -dbg.json file
if (errors.length) {
res.diagnostics.unshift(...errors)
res.success = false
}
return res
}
export async function saveLibFiles(
buildConfig: ResolvedBuildConfig,
options: BuildOptions
) {
// pass the user-provided services so they are included in devicescript-specs.d.ts
const prelude = preludeFiles(buildConfig)
const pref = resolve(options.cwd ?? ".")
await mkdirp(join(pref, LIBDIR))
for (const fn of Object.keys(prelude)) {
const fnpath = join(pref, fn)
const ex = await readFile(fnpath, "utf-8").then(
r => r,
_ => null
)
if (prelude[fn] != ex) await writeFile(fnpath, prelude[fn])
}
// generate constants for non-catalog services
const customServices =
buildConfig.services.filter(srv => srv.catalog !== undefined) || []
// generate source files
for (const lang of ["ts", "c"]) {
const converter = converters()[lang]
let constants = ""
for (const srv of customServices) {
constants += converter(srv) + "\n"
}
const dir = join(pref, GENDIR, lang)
await mkdirp(dir)
await writeFile(join(dir, `constants.${lang}`), constants, {
encoding: "utf-8",
})
}
// json specs
{
const dir = join(pref, GENDIR)
await mkdirp(dir)
await writeFile(
join(dir, `services.json`),
JSON.stringify(customServices, null, 2),
{
encoding: "utf-8",
}
)
}
}
export interface BuildOptions {
noVerify?: boolean
outDir?: string
stats?: boolean
flag?: CompileFlags
cwd?: string
quiet?: boolean
}
export async function build(file: string, options: BuildOptions & CmdOptions) {
file = file || "main.ts"
options.outDir = options.outDir || BINDIR
if (!existsSync(file)) {
// otherwise we throw
error(`${file} does not exist`)
return
}
// log(`building ${file}`)
ensureDirSync(options.outDir)
try {
await buildOnce(file, options)
} catch (e) {
if (e.name === CompilationError.NAME)
process.exit(EXIT_CODE_COMPILATION_ERROR)
}
}
async function buildOnce(file: string, options: BuildOptions & CmdOptions) {
const { stats } = options
const { success, binary, dbg } = await compileFile(file, options)
if (!success) throw new CompilationError("compilation failed")
if (stats) {
log(`bytecode: ${prettySize(binary.length)}`)
const { sizes, functions } = dbg
log(
" " +
Object.keys(sizes)
.map(name => `${name}: ${prettySize(sizes[name])}`)
.join(", ")
)
log(` functions:`)
const resolver = SrcMapResolver.from(dbg)
functions
.sort((l, r) => l.size - r.size)
.forEach(fn => {
log(` ${fn.name} (${prettySize(fn.size)})`)
fn.users.forEach(user =>
debug(` <-- ${resolver.posToString(user[0])}`)
)
})
}
}