diff --git a/f.sh b/f.sh index 30532d9..6986105 100644 --- a/f.sh +++ b/f.sh @@ -1,25 +1,41 @@ #!/bin/sh alias :=_newword -alias '(=:' -alias ')=;' +alias ']=_execbody' +alias xshift='shift 2>/dev/null || printf "Stack underflow\n"' _stack="" # top is _builtin_dictionary="swap dup rot over drop add sub div mod mul put" # + - / * . -_dictionary= _newword() { name="$1" shift - export "\$${name}_definition=\"$*\"" + eval "${name}_definition=\"$*\"" } _execword() { - eval "def='$1_definition'" - for word in $def; do + 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 + } case "$_builtin_dictionary" in - *"$word"*) "_$word" "$_stack" ;; - *) _execword "$word" ;; + *"$word"*) "_$word" $_stack ;; + *) case "$word" in + *[0-9]*) _stack="$word $_stack" ;; + *) _execword "$word" ;; + esac + ;; esac done } @@ -27,7 +43,7 @@ _execword() { _swap() { one="$1" two="$2" - shift + xshift _stack="$2 $1 $*" } @@ -39,7 +55,9 @@ _rot() { one="$1" two="$2" thr="$3" - shift 3 + xshift + xshift + xshift _stack="$3 $1 $2 $*" } @@ -48,48 +66,53 @@ _over() { } _drop() { - shift + xshift _stack="$*" } _add() { one="$1" two="$2" - shift 2 + xshift + xshift _stack="$(( one + two )) $*" } _sub() { one="$1" two="$2" - shift 2 + xshift + xshift _stack="$(( two - one )) $*" } _div() { one="$1" two="$2" - shift 2 + xshift + xshift _stack="$(( two / one )) $*" } _mod() { one="$1" two="$2" - shift 2 + xshift + xshift _stack="$(( two % one )) $*" } _mul() { one="$1" two="$2" - shift 2 + xshift + xshift _stack="$(( one * two )) $*" } _put() { one="$1" - shift + xshift printf '%s \n' "$one" _stack="$*" }