-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimp-defs.mts
More file actions
3073 lines (2756 loc) · 104 KB
/
imp-defs.mts
File metadata and controls
3073 lines (2756 loc) · 104 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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as imp from './imp-core.mjs'
import {
ImpT,
ImpVal,
NIL,
SymT,
ImpJsf,
ImpIfn,
ImpC,
ImpQ,
ImpLst,
ImpLstA,
} from './imp-core.mjs'
import {impShow} from './imp-show.mjs'
import {load} from './imp-load.mjs'
import {impEval} from './imp-eval.mjs'
import {imparse} from './im-parse.mjs'
import {toNativePath} from './lib-file.mjs'
// Import ImpEvaluator type - we need this for 'this' context
import type {ImpEvaluator} from './imp-eval.mjs'
// Node.js modules - only available in Node.js environment
let fs: any = null
let https: any = null
let http: any = null
let readline: any = null
// Try to import Node.js modules if available
try {
if (typeof process !== 'undefined' && process.versions?.node) {
fs = await import('fs')
https = await import('https')
http = await import('http')
readline = await import('readline')
}
} catch (e) {
// Running in browser or environment without Node.js modules
}
// Output provider abstraction - can be customized for different environments
export interface OutputProvider {
writeLine(text: string): void
}
// Default console output provider
class ConsoleOutputProvider implements OutputProvider {
writeLine(text: string): void {
console.log(text)
}
}
// Global output provider
let globalOutputProvider: OutputProvider = new ConsoleOutputProvider()
export function setOutputProvider(provider: OutputProvider) {
globalOutputProvider = provider
}
// Input provider abstraction - can be implemented for Node.js, browser, or other contexts
export interface InputProvider {
readLine(): Promise<string>
}
// Default Node.js readline-based input provider
class NodeReadlineProvider implements InputProvider {
constructor(private rl: any) {}
async readLine(): Promise<string> {
return new Promise((resolve) => {
// Use once('line') instead of question() to properly integrate with the async iterator
this.rl.once('line', (line: string) => {
resolve(line)
})
})
}
}
// Fallback provider for non-interactive contexts (piped input, etc.)
class NodeStdinProvider implements InputProvider {
async readLine(): Promise<string> {
if (!readline) throw 'readline not available'
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
})
rl.once('line', (line: string) => {
rl.close()
resolve(line)
})
})
}
}
// Global input provider (set by REPL or external code)
let globalInputProvider: InputProvider | null = null
export function setInputProvider(provider: InputProvider | null) {
globalInputProvider = provider
}
// Convenience function for Node.js readline interface
export function setReadlineInterface(rl: any | null) {
if (rl) {
globalInputProvider = new NodeReadlineProvider(rl)
} else {
globalInputProvider = null
}
}
// Helper: read a line from the configured input provider
async function readLine(): Promise<string> {
// If we have a global input provider, use it
if (globalInputProvider) {
return await globalInputProvider.readLine()
}
// Otherwise, fall back to Node.js stdin
const fallback = new NodeStdinProvider()
return await fallback.readLine()
}
// Helper: read file or URL content as string (async)
async function readContent(x: ImpVal): Promise<string> {
// Check if it's a FILE symbol
if (ImpQ.isSym(x) && x[1].kind === SymT.FILE) {
if (!fs) throw 'File reading not available in browser environment'
let filepath = toNativePath(x[2].description!)
try {
return fs.readFileSync(filepath, 'utf8')
} catch (e: any) {
throw `Failed to read file: ${filepath} - ${e.message}`
}
}
// Check if it's a URL symbol
else if (ImpQ.isSym(x) && x[1].kind === SymT.URL) {
let url = x[2].description!
// In browser, use fetch API
if (!http && !https) {
try {
const response = await fetch(url)
if (!response.ok) throw new Error(`HTTP ${response.status}`)
return await response.text()
} catch (e: any) {
throw `Failed to fetch URL: ${url} - ${e.message}`
}
}
// In Node.js, use http/https modules
return new Promise((resolve, reject) => {
let protocol = url.startsWith('https:') ? https : http
protocol.get(url, (res: any) => {
let data = ''
res.on('data', (chunk: any) => data += chunk)
res.on('end', () => resolve(data))
}).on('error', (e: any) => reject(`Failed to fetch URL: ${url} - ${e.message}`))
})
}
// String fallback (treat as filepath)
else if (x[0] === ImpT.STR) {
if (!fs) throw 'File reading not available in browser environment'
let filepath = x[2] as string
try {
return fs.readFileSync(filepath, 'utf8')
} catch (e: any) {
throw `Failed to read file: ${filepath} - ${e.message}`
}
}
else {
throw 'read expects a %file, URL, or string filepath'
}
}
// Helper function to get numeric value from INT, NUM, STR (as char codes), or vector types
function getNum(x: ImpVal): number | number[] {
if (x[0] === ImpT.INT || x[0] === ImpT.NUM) return x[2] as number
if (x[0] === ImpT.INTs || x[0] === ImpT.NUMs) return x[2] as number[]
// Handle strings as character code vectors (K behavior)
if (x[0] === ImpT.STR) {
const str = x[2] as string
return str.split('').map(c => c.charCodeAt(0))
}
throw "expected number or vector, got: " + x[0]
}
// Helper function to apply binary operation element-wise (fully atomic)
function elemWise(op: (a: number, b: number) => number, x: ImpVal, y: ImpVal): ImpVal {
let xVal = getNum(x)
let yVal = getNum(y)
// Both scalars
if (typeof xVal === 'number' && typeof yVal === 'number') {
return ImpC.int(op(xVal, yVal))
}
// x is scalar, y is vector
if (typeof xVal === 'number' && Array.isArray(yVal)) {
return ImpC.ints(yVal.map(b => op(xVal, b)))
}
// x is vector, y is scalar
if (Array.isArray(xVal) && typeof yVal === 'number') {
return ImpC.ints(xVal.map(a => op(a, yVal)))
}
// Both vectors - element-wise (must be same length)
if (Array.isArray(xVal) && Array.isArray(yVal)) {
if (xVal.length !== yVal.length) throw "vector length mismatch"
return ImpC.ints(xVal.map((a, i) => op(a, yVal[i])))
}
throw "invalid operands"
}
// Helper for right-atomic operations (monadic functions applied element-wise to right arg)
function rightAtomic(op: (a: number) => number, x: ImpVal): ImpVal {
let xVal = getNum(x)
// Scalar
if (typeof xVal === 'number') {
return ImpC.int(op(xVal))
}
// Vector - apply to each element
if (Array.isArray(xVal)) {
return ImpC.ints(xVal.map(a => op(a)))
}
throw "invalid operand"
}
// Helper for left-atomic operations (dyadic function applied element-wise to left arg)
function leftAtomic(op: (a: number, b: any) => any, x: ImpVal, y: ImpVal): ImpVal {
let xVal = getNum(x)
// x is scalar
if (typeof xVal === 'number') {
return op(xVal, y)
}
// x is vector - apply to each element
if (Array.isArray(xVal)) {
const results: any[] = []
for (const a of xVal) {
results.push(op(a, y))
}
// Return results as appropriate type
if (results.every(r => typeof r === 'number')) {
return ImpC.ints(results as number[])
}
// Otherwise return as list
return imp.lst(undefined, results)
}
throw "invalid operands"
}
// Helper to convert a value to an array representation
// Returns [elements, isString] where isString indicates if we should convert back to string
function toArray(x: ImpVal): [ImpVal[], boolean] {
if (x[0] === ImpT.STR) {
const str = x[2] as string
const chars = str.split('').map(c => ImpC.str(c))
return [chars, true]
}
if (ImpQ.isLst(x)) {
return [x[2] as ImpVal[], false]
}
if (x[0] === ImpT.INTs) {
const nums = x[2] as number[]
return [nums.map(n => ImpC.int(n)), false]
}
if (x[0] === ImpT.NUMs) {
const nums = x[2] as number[]
return [nums.map(n => ImpC.num(n)), false]
}
if (x[0] === ImpT.SYMs) {
const syms = x[2] as symbol[]
return [syms.map(s => ImpC.sym(s, SymT.BQT)), false]
}
throw "toArray expects list, vector, or string"
}
// Helper to convert array back to appropriate type
function fromArray(items: ImpVal[], wasString: boolean, attrs?: any): ImpVal {
if (wasString) {
// Convert back to string
const str = items.map(item => {
if (item[0] === ImpT.STR) return item[2] as string
if (item[0] === ImpT.INT || item[0] === ImpT.NUM) return String.fromCharCode(item[2] as number)
return String(item[2])
}).join('')
return ImpC.str(str)
}
// If original was a list (attrs provided), keep it as a list to avoid
// collapsing symbols into a SYMs strand.
if (attrs !== undefined) {
return imp.lst(attrs, items)
}
// Try to preserve vector types
const allInts = items.every(item => item[0] === ImpT.INT)
const allNums = items.every(item => item[0] === ImpT.NUM)
const allSyms = items.every(item => item[0] === ImpT.SYM)
if (allInts) {
return ImpC.ints(items.map(item => item[2] as number))
}
if (allNums) {
return ImpC.nums(items.map(item => item[2] as number))
}
if (allSyms) {
return ImpC.syms(items.map(item => item[2] as symbol))
}
// Return as general list
return imp.lst(attrs, items)
}
// Type-safe toXml using utility object for syntactic sugar
function toXml(x: ImpVal): string {
if (x[0] === ImpT.NIL) return '<nil/>';
if (ImpQ.isSym(x)) {
const attrs: Record<string, string> = {}
// Only add 'k' attribute if not RAW (add first for consistent ordering)
if (x[1].kind !== SymT.RAW) {
const kindNames = ['raw', 'set', 'get', 'lit', 'refn', 'ish', 'path', 'file', 'url', 'bqt', 'typ', 'ann', 'msg', 'kw', 'msg2', 'kw2', 'err', 'unq']
attrs.k = kindNames[x[1].kind]
}
attrs.v = `${x[2].description}`
return xmlTag('imp:sym', attrs)
}
if (ImpQ.isLst(x) || x[0] === ImpT.TOP) {
return xmlTag('imp:' + x[0].toLowerCase(), x[1]??{},
'\n ' + x[2].map(toXml).join('\n ') + '\n')}
// Handle vector types
if (x[0] === ImpT.INTs || x[0] === ImpT.NUMs) {
return xmlTag('imp:' + x[0].toLowerCase(), {v: (x[2] as number[]).join(' ')})
}
if (x[0] === ImpT.SYMs) {
return xmlTag('imp:' + x[0].toLowerCase(), {v: (x[2] as symbol[]).map(s => s.description).join(' ')})
}
// Handle dictionaries
if (ImpQ.isDct(x)) {
const dct = x[2] as Map<string, ImpVal>
const entries: string[] = []
for (const [key, val] of dct.entries()) {
entries.push(`\n <entry k="${key}">${toXml(val)}</entry>`)
}
return `<imp:dct>${entries.join('')}\n</imp:dct>`
}
// For other types (SEP, INT, STR, MLS, JSF, JDY, END), treat as simple values
return xmlTag('imp:' + x[0].toLowerCase(), {v: (x[2]??'').toString()})}
function xmlTag(tag:string, attrs:Record<string, string>, content?:string) {
let attrStr = Object.entries(attrs).map(([k,v])=>`${k}="${v}"`).join(' ')
if (content) return `<${tag} ${attrStr}>${content}</${tag}>`
else return `<${tag} ${attrStr}/>`
}
// Get word class for a value
function wordClass(x:ImpVal) {
let [xt, _xa, _xv] = x
const ImpP = imp.ImpP
switch (xt) {
case ImpT.TOP: return ImpP.N
case ImpT.END: return ImpP.E
case ImpT.SEP: return ImpP.E // Treat separator as end-like (stops collection)
case ImpT.INT: return ImpP.N
case ImpT.NUM: return ImpP.N
case ImpT.STR: return ImpP.N
case ImpT.MLS: return ImpP.N
case ImpT.SYM: return ImpP.N
case ImpT.LST: return ImpP.N
case ImpT.DCT: return ImpP.N
case ImpT.INTs: return ImpP.N
case ImpT.NUMs: return ImpP.N
case ImpT.SYMs: return ImpP.N
// -- resolved symbols:
case ImpT.JSF: return ImpP.V
case ImpT.IFN: return ImpP.V
case ImpT.NIL: return ImpP.N
default: throw "[wordClass] invalid argument:" + x }}
function printHelp(out: OutputProvider) {
out.writeLine(`implish help
words list all known words
? \`name help for a specific word
look \`name show a word's definition
tokens:
42 integer 1.5 number
"hello" string \`foo quoted symbol
foo word (looked up)
foo: set-word :foo get-word
'foo lit-word .foo message
%path/to file http://... url
@ann annotation #tag issue
/ref refinement ?err error
syntax:
x: 42 assign a value
f: {x + 1} define a function (args: x, y, z)
f[10] call a function
1 2 3 numeric strand (vector)
:[\`a 1; \`b 2] dictionary literal
.: ... :. comment`)
}
// Export the word definitions
export function createImpWords(): Record<string, ImpVal> {
const words: Record<string, ImpVal> = {
'nil': NIL,
'ok': imp.jsf(() => NIL, 0),
// Control flow (these receive unevaluated LST/TOP arguments for lazy evaluation)
'ite': imp.jsf(async function(this: ImpEvaluator, cond: ImpVal, thenBranch: ImpVal, elseBranch: ImpVal) {
// Type check: ensure we got LST or TOP values
if (!ImpQ.isLst(cond) && !ImpQ.isTop(cond)) {
throw "ite: condition must be an unevaluated expression (LST or TOP)"
}
if (!ImpQ.isLst(thenBranch) && !ImpQ.isTop(thenBranch)) {
throw "ite: then branch must be an unevaluated expression (LST or TOP)"
}
if (!ImpQ.isLst(elseBranch) && !ImpQ.isTop(elseBranch)) {
throw "ite: else branch must be an unevaluated expression (LST or TOP)"
}
// Evaluate condition
let condResult = await this.lastEval(cond)
// Check if truthy (non-zero, non-nil, non-empty)
let isTruthy = false
if (condResult[0] === ImpT.INT || condResult[0] === ImpT.NUM) {
isTruthy = (condResult[2] as number) !== 0
} else if (condResult[0] === ImpT.NIL) {
isTruthy = false
} else {
isTruthy = true // Everything else is truthy
}
// Evaluate and return appropriate branch
if (isTruthy) {
return await this.lastEval(thenBranch)
} else {
return await this.lastEval(elseBranch)
}
}, 3),
'while': imp.jsf(async function(this: ImpEvaluator, cond: ImpVal, body: ImpVal) {
// Type check: ensure we got LST or TOP values
if (!ImpQ.isLst(cond) && !ImpQ.isTop(cond)) {
throw "while: condition must be an unevaluated expression (LST or TOP)"
}
if (!ImpQ.isLst(body) && !ImpQ.isTop(body)) {
throw "while: body must be an unevaluated expression (LST or TOP)"
}
// Repeatedly evaluate condition and body
while (true) {
let condResult = await this.lastEval(cond)
// Check if truthy
let isTruthy = false
if (condResult[0] === ImpT.INT || condResult[0] === ImpT.NUM) {
isTruthy = (condResult[2] as number) !== 0
} else if (condResult[0] === ImpT.NIL) {
isTruthy = false
} else {
isTruthy = true
}
if (!isTruthy) break
await this.lastEval(body)
}
return NIL
}, 2),
// Variable access
'get': imp.jsf(function(this: ImpEvaluator, x: ImpVal) {
// get[`word] - look up a quoted symbol, return value or fault
// Also handles symbol vectors
if (ImpQ.isSym(x)) {
const varName = x[2].description!
const value = this.words[varName]
if (value !== undefined) {
return value
}
// Return fault symbol (?word)
return ImpC.sym(x[2], SymT.ERR)
} else if (x[0] === ImpT.SYMs) {
// Handle symbol vector - map get over each symbol
const syms = x[2] as symbol[]
const results: ImpVal[] = []
for (const sym of syms) {
const varName = sym.description!
const value = this.words[varName]
if (value !== undefined) {
results.push(value)
} else {
results.push(ImpC.sym(sym, SymT.ERR))
}
}
// Return as list
return imp.lst(undefined, results)
}
throw "get expects a symbol or symbol vector"
}, 1),
'set': imp.jsf(function(this: ImpEvaluator, x: ImpVal, y: ImpVal) {
// set[`word; value] - bind word to value, return value
// Also handles parallel assignment with symbol vectors
if (ImpQ.isSym(x)) {
const varName = x[2].description!
// Unwrap single-element lists created by imparse (e.g., [2 +])
if (ImpQ.isLst(y)) {
const yList = y as ImpLst
const attrs = yList[1] as ImpLstA
if (yList[2].length === 1 && attrs.open === '[' && attrs.close === ']') {
y = yList[2][0]
}
}
this.words[varName] = y
return y
} else if (x[0] === ImpT.SYMs) {
// Parallel assignment: set[`a `b `c; values]
const syms = x[2] as symbol[]
// If y is a list, distribute values
if (ImpQ.isLst(y)) {
const values = y[2] as ImpVal[]
for (let i = 0; i < syms.length; i++) {
const varName = syms[i].description!
const value = i < values.length ? values[i] : NIL
this.words[varName] = value
}
return y
} else if (y[0] === ImpT.INTs || y[0] === ImpT.NUMs || y[0] === ImpT.SYMs) {
// Vector values - distribute to each variable
const values = y[2] as (number[] | symbol[])
const results: ImpVal[] = []
for (let i = 0; i < syms.length; i++) {
const varName = syms[i].description!
let value: ImpVal
if (i < values.length) {
if (y[0] === ImpT.INTs) value = ImpC.int(values[i] as number)
else if (y[0] === ImpT.NUMs) value = ImpC.num(values[i] as number)
else value = ImpC.sym(values[i] as symbol, SymT.RAW)
} else {
value = NIL
}
this.words[varName] = value
results.push(value)
}
return y
} else {
// Scalar value - assign to all variables
for (const sym of syms) {
const varName = sym.description!
this.words[varName] = y
}
return y
}
}
throw "set expects a symbol or symbol vector as first argument"
}, 2),
'+' : imp.jsf((x,y)=>elemWise((a,b)=>a+b, x, y), 2),
'-' : imp.jsf((x,y)=>elemWise((a,b)=>a-b, x, y), 2),
'*' : imp.jsf((x,y)=>elemWise((a,b)=>a*b, x, y), 2),
'%' : imp.jsf((x,y)=>elemWise((a,b)=>Math.floor(a/b), x, y), 2),
'^' : imp.jsf((x,y)=>elemWise((a,b)=>Math.pow(a,b), x, y), 2),
'min' : imp.jsf((x,y)=>elemWise((a,b)=>Math.min(a,b), x, y), 2),
'max' : imp.jsf((x,y)=>elemWise((a,b)=>Math.max(a,b), x, y), 2),
'<' : imp.jsf((x,y)=>elemWise((a,b)=>a<b ? 1 : 0, x, y), 2),
'>' : imp.jsf((x,y)=>elemWise((a,b)=>a>b ? 1 : 0, x, y), 2),
'<=' : imp.jsf((x,y)=>elemWise((a,b)=>a<=b ? 1 : 0, x, y), 2),
'>=' : imp.jsf((x,y)=>elemWise((a,b)=>a>=b ? 1 : 0, x, y), 2),
'=' : imp.jsf((x,y)=>elemWise((a,b)=>a===b ? 1 : 0, x, y), 2),
'~=' : imp.jsf((x,y)=>elemWise((a,b)=>a!==b ? 1 : 0, x, y), 2),
'tk' : imp.jsf((x,y)=> {
// x tk y: take x items from y, with repeats/cycling
// x must be a scalar integer
if (x[0] !== ImpT.INT) {
throw "tk left argument must be an integer"
}
let count = x[2] as number
// Handle y as string - cycle through characters
if (y[0] === ImpT.STR) {
let str = y[2] as string
if (str.length === 0) {
throw "tk cannot take from empty string"
}
let result = ""
for (let i = 0; i < count; i++) {
result += str[i % str.length]
}
return ImpC.str(result)
}
// Handle y as list - cycle through elements
if (y[0] === ImpT.LST) {
const yList = y as ImpLst
let vals = yList[2] as ImpVal[]
if (vals.length === 0) {
throw "tk cannot take from empty list"
}
let result: ImpVal[] = []
for (let i = 0; i < count; i++) {
result.push(vals[i % vals.length])
}
return imp.lst(yList[1], result)
}
// Handle y as numeric scalar - repeat it
if (y[0] === ImpT.INT) {
let val = y[2] as number
return ImpC.ints(Array(count).fill(val))
}
if (y[0] === ImpT.NUM) {
let val = y[2] as number
return ImpC.nums(Array(count).fill(val))
}
// Handle y as numeric vector
if (y[0] === ImpT.INTs) {
let vals = y[2] as number[]
if (vals.length === 0) {
throw "tk cannot take from empty array"
}
let result: number[] = []
for (let i = 0; i < count; i++) {
result.push(vals[i % vals.length])
}
return ImpC.ints(result)
}
if (y[0] === ImpT.NUMs) {
let vals = y[2] as number[]
if (vals.length === 0) {
throw "tk cannot take from empty array"
}
let result: number[] = []
for (let i = 0; i < count; i++) {
result.push(vals[i % vals.length])
}
return ImpC.nums(result)
}
// For any other scalar type, repeat it in a list
let result: ImpVal[] = []
for (let i = 0; i < count; i++) {
result.push(y)
}
return imp.lst(undefined, result)
}, 2),
'rev': imp.jsf(x => {
const [items, wasString] = toArray(x)
return fromArray([...items].reverse(), wasString, ImpQ.isLst(x) ? x[1] : undefined)
}, 1),
'len': imp.jsf(x => {
// Scalars have length 1
if (x[0] === ImpT.INT || x[0] === ImpT.NUM || x[0] === ImpT.SYM) {
return ImpC.int(1)
}
const [items, _] = toArray(x)
return ImpC.int(items.length)
}, 1),
'!' : imp.jsf(x=>{
let n = x[2] as number
if (n < 0) throw "! requires non-negative integer"
if (n === 0) return ImpC.nums([])
return ImpC.nums(Array.from({length: n}, (_, i) => i))
}, 1),
'rd': imp.jsf(async x=>ImpC.str(await readContent(x)), 1),
'rln': imp.jsf(async ()=>ImpC.str(await readLine()), 0),
'wr': imp.jsf(async (file, content)=>{
if (!fs) throw 'File writing not available in browser environment'
// file should be a FILE symbol or string
let filepath: string
if (ImpQ.isSym(file) && file[1].kind === SymT.FILE) {
filepath = toNativePath(file[2].description!)
} else if (file[0] === ImpT.STR) {
filepath = toNativePath(file[2] as string)
} else {
throw 'wr expects a %file or string filepath as first argument'
}
// content should be a string
if (content[0] !== ImpT.STR) {
throw 'wr expects a string as second argument'
}
let text = content[2] as string
try {
fs.writeFileSync(filepath, text, 'utf8')
return NIL
} catch (e: any) {
throw `Failed to write file: ${filepath} - ${e.message}`
}
}, 2),
'e?': imp.jsf(x=>{
if (!fs) throw 'File operations not available in browser environment'
// file should be a FILE symbol or string
let filepath: string
if (ImpQ.isSym(x) && x[1].kind === SymT.FILE) {
filepath = toNativePath(x[2].description!)
} else if (x[0] === ImpT.STR) {
filepath = toNativePath(x[2] as string)
} else {
throw 'e? expects a %file or string filepath'
}
try {
fs.accessSync(filepath, fs.constants.F_OK)
return ImpC.int(1)
} catch (e) {
return ImpC.int(0)
}
}, 1),
'rm': imp.jsf(x=>{
if (!fs) throw 'File operations not available in browser environment'
// file should be a FILE symbol or string
let filepath: string
if (ImpQ.isSym(x) && x[1].kind === SymT.FILE) {
filepath = toNativePath(x[2].description!)
} else if (x[0] === ImpT.STR) {
filepath = toNativePath(x[2] as string)
} else {
throw 'rm expects a %file or string filepath'
}
try {
fs.unlinkSync(filepath)
return NIL
} catch (e: any) {
throw `Failed to remove file: ${filepath} - ${e.message}`
}
}, 1),
'load': imp.jsf(async x=>{
// If x is a FILE symbol, read it first (load %path == load rd %path)
if (ImpQ.isSym(x) && x[1].kind === SymT.FILE) {
x = ImpC.str(await readContent(x))}
return load(x as any)}, 1),
'xmls': imp.jsf(x=>ImpC.str(toXml(x) as string), 1),
'look': imp.jsf(function(this: ImpEvaluator, x: ImpVal) {
let name: string
if (ImpQ.isSym(x)) name = x[2].description!
else if (x[0] === ImpT.STR) name = x[2] as string
else throw "look expects a symbol or string"
return ImpC.str(impShow(this.words[name] ?? NIL))
}, 1),
'eval': imp.jsf(x=>eval(x[2] as string), 1),
'part': imp.jsf(x=>{
// If x is a string or symbol, look up the word in impWords
let val = x
if (x[0] === ImpT.STR) {
val = words[x[2] as string] ?? x
} else if (ImpQ.isSym(x)) {
val = words[(x[2] as symbol).description ?? ''] ?? x
}
return ImpC.str(wordClass(val))
}, 1),
'type?': imp.jsf(x=>{
// Map ImpT enum to type symbol name
let typeName = x[0].toLowerCase()
return ImpC.sym(Symbol(typeName), SymT.TYP)
}, 1),
'show': imp.jsf(x=>ImpC.str(impShow(x)), 1),
'chr': imp.jsf(x=>{
if (x[0] === ImpT.INT) {
const code = x[2] as number
if (code < 0 || code > 0x10ffff) throw "chr: code point out of range"
return ImpC.str(String.fromCodePoint(code))
}
if (x[0] === ImpT.INTs) {
const codes = x[2] as number[]
const chars = codes.map(c => {
if (c < 0 || c > 0x10ffff) throw "chr: code point out of range"
return String.fromCodePoint(c)
})
return ImpC.str(chars.join(''))
}
throw "chr expects an integer or vector of integers"
}, 1),
'ord': imp.jsf(x=>{
if (x[0] !== ImpT.STR) throw "ord expects a string"
const chars = [...(x[2] as string)]
if (chars.length === 1) {
return ImpC.int(chars[0].codePointAt(0)!)
}
return ImpC.ints(chars.map(c => c.codePointAt(0)!))
}, 1),
'hex': imp.jsf(x=>{
if (x[0] === ImpT.INT) {
const n = x[2] as number
if (!Number.isInteger(n)) throw "hex expects an integer"
if (n < 0) return ImpC.str(`-${(-n).toString(16)}`)
return ImpC.str(n.toString(16))
}
if (x[0] === ImpT.INTs) {
const nums = x[2] as number[]
const strs = nums.map(n => {
if (!Number.isInteger(n)) throw "hex expects integers"
if (n < 0) return `-${(-n).toString(16)}`
return n.toString(16)
})
return imp.lst(undefined, strs.map(s => ImpC.str(s)))
}
throw "hex expects an integer or vector of integers"
}, 1),
'oct': imp.jsf(x=>{
if (x[0] === ImpT.INT) {
const n = x[2] as number
if (!Number.isInteger(n)) throw "oct expects an integer"
if (n < 0) return ImpC.str(`-${(-n).toString(8)}`)
return ImpC.str(n.toString(8))
}
if (x[0] === ImpT.INTs) {
const nums = x[2] as number[]
const strs = nums.map(n => {
if (!Number.isInteger(n)) throw "oct expects integers"
if (n < 0) return `-${(-n).toString(8)}`
return n.toString(8)
})
return imp.lst(undefined, strs.map(s => ImpC.str(s)))
}
throw "oct expects an integer or vector of integers"
}, 1),
'echo': imp.jsf(x=>{
// For vectors/strands, use impShow; for other types, print the raw value
let output: string
if (x[0] === ImpT.INTs || x[0] === ImpT.NUMs || x[0] === ImpT.SYMs) {
output = impShow(x)
} else {
output = String(x[2])
}
globalOutputProvider.writeLine(output)
return NIL
}, 1),
'words': imp.jsf(()=>{
// Return all defined word names as a SYMs vector
return ImpC.syms(Object.keys(words).map(w => Symbol(w)))
}, 0),
'?': imp.jsf(function(this: ImpEvaluator) {
// If no argument follows, print general help
if (this.atEnd()) {
printHelp(globalOutputProvider)
return NIL
}
// Otherwise consume next item as the word to look up
let x = this.nextItem()
let name: string
if (ImpQ.isSym(x)) {
name = x[2].description!
} else if (x[0] === ImpT.STR) {
name = x[2] as string
} else {
globalOutputProvider.writeLine("? expects a symbol or string")
return NIL
}
let w = this.words[name]
if (!w) {
globalOutputProvider.writeLine(`no such word: ${name}`)
return NIL
}
if (w[0] === ImpT.JSF) {
let a = (w[1] as any)
let doc = a.doc as string | undefined
let arity = a.arity as number
if (doc) globalOutputProvider.writeLine(doc)
else globalOutputProvider.writeLine(`${name} — built-in function (no description)`)
globalOutputProvider.writeLine(` arity: ${arity < 0 ? 'variadic' : arity}`)
} else if (w[0] === ImpT.IFN) {
let a = (w[1] as any)
let doc = a.doc as string | undefined
let arity = a.arity as number
if (doc) globalOutputProvider.writeLine(doc)
else globalOutputProvider.writeLine(`${name} — user-defined function (no description)`)
globalOutputProvider.writeLine(` arity: ${arity}`)
globalOutputProvider.writeLine(` use 'look' to see definition`)
} else {
globalOutputProvider.writeLine(`${name} — ${w[0]} value`)
}
return NIL
}, 0),
'imparse': imp.jsf((x) => imparse(x, words), 1),
// Dictionary operations
'keys': imp.jsf(x => {
if (!ImpQ.isDct(x)) throw "keys expects a dictionary"
const dct = x[2] as Map<string, ImpVal>
return ImpC.syms(Array.from(dct.keys()).map(k => Symbol(k)))
}, 1),
'vals': imp.jsf(x => {
if (!ImpQ.isDct(x)) throw "vals expects a dictionary"
const dct = x[2] as Map<string, ImpVal>
return imp.lst(undefined, Array.from(dct.values()))
}, 1),
'at': imp.jsf(async function(this: any, x: ImpVal, y: ImpVal): Promise<ImpVal> {
// Apply function with single argument
if (x[0] === ImpT.JSF || ImpQ.isIfn(x)) {
// Check arity
const arity = x[1].arity
if (arity !== 1) throw `at with function expects arity 1, got ${arity}`
if (x[0] === ImpT.JSF) {
const fn = x[2] as any
return await fn.call(this, y)
} else {
// IFN - implish function
const body = x[2] as ImpVal[]
// Need to evaluate the function body with y as argument
// This would require access to the evaluator context
throw "at with implish function not yet implemented"
}
}
// Index into dictionary with symbol
if (ImpQ.isDct(x)) {
if (!ImpQ.isSym(y)) throw "at with dictionary expects symbol as index"
const dct = x[2] as Map<string, ImpVal>
const keyName = y[2].description || ''
return dct.get(keyName) || NIL
}
// Index into list or vector
const indexOne = (source: ImpVal, idx: number): ImpVal => {
if (ImpQ.isLst(source)) {
const items = source[2] as ImpVal[]
if (idx < 0 || idx >= items.length) return ImpC.int(imp.NULL_INT)
return items[idx]
}
if (source[0] === ImpT.INTs || source[0] === ImpT.NUMs) {
const nums = source[2] as number[]
if (idx < 0 || idx >= nums.length) return ImpC.int(imp.NULL_INT)
return source[0] === ImpT.INTs ? ImpC.int(nums[idx]) : ImpC.num(nums[idx])
}
if (source[0] === ImpT.SYMs) {
const syms = source[2] as symbol[]
if (idx < 0 || idx >= syms.length) return ImpC.int(imp.NULL_INT)
return ImpC.sym(syms[idx], SymT.BQT)
}
if (source[0] === ImpT.STR) {
const str = source[2] as string
if (idx < 0 || idx >= str.length) return ImpC.int(imp.NULL_INT)
return ImpC.str(str[idx])
}
throw "at expects list, vector, string, or dictionary"
}
// Right atomic - apply index to each element of index list/vector
if (y[0] === ImpT.INTs || y[0] === ImpT.NUMs) {
const indices = y[2] as number[]
const results: ImpVal[] = []
for (const idx of indices) {
results.push(indexOne(x, idx))
}
// Try to return as vector if all results are same type
const allInts = results.every(r => r[0] === ImpT.INT)
if (allInts) {
return ImpC.ints(results.map(r => r[2] as number))
}
return imp.lst(undefined, results)
}
if (ImpQ.isLst(y)) {
const items = y[2] as ImpVal[]
const results: ImpVal[] = []
for (const item of items) {
if (item[0] === ImpT.INT || item[0] === ImpT.NUM) {
results.push(indexOne(x, item[2] as number))
} else {
throw "at index list must contain only integers"
}
}
return imp.lst(undefined, results)
}
// Single index
if (y[0] === ImpT.INT || y[0] === ImpT.NUM) {
return indexOne(x, y[2] as number)
}
throw "at expects integer or list of integers as index"
}, 2),
'put': imp.jsf((d, k, v) => {
if (!ImpQ.isDct(d)) throw "put expects dictionary as first argument"
if (!ImpQ.isSym(k)) throw "put expects symbol as second argument"
const dct = d[2] as Map<string, ImpVal>
const keyName = k[2].description || ''
// Create new dictionary with updated value (immutable)
const newMap = new Map(dct)
newMap.set(keyName, v)