-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtm.sh
690 lines (577 loc) · 19.4 KB
/
tm.sh
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
#!/bin/bash
# Author : Austin Voecks
# Program: tm.sh
# Turning Machine in Bash, uses Brainf$$k syntax
# + : increment current position on tape
# - : decrement current position on tape
# > : move tape position once to the right
# < : move tape position once to the left
# [ : starts a loop, body entered when position value is non zero
# ] : denotes the end of a loop
# . : prints ascii value of current position
# , : saves input from user to current position
set -o pipefail
# =========================================
# GLOBALS
# =========================================
declare -a chars # array of characters, input
declare -a tape # array of integers, memory
declare -a stack # array of integers, call stack
declare -a profiler # array of integers, instruction accounting
export tape_pos=0 # integer, our current position on the tape
export char_pos=0 # integer, our current position in the input
export brace_depth=0 # integer, number of nested braces
export stack_size=0 # integer, size of the stack
export green=\\0"33[01;32m"
export normal=\\0"033[00m"
# =========================================
# UTILITY
# =========================================
usage() {
# shows usage information
echo "
usage: bash tm.sh [OPTION ...] (input file | program string)
-c --compile no execution, write parsed, optimized program to file
-h --help show help information
-i --max_iter x number of operations to run before early stopping
-O --Optimize apply advanced, heavy optimizations
-o --optimize apply basic optimizations
-p --print print out the program before execution
-P --profile show instruction execution information
-q --quiet suppress execution trace
-r --raw treat input as already parsed, use with compiled programs
-S --step only advance execution when user presses enter
-s --stime x sleep for x seconds between operations
"
}
parse_options_and_input() {
# process flags to set run time variables
# options
while [[ $2 ]]; do
case $1 in
-h|--help) usage; exit ;;
-S|--step) step=1 ;;
-s|--stime) shift; stime=$1 ;;
-p|--print) print=1 ;;
-P|--profile) profile=1 ;;
-c|--compile) compile=1 ;;
-r|--raw) raw_input=1 ;;
-q|--quiet) quiet=1 ;;
-o|--optimize) simple_optimize=1 ;;
-O|--Optimize) heavy_optimize=1 ;;
-i|--max_iter) shift; max_iters=$1 ;;
*) usage; exit ;;
esac
shift
done
# input file or program string
case $1 in
''|-h|--help) parse_options_and_input _ --help ;;
*) input="$1"; [[ -e "$1" ]] && input="$(cat "$1")" ;;
esac
}
print_tape() {
# prints the entire tape, marking the current position green
local i; i=0
echo -n "tape : "
while [[ ${tape[$i]} ]]; do
if (( i == tape_pos )); then
printf "%b%s%b" "$green" "${tape[$i]} " "$normal"
else
echo -n "${tape[$i]} "
fi
(( i++ ))
done
echo
}
print_chars() {
# prints the entire input, marking the current position green
local i; i=0
echo -n "chars : "
while [[ ${chars[$i]} ]] ; do
if (( i == char_pos )); then
printf "%b%s%b" "$green" "${chars[$i]} " "$normal"
else
echo -n "${chars[$i]} "
fi
(( i++ ))
done
echo
}
run_profiler() {
# show what percentage of total execution each instruction took
# useful for finding heavily repeated loops
local instruction new_percent old_percent sum_percent b_depth size
instruction=${chars[0]}
old_percent="$( bc -l <<< "${profiler[0]} / $iters * 100" )"
sum_percent=""
b_depth=1
b_change=0
echo
echo " % time : instruction(s)"
echo "----------------------------------------------"
for (( i=1; i < ${#profiler[@]}; i++ )); do
new_percent="$( bc -l <<< "${profiler[$i]} / $iters * 100" )"
# attempt to bundle "run together" strings of instructions together
# "run together" means contiguous instructions with the same frequency
if [[ "$new_percent" == "$old_percent" ]]; then
if [[ -z "$sum_percent" ]]; then
sum_percent="$(bc -l <<< "$old_percent + $new_percent")"
else
sum_percent="$(bc -l <<< "$sum_percent + $new_percent")"
fi
instruction="${instruction}${chars[$i]}"
old_percent="$new_percent"
[[ "${chars[$i]}" == "[" ]] && (( b_change++ ))
[[ "${chars[$i]}" == "]" ]] && (( b_change-- ))
else
(( size=b_depth+${#instruction} ))
if [[ -z "$sum_percent" ]]; then
printf '% 7.2f :% *s\n' "$old_percent" "$size" "$instruction"
else
printf '% 7.2f :% *s\n' "$sum_percent" "$size" "$instruction"
fi
instruction="${chars[$i]}"
old_percent="$new_percent"
sum_percent=""
(( b_depth+=b_change ))
b_change=0
[[ "${chars[$i]}" == "]" ]] && (( b_depth-- ))
[[ "${chars[$i]}" == "[" ]] && (( b_depth++ ))
fi
done
size=$(( b_depth + ${#instruction} ))
if [[ -z "$sum_percent" ]]; then
printf '% 7.2f :% *s\n' "$old_percent" "$size" "$instruction"
else
printf '% 7.2f :% *s\n' "$sum_percent" "$size" "$instruction"
fi
}
shut_down() {
(( execution_started )) && {
# final output
print_tape
(( quiet )) || echo "operations: $iters"
# profiler output
(( profile )) && run_profiler
}
exit
}
# =========================================
# OPTIMIZATION
# =========================================
optimize_moves() {
move_dec='\[-[<|>]\+[+|-]\+[>|<]\+\]' # decrement, move left or right
dec_move='\[[<|>]\+[+|-]\+[>|<]\+-\]' # move, decrement left or right
# recognize move operations, in the form [->>+<<] or [>>+<<-], where the
# number of places moved is variable and saved to use during execution
# [->>>+<<<] -> 3a
# [-<<+>>] -> 2A
#
# extended, includes variable number of increments. which would be a move
# with and a multiply
# [->>+++<<] -> 2a3
# [-<<<++>>>] -> 3A2
while read -r move; do
# escape brackets for sed
move="$(sed -e 's/\[/\\\[/g' -e 's/\]/\\\]/g' <<< "$move" )"
case $(grep -o '[>|<][+|-]\+[<|>]' <<< "${move}" | head -n 1) in
# moving to the right some number of places
# [->>+<<]
'>+<')
places=$(grep -o -- '>' <<< "${move}" | grep -c '>')
tchars=$(sed -e "s/$move/${places}A/g" <<< "${tchars}")
;;
# add many times to the right some number of places
# [->>+++<<]
'>+'*'<')
places=$(grep -o -- '>' <<< "${move}" | grep -c '>')
addition=$(grep -o -- '+' <<< "${move}" | grep -c '+')
tchars=$(sed -e "s/$move/${addition}_${places}A/g" <<< "${tchars}")
;;
# moving to the left some number of places
'<+>')
places=$(grep -o -- '<' <<< "${move}" | grep -c '<')
tchars=$(sed -e "s/$move/${places}a/g" <<< "${tchars}")
;;
# add many times to the left some number of places
'<+'*'>')
places=$(grep -o -- '<' <<< "${move}" | grep -c '<')
addition=$(grep -o -- '+' <<< "${move}" | grep -c '+')
tchars=$(sed -e "s/$move/${addition}_${places}a/g" <<< "${tchars}")
;;
# subtracting to the right some number of places
'>-<')
places=$(grep -o -- '>' <<< "${move}" | grep -c '>')
tchars=$(sed -e "s/$move/${places}S/g" <<< "${tchars}")
;;
# subtracting many times to the right some number of places
'>-'*'<')
places=$(grep -o -- '>' <<< "${move}" | grep -c '>')
subtraction=$(grep -o -- '-' <<< "${move}" | grep -c '-')
(( subtraction-- )) # decrement once for loop decrement
tchars=$(sed -e "s/$move/${subtraction}_${places}S/g" <<< "${tchars}")
;;
# subtracting to the left some number of places
'<->')
places=$(grep -o -- '<' <<< "${move}" | grep -c '<')
tchars=$(sed -e "s/$move/${places}s/g" <<< "${tchars}")
;;
*)
echo "matched: $(
grep -o -- '[>|<][+|-]\+[<|>]' <<< "${move}" | head -n 1)"
;;
esac
done < <(
# shellcheck disable=SC1117
grep -o -- "${move_dec}\|${dec_move}" <<< "${tchars}"
)
}
optimize_copies() {
copy_dec='\[-[>]*\(>+\)\+[<]\+\]'
dec_copy='\[[>]*\(>+\)\+[<]\+\-]'
# recognize copies
# we have to determine the number of copies and where each one is going
while read -r move; do
# escape brackets
move="$(sed -e 's/\[/\\\[/g' -e 's/\]/\\\]/g' <<< "$move" )"
# how many copies
copies=$(grep -o -- '+' <<< "${move}" | grep -c '+')
case $(grep -o -- '+[<|>]' <<< "${move}" | tail -n 1) in
# copying to the right
# the number of copies to make _ how far each copy is from other copies
# _ an offset for the entire copy
# [->+>+<<] -> 2_1_0C
# [->>>+>+<<<<] -> 2_1_2C
'+<')
places=1 #$(grep -o -- '>+' <<< "${move}" | grep -c '>+')
shifts=$(( $(grep -o -- '<' <<< "${move}" | grep -c '<') - copies ))
tchars=$(
sed -e "s/$move/${copies}_${places}_${shifts}C/g" <<< "${tchars}")
;;
# copying to the left
# [-<+<+>>]
'+>')
places=$(grep -o -- '<' <<< "${move}" | grep -c '<')
(( places/=copies ))
tchars=$(sed -e "s/$move/${copies}_${places}c/g" <<< "${tchars}")
;;
*)
echo "fail"
;;
esac
done < <(
# shellcheck disable=SC1117
grep -o -- "$copy_dec\|$dec_copy" <<< "${tchars}"
)
}
apply_heavy_optimizations() {
# heavy optimizations are more complex
optimize_moves
# recognize zeroing
tchars=$(sed -e 's/\[-\]/Z/g' <<< "$tchars")
optimize_copies
}
apply_simple_optimizations() {
# simple optimization recognizes repeated instructions and combines them.
# for example >>>> becomes 4>
# optimize repeated operations (2 or more occurrences)
for operation in '---' '+++' '>>>' '<<<'; do
# replace each match with it's simplified form
while read -r match; do
tchars=$(sed -e "s/$match/${#match}${operation::1}/g" <<< "${tchars}")
done < <(grep -o -- "${operation}*" <<< "${tchars}" | sort -r)
done
}
# =========================================
# MAIN
# =========================================
main() {
local input='' quiet=0 step=0 stime=0 max_iters=1000000 iters=0
local simple_optimize=0 heavy_optimize=0 execution_started=0
local print=0 raw_input=0 compile=0 profile=0 counter=0
local ops='' percent_fewer_instructions=0 percent_speed_up=0
tape[0]=0
parse_options_and_input "$@"
# convert all lines of input to an array of characters
if (( raw_input )); then
tchars="$input"
else
tchars=$(grep -v '^[ ]*#.*' <<< "$input" | # remove comments
xargs -0 | # remove newlines
grep -o . | # separate each character
grep '[]\+\>\<\[\.\,-]' | # remove non-syntax chars
grep -v \\\\ | # remove pesky backslashes
tr -d '\n') # back to one line
fi
plength=${#tchars}
# optimizations
(( heavy_optimize )) && { apply_heavy_optimizations; simple_optimize=1; }
(( simple_optimize )) && apply_simple_optimizations
# optionally print the program and optimizing results
(( print )) && {
echo "program: $tchars"
(( simple_optimize )) && {
ops="$(sed 's/[0-9_]*//g' <<< "${tchars[@]}")"
percent_fewer_instructions="$(
bc -l <<< "(1 - (${#ops} / $plength)) * 100" )"
percent_speed_up="$(
bc -l <<< "(1 / (1 - $percent_fewer_instructions / 100) * 100 - 100)")"
printf "optimized away %.2f%% of instructions; %.0f%% speed up" \
"$percent_fewer_instructions" "$percent_speed_up"
}
echo
}
# compile option writes a new program file for use with the -r option
(( compile )) && {
echo "${tchars}" > "$input".raw
exit
}
# convert tchar string to array for execution
# shellcheck disable=SC2207
chars=( $(grep -o -- '[_0-9]*.' <<< "$tchars") )
# run the program
execution_started=1
while [[ ${chars[$char_pos]:-} && $iters -lt $max_iters ]]; do
(( profiler[char_pos]++ ))
if (( brace_depth > 0 )) ; then
case ${chars[$char_pos]} in
"]") (( brace_depth-- )) ;;
"[") (( brace_depth++ )) ;;
esac
else
(( quiet )) || print_chars
# =========================================
# OPERATIONS
# =========================================
# these are intentionally inlined for performance
case ${chars[$char_pos]} in
# composite add to the left
[0-9]*'_'[0-9]*'a')
# many times
# [-<<+++>>] -> 3_2a
# shellcheck disable=SC2206
op_data=( ${chars[$char_pos]//_/ } )
places=${op_data[1]::-1}
amount=${op_data[0]}
(( amount *= tape[tape_pos] ))
(( tape[tape_pos-places] += amount ))
(( tape[tape_pos] = 0 ))
;;
[0-9]*'a')
# once
# [-<<+>>] 2a
places=${chars[$char_pos]::-1}
(( tape[tape_pos-places] += tape[tape_pos] ))
(( tape[tape_pos] = 0 ))
;;
# composite add to the right
[0-9]*'_'[0-9]*'A')
# many times
# [->>+++<<] -> 3_2A
# shellcheck disable=SC2206
op_data=( ${chars[$char_pos]//_/ } )
places=${op_data[1]::-1}
amount=${op_data[0]}
(( amount *= tape[tape_pos] ))
if (( places > 1 )); then
(( counter = tape_pos + places ))
while [[ -z ${tape[$counter]:-} ]]; do
((
tape[counter] = 0,
counter--
))
done
fi
((
tape[tape_pos + places] += amount,
tape[tape_pos] = 0
))
;;
[0-9]*'A')
# once
# [->>+<<] 2A
places=${chars[$char_pos]::-1}
(( places > 1 )) && {
(( counter=tape_pos+places ))
while [[ -z ${tape[$counter]:-} ]]; do
((
tape[counter] = 0,
counter--
))
done
}
((
tape[tape_pos + places] += tape[tape_pos],
tape[tape_pos] = 0
))
;;
[0-9]*'s')
# composite subtract to the left
((
places = ${chars[$char_pos]::-1},
tape[tape_pos - places] -= tape[tape_pos],
tape[tape_pos] = 0
))
;;
# composite subtract to the right
[0-9]*'_'[0-9]*'S')
# many times
# [->>---<<] -> 3_2S
# shellcheck disable=SC2206
op_data=(${chars[$char_pos]//_/ })
places=${op_data[1]::-1}
amount=${op_data[0]}
(( amount *= tape[tape_pos] ))
if (( places > 1 )); then
(( counter = tape_pos + places ))
while [[ -z ${tape[$counter]:-} ]]; do
((
tape[counter] = 0,
counter--
))
done
fi
((
tape[tape_pos+places] -= amount,
tape[tape_pos]=0
))
;;
[0-9]*'S')
# once
((
places = ${chars[char_pos]::-1},
tape[tape_pos + places] -= tape[tape_pos],
tape[tape_pos] = 0
))
;;
Z)
# composite set this position to zero
# [-] -> Z
(( tape[tape_pos] = 0 ))
;;
[0-9]*'_'[0-9]*'_'[0-9]*C)
# composite copy left
# [->+>+<<] -> 2_1_0C
# [->++>++<<]
# [->>+>+<<<] -> 2_1_1C
# shellcheck disable=SC2206
IFS=_ read -r copies shifts offset <<< "${chars[$char_pos]//C/ }"
(( counter = shifts + offset ))
while (( copies > 0 )); do
((
tape[tape_pos + counter] += tape[tape_pos],
copies--,
counter += shifts
))
done
(( tape[tape_pos] = 0 ))
;;
[0-9]*'+')
# increment this position on the tape many times
# 5+
(( tape[tape_pos] += ${chars[char_pos]::-1} ))
;;
"+")
# increment this position on the tape
# +
(( tape[tape_pos]++ ))
;;
[0-9]*'-')
# - : decrement this position on the tape many times
(( tape[tape_pos] -= ${chars[char_pos]::-1} ))
;;
"-")
# - : decrement this position on the tape
(( tape[tape_pos]-- ))
;;
[0-9]*'>')
# > : shift tape position to the right many times,
# check initialization
((
tape_pos += ${chars[char_pos]::-1},
counter = tape_pos
))
while [[ -z ${tape[counter]} ]]; do
((
tape[counter] = 0,
counter--
))
done
;;
">")
# > : shift tape position to the right once, check initialization
(( tape_pos++ ))
[[ ${tape[$tape_pos]} ]] || (( tape[tape_pos] = 0 ))
;;
[0-9]*'<')
# < : shift tape position to the left many times, check underflow
# (( tape_pos -= ${chars[$char_pos]::-1} ))
(( tape_pos -= ${chars[char_pos]::-1} ))
(( tape_pos < 0 )) && { echo "error: lshift < 0" ; exit; }
;;
"<")
# < : shift tape position to the left once, check if underflow
(( tape_pos-- ))
(( tape_pos < 0 )) && { echo "error: lshift < 0" ; exit; }
;;
"]")
# ] : if the jump stack has any elements, set the current character
# position to the character before the lbrace. This way, we'll
# encounter it as the next character. We then remove that position
# from the jump stack
if (( stack_size > 0 )); then
(( char_pos = stack[stack_size] - 1 ))
unset stack[${stack_size}]
(( stack_size-- ))
fi
;;
"[")
# [ : if the current tape value is greater than zero, save our
# current position on the stack and run the contents of the loop.
# Otherwise, seek to the next rbrace
if (( tape[tape_pos] > 0 )); then
((
stack_size++,
stack[stack_size] = char_pos
))
else
(( brace_depth++ ))
fi
;;
".")
# . : add current position to output
# shellcheck disable=SC2059,SC1117
printf "\x$(printf %x "${tape[$tape_pos]}")"
#output="${output} ${tape[$tape_pos]}"
;;
",")
# , : saves input from user to current position
echo -n "input?> "
read -r value
tape[$tape_pos]=${value}
;;
*)
echo "error: unrecognized instruction: ${chars[$char_pos]}"
exit
;;
esac
# step, sleep, and/or print
(( quiet )) || {
print_tape
if (( step )); then
read -r _
elif [[ $stime != 0 ]]; then
sleep "$stime"
fi
echo
}
fi
(( iters++ ))
char_pos=$(( char_pos + 1 ))
done
(( iters == max_iters )) && echo "iteration maximum reached: $max_iters"
shut_down
}
trap shut_down INT
main "$@"