forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspecgen.ts
More file actions
720 lines (643 loc) · 20.7 KB
/
Copy pathspecgen.ts
File metadata and controls
720 lines (643 loc) · 20.7 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
import {
ArchConfig,
DeviceConfig,
LocalBuildConfig,
ResolvedBuildConfig,
} from "@devicescript/interop"
import {
SRV_BOOTLOADER,
SRV_BRIDGE,
SRV_CONTROL,
SRV_DASHBOARD,
SRV_DEVICE_SCRIPT_CONDITION,
SRV_DEVICE_SCRIPT_MANAGER,
SRV_INFRASTRUCTURE,
SRV_LOGGER,
SRV_PROTO_TEST,
SRV_PROXY,
SRV_ROLE_MANAGER,
SRV_UNIQUE_BRAIN,
cStorage,
addComment,
wrapComment,
SRV_WSSK,
SRV_CLOUD_CONFIGURATION,
SRV_CODAL_MESSAGE_BUS,
SRV_DEVS_DBG,
SRV_TCP,
SRV_I2C,
SRV_SETTINGS,
SRV_CLOUD_ADAPTER,
SRV_ROS,
SRV_GPIO,
} from "jacdac-ts"
import { boardSpecifications, jacdacDefaultSpecifications } from "./embedspecs"
import { PacketSpecCode, runtimeVersion } from "./format"
import { prelude } from "./prelude"
import { camelize, oops, upperCamel, upperFirst } from "./util"
import { pinsInfo } from "./board"
import { assert } from "./jdutil"
import { TSDOC_NATIVE, TSDOC_START } from "./compiler"
const REGISTER_NUMBER = "Register<number>"
const REGISTER_BOOL = "Register<boolean>"
const REGISTER_STRING = "Register<string>"
const REGISTER_BUFFER = "Register<Buffer>"
const REGISTER_ARRAY = "Register<any[]>"
export function unresolveBuildConfig(
cfg: ResolvedBuildConfig
): LocalBuildConfig {
if (!cfg) cfg = {} as any
const r: LocalBuildConfig = {
hwInfo: cfg.hwInfo,
addArchs: cfg.addArchs,
addBoards: cfg.addBoards,
addServices: cfg.addServices,
}
return JSON.parse(JSON.stringify(r))
}
export function resolveBuildConfig(
local?: LocalBuildConfig
): ResolvedBuildConfig {
const r: ResolvedBuildConfig = {
hwInfo: Object.assign({}, local?.hwInfo ?? {}),
pkgJson: Object.assign({}, local?.pkgJson ?? {}),
addArchs: local?.addArchs,
addBoards: local?.addBoards,
addServices: local?.addServices,
boards: Object.assign({}, boardSpecifications.boards),
archs: Object.assign({}, boardSpecifications.archs),
services: jacdacDefaultSpecifications.concat(local?.addServices ?? []),
}
for (const arch of local?.addArchs ?? []) r.archs[arch.id] = arch
for (const board of local?.addBoards ?? []) r.boards[board.id] = board
return r
}
function isRegister(k: jdspec.PacketKind) {
return k == "ro" || k == "rw" || k == "const"
}
function toHex(n: number): string {
if (n === undefined) return ""
if (n < 0) return "-" + toHex(n)
return "0x" + n.toString(16)
}
function noCtorSpec(info: jdspec.ServiceSpec) {
return [].indexOf(info.classIdentifier) > -1
}
function noClientMarkdownSpec(info: jdspec.ServiceSpec) {
return [SRV_CONTROL].indexOf(info.classIdentifier) > -1
}
function ignoreSpec(info: jdspec.ServiceSpec) {
return (
info.status === "deprecated" ||
[
SRV_ROLE_MANAGER,
SRV_LOGGER,
SRV_BOOTLOADER,
SRV_PROTO_TEST,
SRV_INFRASTRUCTURE,
SRV_PROXY,
SRV_UNIQUE_BRAIN,
SRV_DASHBOARD,
SRV_BRIDGE,
SRV_DEVICE_SCRIPT_CONDITION,
SRV_DEVICE_SCRIPT_MANAGER,
SRV_WSSK,
SRV_CLOUD_CONFIGURATION,
SRV_CODAL_MESSAGE_BUS,
SRV_DEVS_DBG,
SRV_TCP,
].indexOf(info.classIdentifier) > -1
)
}
let sysCache: Record<string, jdspec.PacketInfo>
export function pktName(pkt: jdspec.PacketInfo): string {
if (!sysCache) {
sysCache = {}
for (const pkt of jacdacDefaultSpecifications.find(
s => s.camelName == "system"
).packets) {
// these typically have much better names in the spec
// there also isn't much gain in harmonizing
if (["value", "active", "inactive"].includes(pkt.name)) continue
sysCache[pkt.kind + ":" + pkt.identifier] = pkt
}
}
const sys = sysCache[pkt.kind + ":" + pkt.identifier]
if (sys) {
if (
sys.name == "intensity" &&
pkt.fields.length == 1 &&
pkt.fields[0].type == "bool"
)
return "enabled"
return camelize(sys.name)
}
return camelize(pkt.name)
}
export function specToDeviceScript(info: jdspec.ServiceSpec): string {
let r = ""
let srv = ""
for (const en of Object.values(info.enums)) {
const enPref = enumName(info, en.name)
r += `enum ${enPref} { // ${cStorage(en.storage)}\n`
for (const k of Object.keys(en.members)) {
r += " " + k + " = " + toHex(en.members[k]) + ",\n"
}
r += "}\n\n"
}
if (ignoreSpec(info)) return r
const clname = upperCamel(info.camelName)
const isSensor = info.extends.includes("_sensor")
const docUrl =
info.catalog !== false
? `https://microsoft.github.io/devicescript/api/clients/${info.shortId}/`
: undefined
// emit stats as attributes
{
let cmt = (info.notes["short"] || info.name) + "\n\n"
if (info.notes["long"])
cmt += "@remarks\n\n" + info.notes["long"] + "\n\n"
if (!info.status || info.status === "experimental")
cmt += "@experimental\n"
if (info.group) cmt += `@group ${info.group}\n`
if (info.tags?.length) cmt += `@category ${info.tags.join(", ")}\n`
if (docUrl) cmt += `@see {@link ${docUrl} | Documentation}`
r += wrapComment("devs", patchLinks(cmt))
}
// emit class
r += `class ${clname} extends ${isSensor ? "Sensor" : "Role"} {\n`
const ibase =
info.shortId == "_base"
? "ServerInterface"
: isSensor
? "SensorServerSpec"
: "BaseServerSpec"
srv += `interface ${clname}ServerSpec extends ${ibase} {\n`
if (noCtorSpec(info))
r +=
wrapComment("devs", "This service cannot be accessed via role.") +
" private constructor()\n"
else
r +=
wrapComment("devs", "Create new service client.") +
" constructor(roleName?: string)\n"
r +=
wrapComment("devs", `Static specification for ${info.name}`) +
" static spec: ServiceSpec\n"
let codes =
wrapComment("devs", `Spec-code definitions for ${info.name}`) +
`enum ${clname}Codes {\n`
info.packets.forEach(pkt => {
if (pkt.derived || pkt.pipeType) return
const cmt = addComment(pkt)
let kw = ""
let tp = ""
let sx = ""
let argtp = packetType(info, pkt)
const client = !!pkt.client
const nameOfPkt = pktName(pkt)
const opt = pkt.optional ? "?" : ""
let enumPref = ""
let enumMask = 0
if (isRegister(pkt.kind)) {
enumPref = "Reg"
enumMask = PacketSpecCode.REGISTER
if (client) {
tp = "ClientRegister"
sx = "()"
} else {
kw = "readonly "
tp = "Register"
const rettp =
nameOfPkt == "instanceName" ? argtp : `AsyncValue<${argtp}>`
srv += ` ${nameOfPkt}${opt}(): ${rettp}\n`
if (pkt.kind == "rw") {
const args = pktFields(info, pkt)
srv += ` set_${nameOfPkt}${opt}(${args}): AsyncValue<void>\n`
}
}
} else if (pkt.kind == "event") {
enumPref = "Event"
enumMask = PacketSpecCode.EVENT
kw = "readonly "
tp = "Event"
// skip events for srv for now
} else if (pkt.kind == "command") {
enumPref = "Cmd"
enumMask = PacketSpecCode.COMMAND
r += wrapComment(
"devs",
cmt.comment +
pkt.fields
.filter(f => !!f)
.map(f => `@param ${f.name} - ${f.unit ?? ""}`)
.join("\n")
)
r += ` ${commandSig(info, pkt).sig}\n`
srv += ` ${commandSig(info, pkt, true).sig}\n`
} else if (pkt.kind == "report") {
enumPref = "Report"
enumMask = PacketSpecCode.REPORT
}
if (enumPref) {
const id = upperFirst(pktName(pkt))
const code = enumMask | pkt.identifier
codes += ` ${enumPref}${id} = 0x${code.toString(16)},\n`
}
if (tp) {
if (docUrl)
cmt.comment += `@see {@link ${docUrl}#${pkt.kind}:${pktName(
pkt
)} | Documentation}`
r += wrapComment("devs", cmt.comment)
r += ` ${kw}${nameOfPkt}${sx}: ${tp}<${argtp}>\n`
}
})
codes += "}\n\n"
r += "}\n\n" + codes
srv += "}\n"
r += srv
return r.replace(/ *$/gm, "")
}
const pinFunToType: Record<string, string> = {
io: "IOPin",
input: "InputPin",
output: "OutputPin",
analogIn: "AnalogInPin",
analogOut: "AnalogOutPin",
}
function boardFile(binfo: DeviceConfig, arch: ArchConfig) {
let r = `declare module "@dsboard/${binfo.id}" {\n`
r += ` import * as ds from "@devicescript/core"\n`
r += ` interface Board {\n`
for (const service of binfo.$services ?? []) {
const serv = upperFirst(service.service.replace(/.*:/, ""))
const inst = service.name ? upperFirst(service.name) : serv
r += wrapComment(
"devs",
`Start built-in ${inst}\n@${TSDOC_START} ${JSON.stringify(service)}`
)
r += ` start${inst}(roleName?: string): ds.${serv}\n`
}
r += ` }\n`
r += ` const board: Board\n`
r += ` interface BoardPins {\n`
const { infos } = pinsInfo(arch, binfo)
for (const pin of infos) {
if (
pin.label.startsWith("@") ||
(pin.functionLabel && !pin.functionLabel.startsWith("$services")) ||
pin.functionLabel === pin.silkLabel
)
continue
const funs = pin.functions
const types = funs
.map(s => pinFunToType[s])
.filter(s => !!s)
.map(s => "ds." + s)
if (types.length == 0) r += ` // ${pin.label} seems invalid\n`
else {
const cmn = pin.commonLabel != pin.silkLabel
r += [
`/**`,
` * Pin ${pin.silkLabel} (GPIO${pin.gpio}, ${funs.join(", ")})`,
pin.functionLabel
? ` * @note can be also used as ${pin.functionLabel}`
: undefined,
cmn ? ` * @${TSDOC_NATIVE} GPIO.${pin.commonLabel}` : undefined,
` */`,
`${pin.silkLabel}: ${types.join(" & ")}`,
]
.filter(Boolean)
.map(l => " " + l + "\n")
.join("")
}
}
r += ` }\n`
r += ` /**\n`
r += ` * Pin definitions for ${binfo.devName}\n`
r += ` *\n`
r += ` * @${TSDOC_NATIVE} GPIO\n`
r += ` */\n`
r += ` const pins: BoardPins\n`
r += `}\n`
return r
}
// called from build.js with config===undefined
export function preludeFiles(config: ResolvedBuildConfig) {
if (!config) config = resolveBuildConfig()
const pref = "node_modules/@devicescript/"
const r: Record<string, string> = {}
for (const k of Object.keys(prelude)) {
r[pref + k] = prelude[k]
}
const thespecs = config.services
.map(specToDeviceScript)
.filter(n => !!n)
.join("\n")
const withmodule = `declare module "@devicescript/core" {
/**
* Version of the DeviceScript runtime corresponding to this declaration file.
*/
const RUNTIME_VERSION = "${runtimeVersion()}"
${thespecs}
}
`
r[pref + "core/src/devicescript-spec.d.ts"] = withmodule
r[pref + `core/src/devicescript-boards.d.ts`] = Object.values(config.boards)
.map(b => boardFile(b, config.archs[b.archId]))
.join("\n")
return r
}
const serviceBuiltinPackages: Record<number, string> = {
[SRV_I2C]: "i2c",
[SRV_SETTINGS]: "settings",
[SRV_CLOUD_ADAPTER]: "cloud",
[SRV_ROS]: "ros",
[SRV_GPIO]: "gpio",
}
function serviceSpecificationToMarkdown(info: jdspec.ServiceSpec): string {
const { status, camelName } = info
const reserved: Record<string, string> = { switch: "sw" }
const clname = upperCamel(camelName)
const varname = reserved[camelName] || camelName
const baseclass = info.extends.indexOf("_sensor") >= 0 ? "Sensor" : "Role"
if (status === "deprecated") {
return `---
pagination_prev: null
pagination_next: null
unlisted: true
---
# ${clname}
The [${info.name} service](https://microsoft.github.io/jacdac-docs/services/${info.shortId}/) is deprecated and not supported in DeviceScript.
`
}
if (ignoreSpec(info) || noCtorSpec(info) || noClientMarkdownSpec(info)) {
return `---
pagination_prev: null
pagination_next: null
unlisted: true
---
# ${clname}
The [${info.name} service](https://microsoft.github.io/jacdac-docs/services/${info.shortId}/) is used internally by the runtime
and is not directly programmable in DeviceScript.
`
}
const builtinPackage = serviceBuiltinPackages[info.classIdentifier]
if (builtinPackage) {
return `---
pagination_prev: null
pagination_next: null
description: DeviceScript client for ${info.name} service
---
# ${clname}
The [${info.name} service](https://microsoft.github.io/jacdac-docs/services/${info.shortId}/) is used internally by the
[\`@devicescript/${builtinPackage}\`](/developer/packages) package.
{@import optional ../clients-custom/${info.shortId}.mdp}
`
}
let r: string[] = [
`---
pagination_prev: null
pagination_next: null
description: DeviceScript client for ${info.name} service
---
# ${clname}
`,
status !== "stable" && info.shortId[0] !== "_"
? `
:::caution
This service is ${status} and may change in the future.
:::
`
: undefined,
patchLinks(info.notes["short"]),
`- client for [${info.name} service](https://microsoft.github.io/jacdac-docs/services/${info.shortId}/)`,
baseclass ? `- inherits ${baseclass}` : undefined,
info.notes["long"]
? `## About
${patchLinks(info.notes["long"])}
`
: undefined,
`
\`\`\`ts
import { ${clname} } from "@devicescript/core"
const ${varname} = new ${clname}()
\`\`\`
`,
`{@import optional ../clients-custom/${info.shortId}-about.mdp}`,
]
const cmds = info.packets.filter(
pkt =>
pkt.kind === "command" &&
!pkt.pipeType &&
!pkt.internal &&
!pkt.derived &&
!pkt.lowLevel
)
if (cmds.length) r.push("## Commands", "")
cmds.forEach(pkt => {
const { sig, name } = commandSig(info, pkt)
r.push(
`### ${name}`,
"",
pkt.description,
`
\`\`\`ts skip no-run
${varname}.${sig}
\`\`\`
`
)
})
const regs = info.packets
.filter(pkt => isRegister(pkt.kind))
.filter(pkt => !pkt.derived && !pkt.internal && !pkt.lowLevel)
if (regs?.length) r.push("## Registers", "")
regs.forEach(pkt => {
const cmt = addComment(pkt)
const nobuild = status === "stable" && !pkt.client ? "" : "skip"
const pname = pktName(pkt)
const isConst = pkt.kind === "const"
let tp: string = undefined
if (cmt.needsStruct) {
tp = REGISTER_ARRAY
} else {
if (pkt.fields.length == 1 && pkt.fields[0].type == "string")
tp = REGISTER_STRING
else if (pkt.fields.length == 1 && pkt.fields[0].type == "bytes")
tp = REGISTER_BUFFER
else if (pkt.fields[0].type == "bool") tp = REGISTER_BOOL
else tp = REGISTER_NUMBER
}
const isNumber = tp === REGISTER_NUMBER
const isBoolean = tp === REGISTER_BOOL
const isString = tp === REGISTER_STRING
r.push(
`### ${pname} {#${pkt.kind}:${pktName(pkt)}}
`,
pkt.description,
"",
`- type: \`${tp}\` (packing format \`${pkt.packFormat}\`)`,
pkt.optional
? `- optional: this register may not be implemented`
: undefined,
isConst
? `- constant: the register value will not change (until the next reset)`
: undefined,
"",
!isNumber && !isBoolean && !isString
? undefined
: pkt.kind === "rw"
? `- read and write
\`\`\`ts ${nobuild}
import { ${clname} } from "@devicescript/core"
const ${varname} = new ${clname}()
// ...
const value = await ${varname}.${pname}.read()
await ${varname}.${pname}.write(value)
\`\`\`
`
: `- read only
\`\`\`ts ${nobuild}
import { ${clname} } from "@devicescript/core"
const ${varname} = new ${clname}()
// ...
const value = await ${varname}.${pname}.read()
\`\`\`
`,
isConst
? undefined
: `- track incoming values
\`\`\`ts ${nobuild}
import { ${clname} } from "@devicescript/core"
const ${varname} = new ${clname}()
// ...
${varname}.${pname}.subscribe(async (value) => {
...
})
\`\`\`
`,
`
:::note
\`write\` and \`read\` will block until a server is bound to the client.
:::
`
)
})
const evts = info.packets.filter(
pkt =>
pkt.kind === "event" &&
!pkt.internal &&
!pkt.derived &&
!pkt.lowLevel
)
if (evts.length) r.push("## Events", "")
evts.forEach(pkt => {
const pname = pktName(pkt)
r.push(
`### ${pname}`,
"",
pkt.description,
`
\`\`\`ts skip no-run
${varname}.${pname}.subscribe(() => {
})
\`\`\`
`
)
})
// import custom files
r.push(`\n{@import optional ../clients-custom/${info.shortId}.mdp}\n`)
return r.filter(s => s !== undefined).join("\n")
}
function enumName(info: jdspec.ServiceSpec, n: string) {
return upperCamel(info.camelName) + upperCamel(n)
}
function patchLinks(n: string) {
return n?.replace(/\]\(\/services\//g, "](/api/clients/")
}
function packetType(info: jdspec.ServiceSpec, pkt: jdspec.PacketInfo) {
const cmt = addComment(pkt)
if (cmt.needsStruct) {
const types = pkt.fields.map(f => memType(info, f))
const allSame = types.every(t => t == types[0])
if (pkt.fields.some(p => p.startRepeats))
return allSame ? types[0] + "[]" : "any[]"
return `[${types.join(", ")}]`
}
if (pkt.fields.length == 0) return "void"
assert(pkt.fields.length == 1)
return memType(info, pkt.fields[0])
}
function pktFields(info: jdspec.ServiceSpec, pkt: jdspec.PacketInfo) {
// if there's a startRepeats before last field, we don't put ... before it
const earlyRepeats = pkt.fields
.slice(0, pkt.fields.length - 1)
.some(f => f.startRepeats)
const fields = pkt.fields
.map(f => {
const tp = memType(info, f)
if (f.startRepeats && !earlyRepeats) return `...${f.name}: ${tp}[]`
else return `${f.name == "_" ? "value" : f.name}: ${tp}`
})
.join(", ")
return fields
}
function commandSig(
info: jdspec.ServiceSpec,
pkt: jdspec.PacketInfo,
srv = false
) {
const fields = pktFields(info, pkt)
let name = pktName(pkt)
const report = info.packets.find(
p => p.kind == "report" && p.identifier == pkt.identifier
)
const retType = !report ? "void" : packetType(info, report)
if (srv && pkt.optional) name += "?"
const ret = srv ? `AsyncValue<${retType}>` : `Promise<void>`
const sig = `${name}(${fields}): ${ret}`
return {
sig,
name,
}
}
function memType(info: jdspec.ServiceSpec, f: jdspec.PacketMember) {
switch (f.type) {
case "string":
case "string0":
return "string"
case "bytes":
return "Buffer"
case "bool":
return "boolean"
case "f32":
case "f64":
return "number"
case "devid":
return "Buffer"
case "pipe_port":
case "pipe":
return "unknown"
default:
if (/^[iu]\d+(\.\d+)?$/.test(f.type)) return "number"
if (/^u8\[\d+\]$/.test(f.type)) return "Buffer"
if (info.enums[f.type]) return enumName(info, f.type)
oops(`unknown type ${f.type} in spec: ${info.name}`)
}
}
export function clientsMarkdownFiles() {
const { services } = resolveBuildConfig()
const r: Record<string, string> = {}
services.forEach(spec => {
const md = serviceSpecificationToMarkdown(spec)
if (md) r[`${spec.shortId}.md`] = md
})
r["index.mdx"] = `---
title: Clients
---
# Clients
{@import optional ../clients-custom/index.mdp}
`
return r
}