forsh/f.sh

119 lines
1.4 KiB
Bash
Raw Normal View History

2021-04-15 13:40:48 +02:00
#!/bin/sh
alias :=_newword
2021-04-15 14:09:33 +02:00
alias ']=_execbody'
alias xshift='shift 2>/dev/null || printf "Stack underflow\n"'
2021-04-15 13:40:48 +02:00
_stack="" # top is
_builtin_dictionary="swap dup rot over drop add sub div mod mul put" # + - / * .
_newword() {
name="$1"
shift
2021-04-15 14:09:33 +02:00
eval "${name}_definition=\"$*\""
2021-04-15 13:40:48 +02:00
}
_execword() {
2021-04-15 14:09:33 +02:00
eval "def=\"\$$1_definition\""
eval "def=\"\$$1_definition\""
[ "$def" ] || {
printf '%s\n' "Error: no word $1"
return
}
_execbody $def
}
_execbody() {
for word in "$@"; do
[ "$_debug" ] && {
printf 'word %s\nstack %s\n' "$word" "$_stack"
read
}
2021-04-15 13:40:48 +02:00
case "$_builtin_dictionary" in
2021-04-15 14:09:33 +02:00
*"$word"*) "_$word" $_stack ;;
*) case "$word" in
*[0-9]*) _stack="$word $_stack" ;;
*) _execword "$word" ;;
esac
;;
2021-04-15 13:40:48 +02:00
esac
done
}
_swap() {
one="$1"
two="$2"
2021-04-15 14:09:33 +02:00
xshift
2021-04-15 13:40:48 +02:00
_stack="$2 $1 $*"
}
_dup() {
_stack="$1 $*"
}
_rot() {
one="$1"
two="$2"
thr="$3"
2021-04-15 14:09:33 +02:00
xshift
xshift
xshift
2021-04-15 13:40:48 +02:00
_stack="$3 $1 $2 $*"
}
_over() {
_stack="$2 $*"
}
_drop() {
2021-04-15 14:09:33 +02:00
xshift
2021-04-15 13:40:48 +02:00
_stack="$*"
}
_add() {
one="$1"
two="$2"
2021-04-15 14:09:33 +02:00
xshift
xshift
2021-04-15 13:40:48 +02:00
_stack="$(( one + two )) $*"
}
_sub() {
one="$1"
two="$2"
2021-04-15 14:09:33 +02:00
xshift
xshift
2021-04-15 13:40:48 +02:00
_stack="$(( two - one )) $*"
}
_div() {
one="$1"
two="$2"
2021-04-15 14:09:33 +02:00
xshift
xshift
2021-04-15 13:40:48 +02:00
_stack="$(( two / one )) $*"
}
_mod() {
one="$1"
two="$2"
2021-04-15 14:09:33 +02:00
xshift
xshift
2021-04-15 13:40:48 +02:00
_stack="$(( two % one )) $*"
}
_mul() {
one="$1"
two="$2"
2021-04-15 14:09:33 +02:00
xshift
xshift
2021-04-15 13:40:48 +02:00
_stack="$(( one * two )) $*"
}
_put() {
one="$1"
2021-04-15 14:09:33 +02:00
xshift
2021-04-15 13:40:48 +02:00
printf '%s \n' "$one"
_stack="$*"
}