about summary refs log tree commit diff stats
path: root/061text.mu
blob: 4d46319bc6fec9148c1cb7ce442073096ed4fb54 (plain) (blame)
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
700pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
//: Since different layers all carve out different parts of various namespaces
//: (recipes, memory, etc.) for their own use, there's no previous place where
//: we can lay out the big picture of what uses what. So we'll do that here
//: and just have to manually remember to update it when we move boundaries
//: around.
//:
//:: Memory
//:
//: Location 0 - unused (since it can help uncover bugs)
//: Locations 1-899 - reserved for tests
//: Locations 900-999 - reserved for predefined globals in mu scenarios, like keyboard, screen, etc.
:(before "End Setup")
assert(Max_variables_in_scenarios == 900);
//: Locations 1000 ('Reserved_for_tests') onward - available to the allocator in chunks of size Initial_memory_per_routine.
assert(Reserved_for_tests == 1000);

//:: Recipes
//:
//: 0 - unused (IDLE; do nothing)
//: 1-199 - primitives
assert(MAX_PRIMITIVE_RECIPES < 200);
//: 200-999 - defined in .mu files as sequences of primitives
assert(Next_recipe_ordinal == 1000);
//: 1000 onwards - reserved for tests, cleared between tests

//:: Depths for tracing
//:
//: 0 - unused
//: 1-100 - app-level trace statements in mu
//: 101-9989 - call-stack statements (mostly label run)
assert(Initial_callstack_depth == 101);
assert(Max_callstack_depth == 9989);
//: 9990-9999 - intra-instruction lines (mostly label mem)

//:: Summary of transforms and their dependencies
//: begin transforms
//:   begin instruction inserting transforms
//:     52 insert fragments
//:      ↳ 52.2 check fragments
//:   ---
//:   end instruction inserting transforms
//:
//:   begin instruction modifying transforms
//:     56.2 check header ingredients
//:      ↳ 56.4 fill in reply ingredients
//:
//:     begin type modifying transforms
//:        ↱ 56.3 deduce types from header
//:       56 check reply instructions against header
//:       48 check types by name
//:     ---
//:       30 check or set invalid containers
//:     end type modifying transforms
//:      ↳ 57 static dispatch
//:   ---
//:     13 update instruction operation
//:     40 transform braces
//:     41 transform labels
//:      ↱ 46 collect surrounding spaces
//:     42 transform names
//:   end instruction modifying transforms
//:
//:   begin checks
//:   ---
//:     21 check instruction
//:     ↳ 43 transform 'new' to 'allocate'
//:   end checks
//: end transforms
1015' href='#n1015'>1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
# Some useful helpers for dealing with text (arrays of characters)

def equal a:text, b:text -> result:bool [
  local-scope
  load-inputs
  an:num, bn:num <- deaddress a, b
  address-equal?:boolean <- equal an, bn
  return-if address-equal?, true
  return-unless a, false
  return-unless b, false
  a-len:num <- length *a
  b-len:num <- length *b
  # compare lengths
  trace 99, [text-equal], [comparing lengths]
  length-equal?:bool <- equal a-len, b-len
  return-unless length-equal?, false
  # compare each corresponding character
  trace 99, [text-equal], [comparing characters]
  i:num <- copy 0
  {
    done?:bool <- greater-or-equal i, a-len
    break-if done?
    a2:char <- index *a, i
    b2:char <- index *b, i
    chars-match?:bool <- equal a2, b2
    return-unless chars-match?, false
    i <- add i, 1
    loop
  }
  return true
]

scenario text-equal-reflexive [
  local-scope
  x:text <- new [abc]
  run [
    10:bool/raw <- equal x, x
  ]
  memory-should-contain [
    10 <- 1  # x == x for all x
  ]
]

scenario text-equal-identical [
  local-scope
  x:text <- new [abc]
  y:text <- new [abc]
  run [
    10:bool/raw <- equal x, y
  ]
  memory-should-contain [
    10 <- 1  # abc == abc
  ]
]

scenario text-equal-distinct-lengths [
  local-scope
  x:text <- new [abc]
  y:text <- new [abcd]
  run [
    10:bool/raw <- equal x, y
  ]
  memory-should-contain [
    10 <- 0  # abc != abcd
  ]
  trace-should-contain [
    text-equal: comparing lengths
  ]
  trace-should-not-contain [
    text-equal: comparing characters
  ]
]

scenario text-equal-with-empty [
  local-scope
  x:text <- new []
  y:text <- new [abcd]
  run [
    10:bool/raw <- equal x, y
  ]
  memory-should-contain [
    10 <- 0  # "" != abcd
  ]
]

scenario text-equal-with-null [
  local-scope
  x:text <- new [abcd]
  y:text <- copy null
  run [
    10:bool/raw <- equal x, null
    11:bool/raw <- equal null, x
    12:bool/raw <- equal x, y
    13:bool/raw <- equal y, x
    14:bool/raw <- equal y, y
  ]
  memory-should-contain [
    10 <- 0
    11 <- 0
    12 <- 0
    13 <- 0
    14 <- 1
  ]
  check-trace-count-for-label 0, [error]
]

scenario text-equal-common-lengths-but-distinct [
  local-scope
  x:text <- new [abc]
  y:text <- new [abd]
  run [
    10:bool/raw <- equal x, y
  ]
  memory-should-contain [
    10 <- 0  # abc != abd
  ]
]

# A new type to help incrementally construct texts.
container buffer:_elem [
  length:num
  data:&:@:_elem
]

def new-buffer capacity:num -> result:&:buffer:_elem [
  local-scope
  load-inputs
  result <- new {(buffer _elem): type}
  *result <- put *result, length:offset, 0
  {
    break-if capacity
    # capacity not provided
    capacity <- copy 10
  }
  data:&:@:_elem <- new _elem:type, capacity
  *result <- put *result, data:offset, data
  return result
]

def grow-buffer buf:&:buffer:_elem -> buf:&:buffer:_elem [
  local-scope
  load-inputs
  # double buffer size
  olddata:&:@:_elem <- get *buf, data:offset
  oldlen:num <- length *olddata
  newlen:num <- multiply oldlen, 2
  newdata:&:@:_elem <- new _elem:type, newlen
  *buf <- put *buf, data:offset, newdata
  # copy old contents
  i:num <- copy 0
  {
    done?:bool <- greater-or-equal i, oldlen
    break-if done?
    src:_elem <- index *olddata, i
    *newdata <- put-index *newdata, i, src
    i <- add i, 1
    loop
  }
]

def buffer-full? in:&:buffer:_elem -> result:bool [
  local-scope
  load-inputs
  len:num <- get *in, length:offset
  s:&:@:_elem <- get *in, data:offset
  capacity:num <- length *s
  result <- greater-or-equal len, capacity
]

# most broadly applicable definition of append to a buffer
def append buf:&:buffer:_elem, x:_elem -> buf:&:buffer:_elem [
  local-scope
  load-inputs
  len:num <- get *buf, length:offset
  {
    # grow buffer if necessary
    full?:bool <- buffer-full? buf
    break-unless full?
    buf <- grow-buffer buf
  }
  s:&:@:_elem <- get *buf, data:offset
  *s <- put-index *s, len, x
  len <- add len, 1
  *buf <- put *buf, length:offset, len
]

# most broadly applicable definition of append to a buffer of characters: just
# call to-text
def append buf:&:buffer:char, x:_elem -> buf:&:buffer:char [
  local-scope
  load-inputs
  text:text <- to-text x
  buf <- append buf, text
]

# specialization for characters that is backspace-aware
def append buf:&:buffer:char, c:char -> buf:&:buffer:char [
  local-scope
  load-inputs
  len:num <- get *buf, length:offset
  {
    # backspace? just drop last character if it exists and return
    backspace?:bool <- equal c, 8/backspace
    break-unless backspace?
    empty?:bool <- lesser-or-equal len, 0
    return-if empty?
    len <- subtract len, 1
    *buf <- put *buf, length:offset, len
    return
  }
  {
    # grow buffer if necessary
    full?:bool <- buffer-full? buf
    break-unless full?
    buf <- grow-buffer buf
  }
  s:text <- get *buf, data:offset
  *s <- put-index *s, len, c
  len <- add len, 1
  *buf <- put *buf, length:offset, len
]

def append buf:&:buffer:_elem, t:&:@:_elem -> buf:&:buffer:_elem [
  local-scope
  load-inputs
  len:num <- length *t
  i:num <- copy 0
  {
    done?:bool <- greater-or-equal i, len
    break-if done?
    x:_elem <- index *t, i
    buf <- append buf, x
    i <- add i, 1
    loop
  }
]

scenario append-to-empty-buffer [
  local-scope
  x:&:buffer:char <- new-buffer
  run [
    c:char <- copy 97/a
    x <- append x, c
    10:num/raw <- get *x, length:offset
    s:text <- get *x, data:offset
    11:char/raw <- index *s, 0
    12:char/raw <- index *s, 1
  ]
  memory-should-contain [
    10 <- 1  # buffer length
    11 <- 97  # a
    12 <- 0  # rest of buffer is empty
  ]
]

scenario append-to-buffer [
  local-scope
  x:&:buffer:char <- new-buffer
  c:char <- copy 97/a
  x <- append x, c
  run [
    c <- copy 98/b
    x <- append x, c
    10:num/raw <- get *x, length:offset
    s:text <- get *x, data:offset
    11:char/raw <- index *s, 0
    12:char/raw <- index *s, 1
    13:char/raw <- index *s, 2
  ]
  memory-should-contain [
    10 <- 2  # buffer length
    11 <- 97  # a
    12 <- 98  # b
    13 <- 0  # rest of buffer is empty
  ]
]

scenario append-grows-buffer [
  local-scope
  x:&:buffer:char <- new-buffer 3
  s1:text <- get *x, data:offset
  x <- append x, [abc]  # buffer is now full
  s2:text <- get *x, data:offset
  run [
    10:bool/raw <- equal s1, s2
    11:@:char/raw <- copy *s2
    +buffer-filled
    c:char <- copy 100/d
    x <- append x, c
    s3:text <- get *x, data:offset
    20:bool/raw <- equal s1, s3
    21:num/raw <- get *x, length:offset
    30:@:char/raw <- copy *s3
  ]
  memory-should-contain [
    # before +buffer-filled
    10 <- 1   # no change in data pointer after original append
    11 <- 3   # size of data
    12 <- 97  # data
    13 <- 98
    14 <- 99
    # in the end
    20 <- 0   # data pointer has grown after second append
    21 <- 4   # final length
    30 <- 6   # but data's capacity has doubled
    31 <- 97  # data
    32 <- 98
    33 <- 99
    34 <- 100
    35 <- 0
    36 <- 0
  ]
]

scenario buffer-append-handles-backspace [
  local-scope
  x:&:buffer:char <- new-buffer
  x <- append x, [ab]
  run [
    c:char <- copy 8/backspace
    x <- append x, c
    s:text <- buffer-to-array x
    10:@:char/raw <- copy *s
  ]
  memory-should-contain [
    10 <- 1   # length
    11 <- 97  # contents
    12 <- 0
  ]
]

scenario append-to-buffer-of-non-characters [
  local-scope
  x:&:buffer:text <- new-buffer 1/capacity
  # no errors
]

def buffer-to-array in:&:buffer:_elem -> result:&:@:_elem [
  local-scope
  load-inputs
  # propagate null buffer
  return-unless in, null
  len:num <- get *in, length:offset
  s:&:@:_elem <- get *in, data:offset
  # we can't just return s because it is usually the wrong length
  result <- new _elem:type, len
  i:num <- copy 0
  {
    done?:bool <- greater-or-equal i, len
    break-if done?
    src:_elem <- index *s, i
    *result <- put-index *result, i, src
    i <- add i, 1
    loop
  }
]

def blank? x:&:@:_elem -> result:bool [
  local-scope
  load-inputs
  return-unless x, true
  len:num <- length *x
  result <- equal len, 0
]

# Append any number of texts together.
# A later layer also translates calls to this to implicitly call to-text, so
# append to string becomes effectively dynamically typed.
#
# Beware though: this hack restricts how much 'append' can be overridden. Any
# new variants that match:
#   append _:text, ___
# will never ever get used.
def append first:text -> result:text [
  local-scope
  load-inputs
  buf:&:buffer:char <- new-buffer 30
  # append first input
  {
    break-unless first
    buf <- append buf, first
  }
  # append remaining inputs
  {
    arg:text, arg-found?:bool <- next-input
    break-unless arg-found?
    loop-unless arg
    buf <- append buf, arg
    loop
  }
  result <- buffer-to-array buf
]

scenario text-append-1 [
  local-scope
  x:text <- new [hello,]
  y:text <- new [ world!]
  run [
    z:text <- append x, y
    10:@:char/raw <- copy *z
  ]
  memory-should-contain [
    10:array:character <- [hello, world!]
  ]
]

scenario text-append-null [
  local-scope
  x:text <- copy null
  y:text <- new [ world!]
  run [
    z:text <- append x, y
    10:@:char/raw <- copy *z
  ]
  memory-should-contain [
    10:array:character <- [ world!]
  ]
]

scenario text-append-null-2 [
  local-scope
  x:text <- new [hello,]
  y:text <- copy null
  run [
    z:text <- append x, y
    10:@:char/raw <- copy *z
  ]
  memory-should-contain [
    10:array:character <- [hello,]
  ]
]

scenario text-append-multiary [
  local-scope
  x:text <- new [hello, ]
  y:text <- new [world]
  z:text <- new [!]
  run [
    z:text <- append x, y, z
    10:@:char/raw <- copy *z
  ]
  memory-should-contain [
    10:array:character <- [hello, world!]
  ]
]

scenario replace-character-in-text [
  local-scope
  x:text <- new [abc]
  run [
    x <- replace x, 98/b, 122/z
    10:@:char/raw <- copy *x
  ]
  memory-should-contain [
    10:array:character <- [azc]
  ]
]

def replace s:text, oldc:char, newc:char, from:num/optional -> s:text [
  local-scope
  load-inputs
  len:num <- length *s
  i:num <- find-next s, oldc, from
  done?:bool <- greater-or-equal i, len
  return-if done?
  *s <- put-index *s, i, newc
  i <- add i, 1
  s <- replace s, oldc, newc, i
]

scenario replace-character-at-start [
  local-scope
  x:text <- new [abc]
  run [
    x <- replace x, 97/a, 122/z
    10:@:char/raw <- copy *x
  ]
  memory-should-contain [
    10:array:character <- [zbc]
  ]
]

scenario replace-character-at-end [
  local-scope
  x:text <- new [abc]
  run [
    x <- replace x, 99/c, 122/z
    10:@:char/raw <- copy *x
  ]
  memory-should-contain [
    10:array:character <- [abz]
  ]
]

scenario replace-character-missing [
  local-scope
  x:text <- new [abc]
  run [
    x <- replace x, 100/d, 122/z
    10:@:char/raw <- copy *x
  ]
  memory-should-contain [
    10:array:character <- [abc]
  ]
]

scenario replace-all-characters [
  local-scope
  x:text <- new [banana]
  run [
    x <- replace x, 97/a, 122/z
    10:@:char/raw <- copy *x
  ]
  memory-should-contain [
    10:array:character <- [bznznz]
  ]
]

# replace underscores in first with remaining args
def interpolate template:text -> result:text [
  local-scope
  load-inputs  # consume just the template
  # compute result-len, space to allocate for result
  tem-len:num <- length *template
  result-len:num <- copy tem-len
  {
    # while inputs remain
    a:text, arg-received?:bool <- next-input
    break-unless arg-received?
    # result-len = result-len + arg.length - 1 (for the 'underscore' being replaced)
    a-len:num <- length *a
    result-len <- add result-len, a-len
    result-len <- subtract result-len, 1
    loop
  }
  rewind-inputs
  _ <- next-input  # skip template
  result <- new character:type, result-len
  # repeatedly copy sections of template and 'holes' into result
  result-idx:num <- copy 0
  i:num <- copy 0
  {
    # while arg received
    a:text, arg-received?:bool <- next-input
    break-unless arg-received?
    # copy template into result until '_'
    {
      # while i < template.length
      tem-done?:bool <- greater-or-equal i, tem-len
      break-if tem-done?, +done
      # while template[i] != '_'
      in:char <- index *template, i
      underscore?:bool <- equal in, 95/_
      break-if underscore?
      # result[result-idx] = template[i]
      *result <- put-index *result, result-idx, in
      i <- add i, 1
      result-idx <- add result-idx, 1
      loop
    }
    # copy 'a' into result
    j:num <- copy 0
    {
      # while j < a.length
      arg-done?:bool <- greater-or-equal j, a-len
      break-if arg-done?
      # result[result-idx] = a[j]
      in:char <- index *a, j
      *result <- put-index *result, result-idx, in
      j <- add j, 1
      result-idx <- add result-idx, 1
      loop
    }
    # skip '_' in template
    i <- add i, 1
    loop  # interpolate next arg
  }
  +done
  # done with holes; copy rest of template directly into result
  {
    # while i < template.length
    tem-done?:bool <- greater-or-equal i, tem-len
    break-if tem-done?
    # result[result-idx] = template[i]
    in:char <- index *template, i
    *result <- put-index *result, result-idx, in
    i <- add i, 1
    result-idx <- add result-idx, 1
    loop
  }
]

scenario interpolate-works [
  local-scope
  x:text <- new [abc_ghi]
  y:text <- new [def]
  run [
    z:text <- interpolate x, y
    10:@:char/raw <- copy *z
  ]
  memory-should-contain [
    10:array:character <- [abcdefghi]
  ]
]

scenario interpolate-at-start [
  local-scope
  x:text <- new [_, hello!]
  y:text <- new [abc]
  run [
    z:text <- interpolate x, y
    10:@:char/raw <- copy *z
  ]
  memory-should-contain [
    10:array:character <- [abc, hello!]
    22 <- 0  # out of bounds
  ]
]

scenario interpolate-at-end [
  local-scope
  x:text <- new [hello, _]
  y:text <- new [abc]
  run [
    z:text <- interpolate x, y
    10:@:char/raw <- copy *z
  ]
  memory-should-contain [
    10:array:character <- [hello, abc]
  ]
]

# result:bool <- space? c:char
def space? c:char -> result:bool [
  local-scope
  load-inputs
  # most common case first
  result <- equal c, 32/space
  return-if result
  result <- equal c, 10/newline
  return-if result
  result <- equal c, 9/tab
  return-if result
  result <- equal c, 13/carriage-return
  return-if result
  # remaining uncommon cases in sorted order
  # http://unicode.org code-points in unicode-set Z and Pattern_White_Space
  result <- equal c, 11/ctrl-k
  return-if result
  result <- equal c, 12/ctrl-l
  return-if result
  result <- equal c, 133/ctrl-0085
  return-if result
  result <- equal c, 160/no-break-space
  return-if result
  result <- equal c, 5760/ogham-space-mark
  return-if result
  result <- equal c, 8192/en-quad
  return-if result
  result <- equal c, 8193/em-quad
  return-if result
  result <- equal c, 8194/en-space
  return-if result
  result <- equal c, 8195/em-space
  return-if result
  result <- equal c, 8196/three-per-em-space
  return-if result
  result <- equal c, 8197/four-per-em-space
  return-if result
  result <- equal c, 8198/six-per-em-space
  return-if result
  result <- equal c, 8199/figure-space
  return-if result
  result <- equal c, 8200/punctuation-space
  return-if result
  result <- equal c, 8201/thin-space
  return-if result
  result <- equal c, 8202/hair-space
  return-if result
  result <- equal c, 8206/left-to-right
  return-if result
  result <- equal c, 8207/right-to-left
  return-if result
  result <- equal c, 8232/line-separator
  return-if result
  result <- equal c, 8233/paragraph-separator
  return-if result
  result <- equal c, 8239/narrow-no-break-space
  return-if result
  result <- equal c, 8287/medium-mathematical-space
  return-if result
  result <- equal c, 12288/ideographic-space
]

def trim s:text -> result:text [
  local-scope
  load-inputs
  len:num <- length *s
  # left trim: compute start
  start:num <- copy 0
  {
    {
      at-end?:bool <- greater-or-equal start, len
      break-unless at-end?
      result <- new character:type, 0
      return
    }
    curr:char <- index *s, start
    whitespace?:bool <- space? curr
    break-unless whitespace?
    start <- add start, 1
    loop
  }
  # right trim: compute end
  end:num <- subtract len, 1
  {
    not-at-start?:bool <- greater-than end, start
    assert not-at-start?, [end ran up against start]
    curr:char <- index *s, end
    whitespace?:bool <- space? curr
    break-unless whitespace?
    end <- subtract end, 1
    loop
  }
  # result = new character[end+1 - start]
  new-len:num <- subtract end, start, -1
  result:text <- new character:type, new-len
  # copy the untrimmed parts between start and end
  i:num <- copy start
  j:num <- copy 0
  {
    # while i <= end
    done?:bool <- greater-than i, end
    break-if done?
    # result[j] = s[i]
    src:char <- index *s, i
    *result <- put-index *result, j, src
    i <- add i, 1
    j <- add j, 1
    loop
  }
]

scenario trim-unmodified [
  local-scope
  x:text <- new [abc]
  run [
    y:text <- trim x
    1:@:char/raw <- copy *y
  ]
  memory-should-contain [
    1:array:character <- [abc]
  ]
]

scenario trim-left [
  local-scope
  x:text <- new [  abc]
  run [
    y:text <- trim x
    1:@:char/raw <- copy *y
  ]
  memory-should-contain [
    1:array:character <- [abc]
  ]
]

scenario trim-right [
  local-scope
  x:text <- new [abc  ]
  run [
    y:text <- trim x
    1:@:char/raw <- copy *y
  ]
  memory-should-contain [
    1:array:character <- [abc]
  ]
]

scenario trim-left-right [
  local-scope
  x:text <- new [  abc   ]
  run [
    y:text <- trim x
    1:@:char/raw <- copy *y
  ]
  memory-should-contain [
    1:array:character <- [abc]
  ]
]

scenario trim-newline-tab [
  local-scope
  x:text <- new [	abc
]
  run [
    y:text <- trim x
    1:@:char/raw <- copy *y
  ]
  memory-should-contain [
    1:array:character <- [abc]
  ]
]

def find-next text:text, pattern:char, idx:num -> next-index:num [
  local-scope
  load-inputs
  len:num <- length *text
  {
    eof?:bool <- greater-or-equal idx, len
    break-if eof?
    curr:char <- index *text, idx
    found?:bool <- equal curr, pattern
    break-if found?
    idx <- add idx, 1
    loop
  }
  return idx
]

scenario text-find-next [
  local-scope
  x:text <- new [a/b]
  run [
    10:num/raw <- find-next x, 47/slash, 0/start-index
  ]
  memory-should-contain [
    10 <- 1
  ]
]

scenario text-find-next-empty [
  local-scope
  x:text <- new []
  run [
    10:num/raw <- find-next x, 47/slash, 0/start-index
  ]
  memory-should-contain [
    10 <- 0
  ]
]

scenario text-find-next-initial [
  local-scope
  x:text <- new [/abc]
  run [
    10:num/raw <- find-next x, 47/slash, 0/start-index
  ]
  memory-should-contain [
    10 <- 0  # prefix match
  ]
]

scenario text-find-next-final [
  local-scope
  x:text <- new [abc/]
  run [
    10:num/raw <- find-next x, 47/slash, 0/start-index
  ]
  memory-should-contain [
    10 <- 3  # suffix match
  ]
]

scenario text-find-next-missing [
  local-scope
  x:text <- new [abcd]
  run [
    10:num/raw <- find-next x, 47/slash, 0/start-index
  ]
  memory-should-contain [
    10 <- 4  # no match
  ]
]

scenario text-find-next-invalid-index [
  local-scope
  x:text <- new [abc]
  run [
    10:num/raw <- find-next x, 47/slash, 4/start-index
  ]
  memory-should-contain [
    10 <- 4  # no change
  ]
]

scenario text-find-next-first [
  local-scope
  x:text <- new [ab/c/]
  run [
    10:num/raw <- find-next x, 47/slash, 0/start-index
  ]
  memory-should-contain [
    10 <- 2  # first '/' of multiple
  ]
]

scenario text-find-next-second [
  local-scope
  x:text <- new [ab/c/]
  run [
    10:num/raw <- find-next x, 47/slash, 3/start-index
  ]
  memory-should-contain [
    10 <- 4  # second '/' of multiple
  ]
]

# search for a pattern of multiple characters
# fairly dumb algorithm
def find-next text:text, pattern:text, idx:num -> next-index:num [
  local-scope
  load-inputs
  first:char <- index *pattern, 0
  # repeatedly check for match at current idx
  len:num <- length *text
  {
    # does some unnecessary work checking even when there isn't enough of text left
    done?:bool <- greater-or-equal idx, len
    break-if done?
    found?:bool <- match-at text, pattern, idx
    break-if found?
    idx <- add idx, 1
    # optimization: skip past indices that definitely won't match
    idx <- find-next text, first, idx
    loop
  }
  return idx
]

scenario find-next-text-1 [
  local-scope
  x:text <- new [abc]
  y:text <- new [bc]
  run [
    10:num/raw <- find-next x, y, 0
  ]
  memory-should-contain [
    10 <- 1
  ]
]

scenario find-next-text-2 [
  local-scope
  x:text <- new [abcd]
  y:text <- new [bc]
  run [
    10:num/raw <- find-next x, y, 1
  ]
  memory-should-contain [
    10 <- 1
  ]
]

scenario find-next-no-match [
  local-scope
  x:text <- new [abc]
  y:text <- new [bd]
  run [
    10:num/raw <- find-next x, y, 0
  ]
  memory-should-contain [
    10 <- 3  # not found
  ]
]

scenario find-next-suffix-match [
  local-scope
  x:text <- new [abcd]
  y:text <- new [cd]
  run [
    10:num/raw <- find-next x, y, 0
  ]
  memory-should-contain [
    10 <- 2
  ]
]

scenario find-next-suffix-match-2 [
  local-scope
  x:text <- new [abcd]
  y:text <- new [cde]
  run [
    10:num/raw <- find-next x, y, 0
  ]
  memory-should-contain [
    10 <- 4  # not found
  ]
]

# checks if pattern matches at index 'idx'
def match-at text:text, pattern:text, idx:num -> result:bool [
  local-scope
  load-inputs
  pattern-len:num <- length *pattern
  # check that there's space left for the pattern
  x:num <- length *text
  x <- subtract x, pattern-len
  enough-room?:bool <- lesser-or-equal idx, x
  return-unless enough-room?, false/not-found
  # check each character of pattern
  pattern-idx:num <- copy 0
  {
    done?:bool <- greater-or-equal pattern-idx, pattern-len
    break-if done?
    c:char <- index *text, idx
    exp:char <- index *pattern, pattern-idx
    match?:bool <- equal c, exp
    return-unless match?, false/not-found
    idx <- add idx, 1
    pattern-idx <- add pattern-idx, 1
    loop
  }
  return true/found
]

scenario match-at-checks-pattern-at-index [
  local-scope
  x:text <- new [abc]
  y:text <- new [ab]
  run [
    10:bool/raw <- match-at x, y, 0
  ]
  memory-should-contain [
    10 <- 1  # match found
  ]
]

scenario match-at-reflexive [
  local-scope
  x:text <- new [abc]
  run [
    10:bool/raw <- match-at x, x, 0
  ]
  memory-should-contain [
    10 <- 1  # match found
  ]
]

scenario match-at-outside-bounds [
  local-scope
  x:text <- new [abc]
  y:text <- new [a]
  run [
    10:bool/raw <- match-at x, y, 4
  ]
  memory-should-contain [
    10 <- 0  # never matches
  ]
]

scenario match-at-empty-pattern [
  local-scope
  x:text <- new [abc]
  y:text <- new []
  run [
    10:bool/raw <- match-at x, y, 0
  ]
  memory-should-contain [
    10 <- 1  # always matches empty pattern given a valid index
  ]
]

scenario match-at-empty-pattern-outside-bound [
  local-scope
  x:text <- new [abc]
  y:text <- new []
  run [
    10:bool/raw <- match-at x, y, 4
  ]
  memory-should-contain [
    10 <- 0  # no match
  ]
]

scenario match-at-empty-text [
  local-scope
  x:text <- new []
  y:text <- new [abc]
  run [
    10:bool/raw <- match-at x, y, 0
  ]
  memory-should-contain [
    10 <- 0  # no match
  ]
]

scenario match-at-empty-against-empty [
  local-scope
  x:text <- new []
  run [
    10:bool/raw <- match-at x, x, 0
  ]
  memory-should-contain [
    10 <- 1  # matches because pattern is also empty
  ]
]

scenario match-at-inside-bounds [
  local-scope
  x:text <- new [abc]
  y:text <- new [bc]
  run [
    10:bool/raw <- match-at x, y, 1
  ]
  memory-should-contain [
    10 <- 1  # match
  ]
]

scenario match-at-inside-bounds-2 [
  local-scope
  x:text <- new [abc]
  y:text <- new [bc]
  run [
    10:bool/raw <- match-at x, y, 0
  ]
  memory-should-contain [
    10 <- 0  # no match
  ]
]

def split s:text, delim:char -> result:&:@:text [
  local-scope
  load-inputs
  # empty text? return empty array
  len:num <- length *s
  {
    empty?:bool <- equal len, 0
    break-unless empty?
    result <- new {(address array character): type}, 0
    return
  }
  # count #pieces we need room for
  count:num <- copy 1  # n delimiters = n+1 pieces
  idx:num <- copy 0
  {
    idx <- find-next s, delim, idx
    done?:bool <- greater-or-equal idx, len
    break-if done?
    idx <- add idx, 1
    count <- add count, 1
    loop
  }
  # allocate space
  result <- new {(address array character): type}, count
  # repeatedly copy slices start..end until delimiter into result[curr-result]
  curr-result:num <- copy 0
  start:num <- copy 0
  {
    # while next delim exists
    done?:bool <- greater-or-equal start, len
    break-if done?
    end:num <- find-next s, delim, start
    # copy start..end into result[curr-result]
    dest:text <- copy-range s, start, end
    *result <- put-index *result, curr-result, dest
    # slide over to next slice
    start <- add end, 1
    curr-result <- add curr-result, 1
    loop
  }
]

scenario text-split-1 [
  local-scope
  x:text <- new [a/b]
  run [
    y:&:@:text <- split x, 47/slash
    10:num/raw <- length *y
    a:text <- index *y, 0
    b:text <- index *y, 1
    20:@:char/raw <- copy *a
    30:@:char/raw <- copy *b
  ]
  memory-should-contain [
    10 <- 2  # length of result
    20:array:character <- [a]
    30:array:character <- [b]
  ]
]

scenario text-split-2 [
  local-scope
  x:text <- new [a/b/c]
  run [
    y:&:@:text <- split x, 47/slash
    10:num/raw <- length *y
    a:text <- index *y, 0
    b:text <- index *y, 1
    c:text <- index *y, 2
    20:@:char/raw <- copy *a
    30:@:char/raw <- copy *b
    40:@:char/raw <- copy *c
  ]
  memory-should-contain [
    10 <- 3  # length of result
    20:array:character <- [a]
    30:array:character <- [b]
    40:array:character <- [c]
  ]
]

scenario text-split-missing [
  local-scope
  x:text <- new [abc]
  run [
    y:&:@:text <- split x, 47/slash
    10:num/raw <- length *y
    a:text <- index *y, 0
    20:@:char/raw <- copy *a
  ]
  memory-should-contain [
    10 <- 1  # length of result
    20:array:character <- [abc]
  ]
]

scenario text-split-empty [
  local-scope
  x:text <- new []
  run [
    y:&:@:text <- split x, 47/slash
    10:num/raw <- length *y
  ]
  memory-should-contain [
    10 <- 0  # empty result
  ]
]

scenario text-split-empty-piece [
  local-scope
  x:text <- new [a/b//c]
  run [
    y:&:@:text <- split x:text, 47/slash
    10:num/raw <- length *y
    a:text <- index *y, 0
    b:text <- index *y, 1
    c:text <- index *y, 2
    d:text <- index *y, 3
    20:@:char/raw <- copy *a
    30:@:char/raw <- copy *b
    40:@:char/raw <- copy *c
    50:@:char/raw <- copy *d
  ]
  memory-should-contain [
    10 <- 4  # length of result
    20:array:character <- [a]
    30:array:character <- [b]
    40:array:character <- []
    50:array:character <- [c]
  ]
]

def split-first text:text, delim:char -> x:text, y:text [
  local-scope
  load-inputs
  # empty text? return empty texts
  len:num <- length *text
  {
    empty?:bool <- equal len, 0
    break-unless empty?
    x:text <- new []
    y:text <- new []
    return
  }
  idx:num <- find-next text, delim, 0
  x:text <- copy-range text, 0, idx
  idx <- add idx, 1
  y:text <- copy-range text, idx, len
]

scenario text-split-first [
  local-scope
  x:text <- new [a/b]
  run [
    y:text, z:text <- split-first x, 47/slash
    10:@:char/raw <- copy *y
    20:@:char/raw <- copy *z
  ]
  memory-should-contain [
    10:array:character <- [a]
    20:array:character <- [b]
  ]
]

def copy-range buf:text, start:num, end:num -> result:text [
  local-scope
  load-inputs
  # if end is out of bounds, trim it
  len:num <- length *buf
  end:num <- min len, end
  # allocate space for result
  len <- subtract end, start
  result:text <- new character:type, len
  # copy start..end into result[curr-result]
  src-idx:num <- copy start
  dest-idx:num <- copy 0
  {
    done?:bool <- greater-or-equal src-idx, end
    break-if done?
    src:char <- index *buf, src-idx
    *result <- put-index *result, dest-idx, src
    src-idx <- add src-idx, 1
    dest-idx <- add dest-idx, 1
    loop
  }
]

scenario copy-range-works [
  local-scope
  x:text <- new [abc]
  run [
    y:text <- copy-range x, 1, 3
    1:@:char/raw <- copy *y
  ]
  memory-should-contain [
    1:array:character <- [bc]
  ]
]

scenario copy-range-out-of-bounds [
  local-scope
  x:text <- new [abc]
  run [
    y:text <- copy-range x, 2, 4
    1:@:char/raw <- copy *y
  ]
  memory-should-contain [
    1:array:character <- [c]
  ]
]

scenario copy-range-out-of-bounds-2 [
  local-scope
  x:text <- new [abc]
  run [
    y:text <- copy-range x, 3, 3
    1:@:char/raw <- copy *y
  ]
  memory-should-contain [
    1:array:character <- []
  ]
]

def parse-whole-number in:text -> out:num, error?:bool [
  local-scope
  load-inputs
  out <- copy 0
  result:num <- copy 0  # temporary location
  i:num <- copy 0
  len:num <- length *in
  {
    done?:bool <- greater-or-equal i, len
    break-if done?
    c:char <- index *in, i
    x:num <- character-to-code c
    digit:num, error?:bool <- character-code-to-digit x
    return-if error?
    result <- multiply result, 10
    result <- add result, digit
    i <- add i, 1
    loop
  }
  # no error; all digits were valid
  out <- copy result
]

# (contributed by Ella Couch)
recipe character-code-to-digit character-code:number -> result:number, error?:boolean [
  local-scope
  load-inputs
  result <- copy 0
  error? <- lesser-than character-code, 48  # '0'
  return-if error?
  error? <- greater-than character-code, 57  # '9'
  return-if error?
  result <- subtract character-code, 48
]

scenario character-code-to-digit-contain-only-digit [
  local-scope
  a:number <- copy 48  # character code for '0'
  run [
    10:number/raw, 11:boolean/raw <- character-code-to-digit a
  ]
  memory-should-contain [
    10 <- 0
    11 <- 0  # no error
  ]
]

scenario character-code-to-digit-contain-only-digit-2 [
  local-scope
  a:number <- copy 57  # character code for '9'
  run [
    1:number/raw, 2:boolean/raw <- character-code-to-digit a
  ]
  memory-should-contain [
    1 <- 9
    2 <- 0  # no error
  ]
]

scenario character-code-to-digit-handles-codes-lower-than-zero [
  local-scope
  a:number <- copy 47
  run [
    10:number/raw, 11:boolean/raw <- character-code-to-digit a
  ]
  memory-should-contain [
    10 <- 0
    11 <- 1  # error
  ]
]

scenario character-code-to-digit-handles-codes-larger-than-nine [
  local-scope
  a:number <- copy 58
  run [
    10:number/raw, 11:boolean/raw <- character-code-to-digit a
  ]
  memory-should-contain [
    10 <- 0
    11 <- 1  # error
  ]
]